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);
Related
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.
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
recently i'm trying to practice with laravel 5.5 and create simple upload and update image
here is my controller on store
$input = $request->all();
$this->validate($request, [
'photo' => 'sometimes|image|mimes:jpeg,png,jpg,gif,svg|max:500',
]);
if ($request->hasFile('photo')) {
$photo = $request->file('photo');
$ext = $photo->getClientOriginalExtension();
if ($request->file('photo')->isValid()) {
$photo_name = date('YmdHis'). ".$ext";
$photoName = time().'.'.$request->photo->getClientOriginalExtension();
$request->photo->move(public_path('photo-upload'), $photoName);
$upload_path = public_path('photo-upload');
$input['photo'] = $photoName;
}
}
controller update
if ($request->hasFile('photo')) {
// delete the old/previous one
$exist = Storage::disk('photo')->exists($student->photo);
if (isset($student->photo) && $exist) {
$delete = Storage::disk('photo')->delete($siswa->photo);
}
// upload new one
$photo = $request->file('photo');
$ext = $photo->getClientOriginalExtension();
$photoName = time().'.'.$request->foto->getClientOriginalExtension();
if ($request->file('photo')->isValid()) {
$upload_path = 'photo-upload';
$request->file('photo')->move($upload_path, $phptpName);
$input['photo'] = $iphotoName;
}
}
the store method works perfectly, it uploaded image to the right folder then update the databse
the problem is on the update, it update the database but it didn't upload the image to the photo-upload folder
Any suggestion?
Thanks
my question is about how to split this code. I have a registration form and it's saving function looks like this:
public function store(EntityRequestCreate $request)
{
$geoloc = new Geoloc;
$geoloc->lat = $request->input('lat');
$geoloc->lng = $request->input('lng');
$geoloc->slug = $request->input('name');
$geoloc->save();
$user_id = Auth::id();
$entity = new Entity;
$entity->name = $request->input('name');
$entity->type = $request->input('type');
$entity->email = $request->input('email');
$entity->tags = $request->input('tags');
$entity->_geoloc()->associate($geoloc);
$entity->save();
$entity_id = $entity->id;
$address = new Address;
$address->building_name = $request->input('building_name');
$address->address = $request->input('address');
$address->town = $request->input('town');
$address->postcode = $request->input('postcode');
$address->telephone = $request->input('telephone');
$address->entity_id = $entity_id;
$address->save();
$role = User::find($user_id);
$role->role = "2";
$role->save();
DB::table('entity_user')->insert(array('entity_id' => $entity_id, 'user_id' => $user_id));
$result = $geoloc->save();
$result2 = $entity->save();
$result3 = $address->save();
$result4 = $role->save();
if ($result && $result2 && $result3 && $result4) {
$data = $entity_id;
}
else {
$data = 'error';
}
return redirect('profile/entity');
}
As you see, it has a custom request and it is saving to 3 models, that way my controller code is far too long (having many other functions etc) Instead I want to move this code to a model, as my model so far has only relationships defined in it. However I don't exactly know how to call a model from controller, do I have to call it or it will do it automatically? Any other ideas on how to split the code?
You could use the models create method to make this code shorter and more readable.
For example:
$geoloc = Geoloc::create(
$request->only(['lat', 'lng', 'name'])
);
$entity = Entity::create(
$request->only(['name', 'type', 'email', 'tags])
);
$entity->_geoloc()->associate($geoloc);
$address = Address::create([
array_merge(
['entity_id' => $entity->id],
$request->only(['building_address', 'address', 'town'])
)
])
...
The create method will create an object from a given associated array. The only method on the request object will return an associated array with only the fields for the given keys.
add an image I can not load because it creates a new folder outside the public folder
$input = Input::all();
$polje = array('naslov' => 'required');
$provjera = Validator::make($input, $polje);
if($provjera->passes()){
$file = Input::file('file');
$filename = $file->getClientOriginalName();
$uploadSuccess = Input::file('file')->move(base_path().'/images/vijesti', $filename);
$vijest = new Vijesti();
$vijest->naslov = $input['naslov'];
$vijest->slika = $uploadSuccess;
$vijest->tekst = $input['tekst'];
$vijest->tag = $input['tag'];
$vijest->kategorija_id = Input::get('kategorija_id');
$vijest->save();
return Redirect::to('admin/vijesti/dodaj')->withInput()->with('ok', 'Vijest je uspjesno dodata.');
}else {
return Redirect::to('admin/vijesti/dodaj')->with('no', 'Greska: morate pokusati ponovo, polje naslov i slika su obavezna polja.');
}
You are using the wrong function. Use public_path() instead of base_path().
$uploadSuccess = Input::file('file')->move(public_path().'/images/vijesti', $filename);
Hope that helps :)