How to upload image file on codeigniter 3? - file-upload

I've tried everything to code upload the image file but I still stuck and it keeps an error. It can't detect the data of the image file so it can't store to the database when I submitted the form. I saw every tutorial I've been searched and look into my code seems everything right but why it still keeps an error.
Controller
public function create()
{
if (!$this->session->userdata('user_logged')) {
redirect('Auth');
}
$data["title"] = "Form Create Blog";
$data["landingpage"] = false;
$data['content'] = 'component/admin/blog/blog_create';
$this->form_validation->set_rules('blogTitle', 'Title tidak boleh kosong', 'required|max_length[50]');
$this->form_validation->set_rules('blogHeaderImg', 'Header Image tidak boleh kosong', 'required');
$this->form_validation->set_rules('blogKeyword', 'Keyword tidak boleh kosong', 'required|max_length[50]');
$this->form_validation->set_rules('blogContent', 'Content tidak boleh kosong', 'required');
if ($this->form_validation->run() == FALSE) {
$this->load->view('index', $data);
} else {
$config['upload_path'] = realpath(APPPATH . '../assets/img/upload/blog/header_image');
$config['allowed_types'] = 'jpg|png|PNG';
$nmfile = time() . "_" . $_FILES['blogHeaderImg']['name'];
$config['file_name'] = $nmfile;
$this->load->library('upload', $config);
if (!$this->upload->do_upload("blogHeaderImg")) {
$error = array('error' => $this->upload->display_errors());
echo '<div class="alert alert-danger">' . $error['error'] . '</div>';
} else {
$data = array('upload_data' => $this->upload->data());
$header_image = $data['upload_data']['file_name'];
$this->M_Blog->storeBlogData($header_image);
print_r($_FILES['blogHeaderImg']);
$this->session->set_flashdata('flashAddBlog', 'Data berhasil <strong>ditambahkan</strong>');
redirect('blog');
}
}
}
Model
public function storeBlogData($header_image)
{
$data = [
'title' => $this->input->post('blogTitle', TRUE),
'header_image' => $header_image,
'content' => $this->input->post('blogContent', TRUE),
'blog_keyword' => $this->input->post('blogKeyword', TRUE),
'created_by' => $this->session->userdata('user_logged')->id,
'last_modified_by' => $this->session->userdata('user_logged')->id,
'is_deleted' => 'n'
];
$this->db->insert('blog', $data);
}
View
<form method="POST" action="create" enctype="multipart/form-data">
<div class="form-group">
<label for="blogTitle">Title</label>
<input class="form-control" type="text" name="blogTitle" id="blogTitle" placeholder="Title">
<small class="form-text text-danger"><?= form_error('blogTitle') ?></small>
</div>
<div class="form-group">
<label for="blogHeaderImg">Header Image</label>
<input class="form-control-file" type="file" id="blogHeaderImg" name="blogHeaderImg">
<small class="form-text text-danger"><?= form_error('blogHeaderImg') ?></small>
</div>
<div class="form-group">
<label for="blogKeyword">Keyword</label>
<input class="form-control" type="text" id="blogKeyword" name="blogKeyword" placeholder="Keyword">
<small class="form-text text-danger"><?= form_error('blogKeyword') ?></small>
</div>
<div class="form-group">
<label for="blogContent">Content</label>
<textarea class="form-control" type="text" id="blogContent" name="blogContent" placeholder="Content" rows="10"></textarea>
<small class="form-text text-danger"><?= form_error('blogContent') ?></small>
</div>
<button class="btn btn-primary" type="submit">Submit</button>
</form>

already solved. I just have to add this code to blog controller
if (empty($_FILES['blogHeaderImg']['name'])) {
$this->form_validation->set_rules('blogHeaderImg', 'Document', 'required');
}
instead of using this code
$this->form_validation->set_rules('blogHeaderImg', 'Header Image tidak boleh kosong', 'required');
thank you

Related

Retrive ids and check related boxes

