Call to a member function storeAs() on null - laravel

I want to store images with id to table and save them to a folder.
I have two tables catalogs and images.Images table has img_id which is a foreign key to id in catalogs table, code in my controller is:
$catalog = new Katalog();
$catalog->name = $name;
$catalog->picturePath = $name . '/';
$catalog->description = $desc;
$catalog->address = $request->input('address');
$catalog->phone_number = $request->input('phone_number');
$catalog->email = $request->input('e_mail');
$catalog->info_holder = $request->input('type');
$catalog->partner_logo = $logo_img_name;
$catalog->short_news = $request->input('short_news');
$catalog->updated_at = Carbon::now();
$catalog->site = $request->input('site');
$catalog->creator_id = Auth::user()->id;
$catalog->save();
$id = Katalog::where('name', $name)->first()->id;
if ($request->hasFile('images')) {
foreach ($request->file('images') as $image) {
$img_name = $image->getClientOriginalName();
$request->image->storeAs(('/images/' . $name), $img_name, 'images');
Image::creat([
'img_id' => $id,
'img_name' => $img_name
]);
}
}
After storing data to the catalogs table it returns a new id but I want to store images to images table with returned id but can not do this.Error shows here $request->image->storeAs(('/images/' . $name), $img_name, 'images');
Help me please thanks in advance.

You can get the ID from the just created object (Katalog) without a query
$id = $catalog->id;
instead of
$id = Katalog::where('name', $name)->first()->id;
Because if there are other Katalog records with the same name, you may not get the one you want
PS: you may have a typo here, add an "e" at the end
Image::create([
'img_id' => $id,
'img_name' => $img_name
]);
Hope this helps

Related

upload image as optional in laravel 8

I want to upload image using laravel 8, and I use following code:
$post = new Post;
$upload_image_name = time().'_'.$req->image_name->getClientOriginalName();
$req->image_name->move('uploads', $upload_image_name);
$post->title = $req->input('title');
$post->image_name = $upload_image_name;
$post->save();
It is working fine, but I got error Call to a member function getClientOriginalName() on null while image is empty.
It's because, suprise, image is empty while image is empty
Add condition to check uploaded image
$post = new Post;
$post->title = $req->input('title');
if($req->image_name)
$upload_image_name = time().'_'.$req->image_name->getClientOriginalName();
$req->image_name->move('uploads', $upload_image_name);
$post->image_name = $upload_image_name;
}
$post->save();
If image is required - add validation in action beginning - but right way for it - make validation in Form Request
$request->validate([
'image_name' => 'required|image',
'title' => 'required|string'
]);
If image is not required - change your migration and make posts.image_name nullable
I use following code but I don't think this is conventional way. Here is the code:
if($req->hasFile('image_name')){
$upload_image_name = time().'_'.$req->image_name->getClientOriginalName();
$req->image_name->move('uploads', $upload_image_name);
}
else
$upload_image_name = "Noimage";
$post = new Post;
$post->title = $req->input('title');
$post->image_name = $upload_image_name;
$post->save();
As I used my last laravel project.
$image = $request->file('thumbnail');
if (isset($image)) {
$imageName = date('y_m_d') . "_" . uniqid().".".$image->getClientOriginalExtension();
if (!Storage::disk('public')->exists('thumbnail')) {
Storage::disk('public')->makeDirectory('thumbnail');
}
$postImage = Image::make($image)->stream();
Storage::disk('public')->put('thumbnail/' . $imageName, $postImage);
} else {
$imageName = "";
}
$post = new Post;
$post->title = $request->title;
$post->image_name = $imageName;
$post->save();
image_name column should be nullable.

Laravel : How can i get old and new value by updateOrCreate

I want update or create in data base
but i want get the old value and updated value because i want to compare between these two value
for example
this item in table user
name = Alex and Order = 10
so now i want update this person by
name = Alex and Order = 8
Now After updating or creating if not exist
just for update i want get
Old order 10 | And new Order 8
I want compare between these order
i have tryin getChange() and getOriginal() but two the function give me just the new value.
Please Help
You can get the old value using getOriginal if you have the object already loaded.
For example :
$user = User::find(1);
$user->first_name = 'newname';
// Dumps `oldname`
dd($user->getOriginal('first_name'));
$user->save();
However in case of updateOrCreate, you just have the data. I am not sure about a way to do it using updateOrCreate but you can do simply do :
$user = User::where('name', 'Alex')->first();
$newOrder = 10;
if($user){
$oldOrder = $user->getOriginal('order');
$user->order = $newOrder;
$user->save();
}
Is the name unique in the table? Because if it is not you will have updates on multiple rows with the same data.
So the best approach is to use the unique column which is probably the ID.
User::updateOrCreate(
[ 'id' => $request->get('id') ], // if the $id is null, it will create new row
[ 'name' => $request->get('name'), 'order' => $request->get('order') ]
);
Solution
$model = Trend::where('name', $trend->name)->first();
if ($model) {
$model->old_order = $model->getOriginal('order');
$model->order = $key + 1;
$model->save();
} else {
Trend::where('order', $key + 1)->delete();
$new = new Trend();
$new->name = $trend->name;
$new->old_order = $key + 1;
$new->order = $key + 1;
$new->tweet_volume = $trend->tweet_volume;
$new->save();
}

