I want to update my product table but when I update my product table, it throws this error :
ErrorException in CreatesController.php line 201: Undefined variable:
name
201 line is this: 'image'=> $name,
My product table contains following fields :
productname,image,price,category_id
This is CreatesController :
public function productupdate(Request $request, $id){
$this->validate($request, [
'productname'=>'required',
'image'=>'image|mimes:jpg,png,jpeg|max:10000',
'price'=>'required',
'category_id'=>'required'
]);
if($request->hasfile('image'))
{
$file=$request->file('image');
$new_name = rand(). '.' .
$path=public_path().'/images';
$name=$file->getClientOriginalName();
$file->move($path, $name);
$data=$name;
}
$data=array(
'productname'=> $request->input('productname'),
'image'=> $name,
'price'=> $request->input('price'),
'category_id'=> $request->input('category_id')
);
Product::where('id', $id)
->update($data);
return redirect('/item')->with('info','Product updated successfuly!');
}
If you are only updating the product details without uploading an image, then if($request->hasfile('image')) becomes false, as $name variable is not getting assigned. Try this..
public function productupdate(Request $request, $id) {
$this->validate($request, [
'productname' => 'required',
'image' => 'image|mimes:jpg,png,jpeg|max:10000',
'price' => 'required',
'category_id' => 'required'
]);
$data = array(
'productname' => $request->input('productname'),
'image' => null,
'price' => $request->input('price'),
'category_id' => $request->input('category_id')
);
if ($request->hasfile('image')) {
$file = $request->file('image');
$path = public_path() . '/images';
$name = $file->getClientOriginalName();
$file->move($path, $name);
$data['image'] = $name;
}
Product::where('id', $id)
->update($data);
return redirect('/item')->with('info', 'Product updated successfully!');
}
Related
I am a Laravel beginner and I want to build an API with Laravel 8.
I have posts and images and I want to store and update them.
My store method works and the images are saved in the database and public path in images folders, but in update method I can't save it in folder.
These are my codes:
PostController
public function store(Request $request )
{
$data = $request->all();
//validationg posts and images fields
$validator = Validator::make($data, [
'user_id' => 'required',
'category_id' => 'required',
'title' => 'required|max:150|unique:posts',
'body' => 'required',
'study_time' => 'required',
'tags' => 'nullable|string',
'image' => 'required',
]);
if ($validator->fails()) {
return response()->json(['error' => $validator->errors(), 'خطا در اعتبار سنجی']);
}
//separate tags
$tags = explode(",", $request->tags);
if ($request->hasfile('image')) {
//getting post images from request
$files = $request->file('image');
//saving name and path of images
foreach ($files as $file) {
$imageName = time().rand(1,10000).'.'.$file->extension();
$postTitle = $request->title; //post title for folder name and the images inside it
$imagePath = public_path(). '/images/posts/'.$postTitle;
$file->move($imagePath, $imageName);
$image = new Image;
$image->image = $imageName;
$image->path = $imagePath;
$images[] = $image; // make an array of uploaded images
}
}
$post = Post::create($data);
$post->images()->saveMany($images);//save imageas in image table
$post->tag($tags);//save tags in tags table
return response()->json([
'success' => true,
'message' => 'با موفقیت ثبت گردید ',
'data' => $post
]);
}
public function update(Request $request, $id)
{
$post_failed = Post::find($id);
if (is_null($post_failed)) {
return response()->json('پست مورد نظر یافت نشد ', 404);
}
$data = $request->all();
//validation posts and images fields
$validator = Validator::make($data, [
'user_id' => 'required',
'category_id' => 'required',
'title' => 'required|max:150|unique:posts',
'body' => 'required',
'study_time' => 'required',
'tags' => 'nullable|string',
'image' => 'required',
]);
if ($validator->fails()) {
return response()->json(['error' => $validator->errors(), 'خطا در اعتبار سنجی ']);
}
$tags = explode(",", $request->tags);
if ($request->hasfile('image')) {
$postTitle = $request->title; //post title for folder name and the images inside it
//delete last Images from database for updating images
Image::where('imageable_type', 'App\Models\Post')->where('imageable_id' , $id)->delete();
//delete last images images folder
File::delete(public_path('/images/posts/'.$postTitle));
$files = $request->file('image');
foreach ($files as $file) {
$imageName = time().rand(1,10000).'.'.$file->extension();
$imagePath = public_path(). '/images/posts/'.$postTitle;
$image = new Image();
$image->image = $imageName;
$image->path = $imagePath;
$images[] = $image;
}
}
$post = Post::find($id);
$post->user_id = $data['user_id'];
$post->category_id = $data['category_id'];
$post->title = $data['title'];
$post->body = $data['body'];
$post->study_time = $data['study_time'];
$post->tags = $data['tags'];
$post->save();
$post->images()->saveMany($images);
$post->tag($tags);
return response()->json([
'success' => true,
'message' => 'با موفقیت ویرایش گردید ',
'data' => $post
]);
}
The relation between posts and images is polymorphic one to many and I tested it with postman.
Postman
Database
And the path:
Please, help.
In store() method you saved images on disk by using
$imagePath = public_path(). '/images/posts/'.$postTitle;
$file->move($imagePath, $imageName);
In update() you deleted them
File::delete(public_path('/images/posts/'.$postTitle));
and determined path for new files
$imagePath = public_path(). '/images/posts/'.$postTitle;
but nothing happens after this. In whole update() method there is no code that could do something in storage, so of course nothing appears in folder ;)
So again use $file->move() or Storage facade to save files.
TIP
Also this is bad practice to repeat long code logic like that. It would be better to extract this and share between store/update.
The name of controller is "BadgeController". This is my store function in BadgeController where is this error happening.
public function store(Request $request)
{
$request->validate([
'image' => 'required',
]);
$image = $request->file('images');
$new_name = rand().'.'.$image->getClientOriginalExtension();
$image->move(public_path('images'), $new_name);
$form_data = array(
'image' => $new_name,
);
Badge::create($form_data);
return redirect('badges.index')->with('success', 'Data Added successfully.');
}
Judging by the error, it means your validation is successfully passed, so I guess the input's name is image not images.
$image = $request->file('image');
I updated and image is showed after that, but i need to delete the previous image (from folder) after updating with the new one.
//update
public function edit ($id)
{
$user = User::find($id);
// $user = User::where('id', $id)->first();
// $user = DB::table('users')->where('id', $id)->first();
return view('edit', compact('user'));
}
public function postEdit (Request $request) {
request()->validate([
'email' => 'required',
'fullname' => 'required',
'birthday' => 'required',
'address' => 'required|min:10',
]);
$image = $request->image;
// dd($image);
$id = $request->id;
$email = $request->email;
$fullname = $request->fullname;
$address = $request->address;
$birthday = $request->birthday;
$country = $request->country;
$image = $request -> file('image');
$destination = base_path().'/public/img';
$file_name = rand(100,1).date('h-i-s');
$image->move($destination, $file_name.".".$image->getClientOriginalExtension());
$img = $file_name.".".$image->getClientOriginalExtension();
User::where('id',$id)->update([
'image' => $img,
'email' => $email,
'fullname' => $fullname,
'birthday' => $birthday,
'address' => $address,
'country' => $country,
]);
return Redirect::to("dashboard")->withSuccess('Great! You have Successfully edited');
}
You can use File facade to delete a file:
use Illuminate\Support\Facades\File;
$pathToFile = base_path('public/img/'.$user->image);
File::delete($pathToFile);
You should first find the user and determine if he already has an image, sou you can delete it from the storage. Do it like this:
public function postEdit (Request $request) {
request()->validate([
'email' => 'required',
'fullname' => 'required',
'birthday' => 'required',
'address' => 'required|min:10',
]);
$user = User::where('id', $request->id)->first();
if($user->image){ //Check if user has image and delete it from storage
if (Storage::exists($user->image)) {
Storage::delete( $user->image ); //Dont forget to use your real paths. $user->image should be a path to an image.
}
}
$image = $request->image;
$id = $request->id;
$email = $request->email;
$fullname = $request->fullname;
$address = $request->address;
$birthday = $request->birthday;
$country = $request->country;
//Insert new image
$image = $request -> file('image');
$destination = base_path().'/public/img';
$file_name = rand(100,1).date('h-i-s');
$image->move($destination, $file_name.".".$image->getClientOriginalExtension());
$img = $file_name.".".$image->getClientOriginalExtension();
//Now update user
$user->update([
'image' => $img,
'email' => $email,
'fullname' => $fullname,
'birthday' => $birthday,
'address' => $address,
'country' => $country,
]);
return Redirect::to("dashboard")->withSuccess('Great! You have Successfully edited');
}
(1/1) BadMethodCallException
Method [validate1504030121.jpeg] does not exist.
public function store(Request $request)
{
//
if( $request->hasfile('thumbnail') && $request->thumbnail->isvalid())
{
$extension = $request->thumbnail->extension();
$filename = time()."-.".$extension;
$request->thumbnail->move(public_path('image'), $filename);
}else
{
$fileiname = 'sagewolf.png';
}
//print_r($request->all());
$this->validate($request, [
'title' => 'required|unique:posts|max:255',
'body' => 'required',
'user_id'=> 'required',
'catagory'=>'required',
'thumbnail'=>$filename, ]);
$store = Post::create($request->all());
Want to avoid thumbnail field from validation rules.
Thanks in advance.
I have a 2 table user and reports
Report model
public function user() {
return $this->belongsTo('App\User', 'author_id');
}
User model
public function reports() {
return $this->hasMany('App\Report', 'author_id');
}
In User model there is a column called "sum_sales"
In Report model there is a column called "total"
Ho can I pass the sum(total) from my Report model to 'sum_total' inside my User model?
My report controller
public function store(Request $request)
{
$this->validate($request, ['title' => 'required',
'date' => 'required|date_format:d/m/Y|regex:/[0-9]{2}\/[0-9]{2}\/[0-9]{4}/',
'image_1' => 'required|mimes:png,jpeg',
'products' => 'required',
'total' => 'required',
'time' => 'required|min:2',
'location' => 'required',
'sub_location' => 'required',
]);
$user = Auth::user()->id;
$report = new Report($request->all());
$report->author_id = $user;
$image = $request->file('image_1');
$destinationPath = 'uploads/reports';
$ext = $image->getClientOriginalExtension();
$fileName = rand(11111,99999).'.'.$ext;
$report->image_1 = $image->move($destinationPath, $fileName);
$field_total = $request->input('total');
$sum_total = $report->sum('total');
$totalSum = $field_total + $sum_total;
$report->author_id->sum_sales = $totalSum;
$report->save();
Session::flash('flash_message', 'Report added!');
return redirect('dash/reports');
}
With this the browser say:
Indirect modification of overloaded property App\Report::$author_id has no effect
How can I figure out?
solved by Giedrius Kiršys
public function store(Request $request)
{
$this->validate($request, ['title' => 'required',
'date' => 'required|date_format:d/m/Y|regex:/[0-9]{2}\/[0-9]{2}\/[0-9]{4}/',
'image_1' => 'required|mimes:png,jpeg',
'products' => 'required',
'total' => 'required',
'time' => 'required|min:2',
'location' => 'required',
'sub_location' => 'required',
]);
$user = Auth::user()->id;
$report = new Report($request->all());
$report->author_id = $user;
$image = $request->file('image_1');
$destinationPath = 'uploads/reports';
$ext = $image->getClientOriginalExtension();
$fileName = rand(11111,99999).'.'.$ext;
$report->image_1 = $image->move($destinationPath, $fileName);
$report->save();
$sumUserTotal = User::find($user)->reports->sum('total');
Auth::user()->update(['sum_sales' => $sumUserTotal]);
Session::flash('flash_message', 'Report added!');
return redirect('dash/reports');
}