Using
Laravel 8.54
Livewire 2.6
Laratrust package for roles and permissions
I want to edit the permissions role like that
RolesEdit.php (livewire component)
<?php
namespace App\Http\Livewire\Admin\Roles;
use App\Models\Role;
use Livewire\Component;
use App\Models\Permission;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Validator;
class RolesEdit extends Component
{
public $data = [];
public $role;
public $selectedIds = [];
public function mount(Role $role)
{
$this->role = $role;
$this->data = $role->toArray();
}
public function update()
{
$this->data['permissions'] = $this->selectedIds;
$validated = Arr::except($this->validatedData(), ['permissions']);
$this->role->update($validated);
$this->role->permissions()->sync($this->data['permissions']);
}
public function validatedData()
{
return Validator::make($this->data, [
'display_name' => 'required',
'description' => 'required',
"permissions" => "required|array|min:1",
"permissions.*" => "required|distinct|min:1",
])->validate();
}
public function render()
{
$permissions = Permission::all();
return view('livewire.admin.roles.roles-edit', compact('permissions'));
}
}
Roles-edit.blade.php
<div class="mt-1">
<label class="form-label">{{ __('site.display_name') }}</label>
<input wire:model="data.display_name" type="text" class="form-control" placeholder="Enter role name" />
</div>
<div class="mt-1">
<label class="form-label">{{ __('site.role_description') }}</label>
<textarea wire:model="data.description" type="text" class="form-control"
placeholder="Enter Description"></textarea>
</div>
<div class="row w-100">
#foreach ($permissions as $permission)
<div class="col-md-3">
<div class="form-check ms-5">
<input wire:model.defer="selectedIds" class="form-check-input" id="{{ $permission->name }}"
value="{{ $permission->id }}" type="checkbox"
{{ $role->permissions->contains($permission->id) ? 'checked' : '' }} />
<label class="form-check-label" for="{{ $permission->name }}">
{{ $permission->display_name }}</label>
</div>
</div>
#endforeach
</div>
When I open roles-edit view I want to check boxes that have $permission->id related to role so I use
{{ $role->permissions->contains($permission->id) ? 'checked' : '' }}
But it did not work … all checkboxes is unchecked
instead using code:
{{ $role->permissions->contains($permission->id) ? 'checked' : '' }}
try this
#if($role->permissions->contains($permission->id)) checked #endif
also try to add wire:key directive to the parent div of the input element
<div class="form-check ms-5" wire:key="input-checkbox-{{ $permission->id }}">
I suggest you, create an array to retrieve the permissions ids of the role
public $permissionsIds = [];
public function mount(Role $role)
{
$this->role = $role;
$this->data = $role->toArray();
$this->permissionsIds = $this->role->permissions()->pluck('id');
}
// in blade
#if(in_array($permission->id,$permissionsIds)) checked #endif

How to save category in laravel 5.7 with vue.js

Using Laravel 5.7 with vuejs, I am trying to display parent_id from a MySQL categories table. I want to pass the name and get all it's child categories irrespective of the parent.
My blade
<form action="{{ route('categories.store') }}" method="post">
#csrf
<div class="form-group">
<label for="name">name:</label>
<input type="text" id="name" class="form-control" v-model="name">
</div>
<div class="form-group">
<label for="sub_category">category</label>
<select id="sub_category" v-model="parent_id" class="form-control">
<option data-display="main category" value="0">main category</option>
<option v-for="category in categories" :value="category.id">#{{ category.name }}</option>
</select>
</div>
<div class="form-group">
<button type="button" #click="addCategory()" class="btn btn-info">save</button>
</div>
</form>
web.php
Route::group(['namespace' => 'Admin', 'prefix' => 'admin'],function (){
$this->get('panel', 'PanelController#index')->name('panel.index');
$this->resource('categories', 'CategoryController');
});
My vue
addCategory: function () {
axios.post(route('categories.store'), {
name: this.name,
parent_id: this.parent_id,
}).then(response => {
this.categories.push({'name': response.data.name, 'id': response.data.id});
}, response => {
this.error = 1;
console.log('Errors');
});
}
CategoryController
public function store(Request $request)
{
$category = new Category();
$category->name = $request->name;
$category->parent_id = $request->parent_id;
if ($category->save()) {
return $category;
}
}
I see this error in console for first
Too
And I get 405 error.
Remove #click from submit buttom.
Remove route... from form action and set it #
Add #submit="addCategory()" to the form
In the axios.post samply add the route without route function.
Update:
If you want to prevent page refreshing, add .prevent after #submit.

Laravel 5.7 Auth::attempt return false