Laravel: how to update records values coming as arrow

I am new to Laravel and I need to update records coming as array from a form.
$a = $request->id;
$b = $request->val;
Now I need to update the records
Details::find($b)->update(['detail'=>$a]);
The script above obviously does not work...
You can do it in more than one way, try this :
$details = Details::find($request->input($id));
$details->val = $request->input('val');
$details->save();
Or you can use this if the inputs has the same name as the model fields:
$details = Details::findOrFail($request->input($id));
$details->update($request->all());
You can update in the following ways. Assuming detail is your field name to update.
$id = $request->id;
$val = $request->val;
$detail = Details::findOrFail($id);
$detail->detail = $val;
$detail->save();
For the below to work. You need to set the $fillable propery in the model
// In Detail model
protected $fillable = ['detail'];
// Controller
Details::where('id', $id)->update([
'detail' => $val
]);
$a = $request->id;
$b = $request->val;
$detail = Detail::where('id', $a)->first();
$detail->update(['detail' => $b]);

Update user avatar profil Laravel 4.2

I have a little problem about update avatar pic of my user.
I have a polymorph relation table for Image and when i update info of my user profile and upload new avatar in my DB he create a new entry and not updated the current id of my table Images.
Table Images Id|path|Imageable_id|imageable_type|created_at
My UsersController method update
public function update($id){
$rules =[
/*'lastname' => 'min:3|string',
'firstname' => 'min:3|string',
'username'=> 'min:4|unique:users',
'mail' => ' email|unique:users',
'birthday' => 'date_format:d-m-Y|before:today',
'country'=>'min:3',
'type_street'=>'min:3',
'number'=>'min:1|numeric',
'street'=>'min:4|string',
'complementary_street'=>'min:2|string',
'town'=>'min:2|string',
'zip'=>'min:4|numeric',
'phone_home'=>'min:10|numeric',
'phone_mobile'=>'min:10|numeric',
'image_path'=>'image|max:1000|mimes:jpeg,jpg,png',*/
];
$validator = Validator::make(Input::all(),$rules);
if($validator->fails()){
return Redirect::to('/profil/'.$id)
->with('alert_error','Merci de corriger les erreurs');
}else{
$user = User::find($id);
$user->lastname = Input::get('lastname');
$user->firstname = Input::get('firstname');
$user->username = Input::get('username');
$user->mail = Input::get('mail');
$user->birthday = Input::get('birthday');
$user->adresse->type_street = Input::get('type_street');
$user->adresse->number = Input::get('number');
$user->adresse->street = Input::get('street');
$user->adresse->complementary_street = Input::get('complementary_street');
$user->adresse->town = Input::get('town');
$user->adresse->zip = Input::get('zip');
$user->adresse->country = Input::get('country');
$user->adresse->phone_home = Input::get('phone_home');
$user->adresse->phone_mobile = Input::get('phone_mobile');
if(Input::hasFile('avatar')){
$avatar = Image::find($id);
$file = Input::file('avatar');
$name = time().'-'.$file->getClientOriginalName();
$file = $file->move('img/avatar/', $name);
$input['path'] = 'img/avatar/'.$name;
$input['imageable_id'] = $user->id;
$input['imageable_type'] = 'User';
$avatar = new Image($input);
$avatar->save();
}
$user->adresse->save();
return Redirect::to('/profil/'.$id)
->with('alert_success','Modification sauvegardé avec succès');
}
}
Can you help me for this feature i don't understand why no updated of current id of my entry and create new One .
Thank's
You're overwriting your find $avatar = Image::find($id); with a new instance $avatar = new Image($input);

How to validate duplicate entries before inserting to database - Codeigniter