Auth::attempt always return false , can't understand why .
web.php
Route::post('/login','SessionsController#store');
Route::post('/register','RegisterController#store');
RegisterController.php
public function store()
{
$this->validate(\request(),[
'name' => 'bail|required|min:3|max:30|string',
'email' => 'bail|required|email',
'password' => 'required|confirmed'
]);
$user = User::create(request(['name','email','password']));
$user->fill([
'password' => Hash::make(\request()->newPassword)
])->save();
auth()->login($user);
return redirect()->home();
}
SessionsController.php
public function store(Request $request)
{
$credentials = $request->only('email', 'password');
if (! Auth::attempt($credentials)) {
return back()->withErrors(['message'=>'Email and Password doesn\'t match']);
}
return redirect()->home();
}
create.blade.php (Login Page)
<form action="/login" method="post">
#csrf
<div class="form-group">
<label for="email" class="form-text">Email :</label>
<input type="email" id="email" name="email" class="form-control" required>
</div>
<div class="form-group">
<label for="password" class="form-text" >Password :</label>
<input type="password" class="form-control" id="password" name="password" required>
</div>
<input type="submit" class="btn btn-primary float-right" value="Register">
</form>
Every thing is okay with registration and database , passwords is hashed .
Auth::attempt always return false .
Can't understand why , posted it after few hours of searching .. most of code is just copied from documentation.
Thanks in advance.
just changing
$user = User::create(request(['name','email','password']));
$user->fill([
'password' => Hash::make(\request()->newPassword)
])->save();
to
$user = User::create([
'name' => request('name'),
'email' => request('email'),
'password' => bcrypt(request('password'))
]);

Custom multilingual inputs - opencart

What is the pattern for creating a multilingual input in opencart for admin side.
For example I want to have two List Description Limit inputs, one for each language.
Like in this image. So I can control from admin side the list limit for every language.
Currently I use this pattern to create a custom input, but this is not language dependent:
File: admin/view/template/extension/theme/theme_default.tpl
<fieldset>
<div class="form-group required">
<label class="col-sm-2 control-label" for="inputId"><span data-toggle="tooltip" title="<?php echo $help_inputName; ?>"><?php echo $label_inputName; ?></span></label>
<div class="col-sm-10">
<input type="text" name="theme_default_inputName" value="<?php echo $theme_default_inputName; ?>" placeholder="<?php echo $label_inputName; ?>" id="inputId" class="form-control" />
<?php if ($error_inputName) { ?>
<div class="text-danger"><?php echo $error_inputName; ?></div>
<?php } ?>
</div>
</div>
</fieldset>
File: admin/language/en-gb/extension/theme/theme_default.php
//Language strings
$_['help_inputName'] = 'helpTxt';
$_['label_inputName'] = 'labelForInput';
$_['error_inputName'] = 'errorForInput';
File: admin/controller/extension/theme/theme_default.php
//Language strings
$text_strings = array(
'help_inputName',
'label_inputName',
'error_inputName'
);
foreach ($text_strings as $text) {
$data[$text] = $this->language->get($text);
}
//Error handling
if (isset($this->error['inputName'])) {
$data['error_inputName'] = $this->error['inputName'];
} else {
$data['error_inputName'] = '';
}
//Custom field
if (isset($this->request->post['theme_default_inputName'])) {
$data['theme_default_inputName'] = $this->request->post['theme_default_inputName'];
} elseif (isset($setting_info['theme_default_inputName'])) {
$data['theme_default_inputName'] = $setting_info['theme_default_inputName'];
} else {
$data['theme_default_inputName'] = "customText";
}
//Validation
if (!$this->request->post['theme_default_inputName']) {
$this->error['inputName'] = $this->language->get('error_inputName');
}

Forms in Pop yii