I have developed simple application, i have generated checkbox in grid dynamically from database, but my problem is when user select the checkbox and other required field from grid and press submit button, it adds duplicate value, so i want to know how can i check the checkbox value & other field value with database value while submitting data to database.
following code i use to generate all selected items and then save too db
foreach ($this->addattendee->results as $key=>$value)
{
//print_r($value);
$id = $this->Attendee_model->save($value);
}
i am using codeigniter....can any one give the idea with sample code plz
{
$person = $this->Person_model->get_by_id($id)->row();
$this->form_data->id = $person->tab_classid;
$this->form_data->classtitle = $person->tab_classtitle;
$this->form_data->classdate = $person->tab_classtime;
$this->form_data->createddate = $person->tab_crtdate;
$this->form_data->peremail = $person->tab_pemail;
$this->form_data->duration = $person->tab_classduration;
//Show User Grid - Attendee>>>>>>>>>>>>>>>>>>>>>>>>
$uri_segment = 0;
$offset = $this->uri->segment($uri_segment);
$users = $this->User_model->get_paged_list($this->limit, $offset)->result();
// generate pagination
$this->load->library('pagination');
$config['base_url'] = site_url('person/index/');
$config['total_rows'] = $this->User_model->count_all();
$config['per_page'] = $this->limit;
$config['uri_segment'] = $uri_segment;
$this->pagination->initialize($config);
$data['pagination'] = $this->pagination->create_links();
// generate table data
$this->load->library('table');
$this->table->set_empty(" ");
$this->table->set_heading('Check', 'User Id','User Name', 'Email', 'Language');
$i = 0 + $offset;
foreach ($users as $user)
{
$checkarray=array('name'=>'chkclsid[]','id'=>'chkclsid','value'=>$user->user_id);
$this->table->add_row(form_checkbox($checkarray), $user->user_id, $user->user_name, $user->user_email,$user->user_language
/*,anchor('person/view/'.$user->user_id,'view',array('class'=>'view')).' '.
anchor('person/update/'.$user->user_id,'update',array('class'=>'update')).' '.
anchor('person/showattendee/'.$user->user_id,'Attendee',array('class'=>'attendee')).' '.
anchor('person/delete/'.$user->user_id,'delete',array('class'=>'delete','onclick'=>"return confirm('Are you sure want to delete this person?')"))*/ );
}
$data['table'] = $this->table->generate();
//end grid code
// load view
// set common properties
$data['title'] = 'Assign Attendees';
$msg = '';
$data['message'] = $msg;
$data['action'] = site_url('person/CreateAttendees');
//$data['value'] = "sssssssssssssssssss";
$session_data = $this->session->userdata('logged_in');
$data['username'] = "<p>Welcome:"." ".$session_data['username']. " | " . anchor('home/logout', 'Logout')." | ". "Userid :"." ".$session_data['id']; "</p>";
$data['link_back'] = anchor('person/index/','Back to list of Classes',array('class'=>'back'));
$this->load->view('common/header',$data);
$this->load->view('adminmenu');
$this->load->view('addattendee_v', $data);
}
The code is quite messy but I have solved a similar issue in my application I think, I am not sure if its the best way, but it works.
function save_vote($vote,$show_id, $stats){
// Check if new vote
$this->db->from('show_ratings')
->where('user_id', $user_id)
->where('show_id', $show_id);
$rs = $this->db->get();
$user_vote = $rs->row_array();
// Here we are check if that entry exists
if ($rs->num_rows() == '0' ){
// Its a new vote so insert data
$this->db->insert('show_ratings', $rate);
}else{
// Its a not new vote, so we update the DB. I also added a UNIQUE KEY to my database for the user_id and show_id fields in the show_ratings table. So There is that extra protection.
$this->db->query('INSERT INTO `show_ratings` (`user_id`,`show_id`,`score`) VALUES (?,?,?) ON DUPLICATE KEY UPDATE `score`=?;', array($user_id, $show_id, $vote, $vote));
return $update;
}
}
I hope this code snippet gives you some idea of what to do.
maybe i have same trouble with you.
and this is what i did.
<?php
public function set_news(){
$this->load->helper('url');
$slug = url_title($this->input->post('title'), 'dash', TRUE);
$query = $this->db->query("select slug from news where slug like '%$slug%'");
if($query->num_rows()>=1){
$jum = $query->num_rows() + 1;
$slug = $slug.'-'.$jum;
}
$data = array(
'title' => $this->input->post('title'),
'slug' => $slug,
'text' => $this->input->post('text')
);
return $this->db->insert('news', $data);
}
?>
then it works.

Resources