I tried to insert a form in Pop up..I used the partial method to redirect it.
I written the pop up code in my controller action.
And I need to insert a form there which I created through GII.
A got an out put but the form is outside the Pop Up..
Can anybody tell me hoe can I Achieve this....
Controller
public function actionpopup($id)
{
//$this->render('/offerEvents/Details',array(
//'model'=>OfferEvents::model()->findByAttributes(array('id'=>$id)), ));
$OfferEventsList = OfferEvents::model()->findAllByAttributes(array('id' => $id));
foreach($OfferEventsList as $Listdata)
{ $titnw=$Listdata['title']; $details=$Listdata['description'];
$discountper=$Listdata['discountper']; $discountperamt=$Listdata['discountperamt'];
$strdaate=$Listdata['startdate']; $enddaate=$Listdata['enddate']; $evoftype=$Listdata['type']; }
$cmuserid=$Listdata['createdby'];
if($Listdata['createdby']==0){ $createdbyname="Admin"; } else { $createdbyname=$Listdata->company->companyname; }
$locationnw=$Listdata->location;
$offrimage=$Listdata->image;
if($offrimage!=""){ $imgUrls=$offrimage; } else { $imgUrls='image-not-available.png'; }
$infowinimgpaths='theme/images/OfferEvents/orginal/'.$imgUrls;
if (file_exists($infowinimgpaths)) { $infowinimgpathSrcs=Yii::app()->baseUrl.'/'.$infowinimgpaths; } else
{ $infowinimgpathSrcs=Yii::app()->baseUrl.'/theme/images/OfferEvents/image-not-available.png'; }
if (Yii::app()->user->id!='' && Yii::app()->user->id!=1){
$subcribeemailid=Yii::app()->user->email; $logsts=1;
$countsubscribe = Newsfeeds::model()->countByAttributes(array('emailid' => $subcribeemailid,'cuserid' => $cmuserid));
} else { $subcribeemailid=''; $countsubscribe=0; $logsts=0; }
$PopupdetailText='<div class="modal-dialog-1">
<div class="modal-content">
<div class="modal-header login_modal_header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h2 class="modal-title" id="myModalLabel">'.$titnw.' </h2>
</div>
<div class="container-1">
<div class="row">
<div class="col-sm-7 detail-text">
<h2 class="title"> ';
if($evoftype==0){ $PopupdetailText.='Offer Price: '.$discountperamt.'
<font style="font-size: 15px;">[ Up To '.$discountper.'% Discount ]</font>'; }
$PopupdetailText.='</h2><p>Details: </p>
<p>'.$details.'</p>
<p>Location: '.$locationnw.'</p>
<p>Expires in: '.$enddaate.'</p>';
if($countsubscribe==0){
$PopupdetailText.='<p>Shared by: '.$createdbyname.'
<button type="button" class="btn btn-success btn-xs" Onclick="subcribefeed('.$logsts.','.$cmuserid.')" >Subscribe NewsFeed</button></p>';
} else {
$PopupdetailText.='<p>Shared by: '.$createdbyname.'
<button type="button" class="btn btn-success disabled btn-xs" >Already Subscribed NewsFeed</button></p>';
}
$PopupdetailText.='<div class="form-group" id="subcribefrm" style="display:none;background-color: #eee; padding: 12px; width: 82%;">
<input type="text" id="subemailid" placeholder="Enter EmailID here" value="'.$subcribeemailid.'" style="width: 100%;" class="form-control login-field">
<br/>
Subscribe Feeds </div> ';
// if($evoftype==0){ $PopupdetailText.='<p>Offer Price:<b> $'.$discountperamt.'</b></p>'; }
$PopupdetailText.='<p>
<img src="'.Yii::app()->baseUrl.'/theme/site/images/yes.png"/>Yes
<img src="'.Yii::app()->baseUrl.'/theme/site/images/no.png"/>No
<img src="'.Yii::app()->baseUrl.'/theme/site/images/comments.png"/>Comments
<img src="'.Yii::app()->baseUrl.'/theme/site/images/share.png"/>Share</p>
<br/>
<form>
<div class="form-group">';
$userComment=new Comments;
$this->renderPartial('/comments/_form', array('model' => $userComment));
$PopupdetailText.='</div>
<div class="form-group">
<input type="text" id="username" placeholder="Enter the below security code here" value="" class="form-control login-field">
</div>
<div class="form-group">
<p><img src="'.Yii::app()->baseUrl.'/theme/site/images/capcha.png"/>Cant read? Refresh</p>
</div>
<div class="form-group">
Post Commets
</div>
</form>
</div>
<div class="col-sm-5">
<img src="'.$infowinimgpathSrcs.'" width="100%"/>
</div>
</div>
</div>
<div class="clearfix"></div>
<div class="modal-footer login_modal_footer">
</div>
</div>
</div>
<script>
function subcribefeed(staus,cid)
{
if(staus==0){
$("#subcribefrm").toggle(); }
else { subcribefeedAdd(cid); }
}
function subcribefeedAdd(cid)
{
subusremail=$("#subemailid").val();
var re = /[A-Z0-9._%+-]+#[A-Z0-9.-]+.[A-Z]{2,4}/igm;
if (subusremail == "" || !re.test(subusremail))
{ alert("Invalid EmailID ."); }
else {
postData ={
"email" :subusremail,
"cid" :cid
}
$.ajax({
type: "POST",
data: postData ,
url: "'.Yii::app()->baseUrl.'/newsfeeds/create",
success: function(msg){
if(msg=="Success"){ showdetails('.$id.'); alert("news feed subscribe successfully."); }
else if(msg=="available"){ alert("Already subscribe News Feed for this Commercial user."); }
else { alert("Error ."); }
}
});
}
}
</script> ';
echo $PopupdetailText;
}
renderPartial has a 3rd parameter return. If you set that to TRUE it will return the rendered form instead of echoing it. You can use it as follows:
$PopupdetailText .= $this->renderPartial('/comments/_form', array('model' => $userComment), TRUE);