Uploading multi images in Laravel 5.8 - laravel

I am a beginner in laravel. I'm trying to submit a post with the option to upload multiple files if the user wants. I keep getting the error "Undefined variable: data." Where did I go wrong?
public function store(Request $request)
{
//validate
$this->validate($request, [
'title' => 'required|min:10',
'body' => 'required|min:20',
'filename' => 'nullable|max:2480',
'filename.*' => 'mimes:jpeg,jpg,png'
]);
//store Image
if($request->file('filename'))
{
foreach($request->file('filename') as $image)
{
$name=time().$image->getClientOriginalName();;
$image->move(public_path().'/images/', $name);
$data[] = $name;
}
}
$post= new Post();
$post->user_id = auth()->user()->id;
$post->title = $request->input('title');
$post->body = $request->input('body');
$post->filename=json_encode($data);
$post->save();
return back()->withMessage('Post created successfully.');
}

I think that it will be better to declare your array outside the foreach loop.
You can try something like this:
Outside your foreach loop.
$data = array();
Inside your foreach loop, try to populate the array like this:
array_push($data, $name);
public function store(Request $request)
{
//validate
$this->validate($request, [
'title' => 'required|min:10',
'body' => 'required|min:20',
'filename' => 'nullable|max:2480',
'filename.*' => 'mimes:jpeg,jpg,png'
]);
//Initialize an empty array
$data = array();
//store Image
if($request->file('filename'))
{
foreach($request->file('filename') as $image)
{
$name=time().$image->getClientOriginalName();;
$image->move(public_path().'/images/', $name);
//populate array here
array_push($data, $name);
}
}
$post= new Post();
$post->user_id = auth()->user()->id;
$post->title = $request->input('title');
$post->body = $request->input('body');
$post->filename=json_encode($data);
$post->save();
return back()->withMessage('Post created successfully.');
}

Related

Image Update Problem Using Laravel Query Builder

My All Data has been updated successfully but Image not update and old image not remove. I am using Query Builder.
Can anyone tell me what to do?
My Controller are given below
I want to know something new.
public function update(Request $request,$id)
{
$validatedData = $request->validate([
'name' => 'required|max:255',
'title' => 'required',
'details' => 'required',
]);
$data = array();
$data['name'] = $request->name;
$data['title'] = $request->title;
$data['details'] = $request->details;
$data['status'] = $request->status;
$image=$request->photo;
if ($image) {
$image_name = str_random(20);
$ext = strtolower($image->getClientOriginalExtension());
$image_full_name = $image_name.'.'.$ext;
$upload_path = 'public/upload/event';
$image_url = $upload_path.$image_full_name;
$success = $image->move($upload_path,$image_full_name);
if ($success) {
$data['photo'] = $image_url;
$img = DB::table('events')->where('id',$id)->first();
$image_path = $img->photo;
$done = unlink($image_path);
$user = DB::table('events')->where('id',$id)->update($data);
if ($user) {
$notification = array(
'messege' => 'Data Updated Successfully',
'alert-type' => 'success'
);
return redirect('admin/event')->with($notification);
}else{
return redirect()->back();
}
}
}else{
return redirect()->back();
}
//return redirect('admin/event')->with($notification);
}

why images aren't stored in public path

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.

uploading image and got error in laravel "Undefined variable: data"

I am trying to update the product and for that I am updating the pictures. I meant if user want to add more pictures to it but when I do this I get below error
Undefined variable: data
Also I want to restrict the total uploading pictures to max 3 pictures or 2 pictures and 1 video
When I add a video it does not show like it does not play
Any help would be great. Thank for the help in advance
public function editProduct($id, Request $request) {
if(Auth::check()) {
$pn = Input::get('pn');
$desc = Input::get('desc');
$price = Input::get('price');
// $products = Product::all();
$products = Product::where('id', $id)->first();
// foreach($products as $p) {
if(($products->user_id == Auth::user()->id) && ($products->id == $id)) {
$this->validate($request, [
'filename.*' => 'required|max:5000',
// 'filename.*' => 'image|mimes:jpeg,png,jpg,mp4|max:5000'
]);
if($request->hasfile('filename'))
{
foreach($request->file('filename') as $image)
{
$name = $image->getClientOriginalName();
$filename = time(). '-' . $image;
$file_path = $image->move(public_path().'/assets/images/', $name);
$data[] = $name;
}
}
$new_name = json_encode($data);
$products = Product::where('user_id', Auth::user()->id)
->where('id', $id)->update([
'product_name' => $pn,
'description' => $desc,
'price' => $price,
'filename' => $new_name,
]);
}
} else {
Session::flash("message", "OOPS! You dont have permission to edit the items. Please login first.");
return redirect("/register-user");
}
I was missing enctype="multipart/form-data" files=true in my form in the view so it was not getting a file from the blade so got it fixed now

Unexpected data found. Unexpected data found. Data missing

Unexpected data found. Data missing
what is the wrong with my code ??
public function update(Request $request , $id )
{
$request->validate([
'title' => 'required|max:200',
'body' => 'required|max:500'
]);
$post = new Post();
$post = Post::find($id);
$post->title = $request->title;
$post->body = $request->body;
$post->user_id = auth()->User()->id;
$post->save();
return redirect('/posts')->with('status', 'Post was Updated !');
}
Replace your code with below given,
public function update(Request $request , $id )
{
$request->validate([
'title' => 'required|max:200',
'body' => 'required|max:500'
]);
$post = Post::find($id);
$post->title = $request->title;
$post->body = $request->body;
$post->user_id = auth()->user()->id;
$post->save();
return redirect('/posts')->with('status', 'Post was Updated !');
}
$post = new Post(); is not needed as $post object is created in next line.

How to display array data after store & email sent?

UPDATE
I have contact form. it works good. I would like to display $data array at
final page which is admintemp.blade.php.
I can display $data array at one step before final page. but I would like to display those at last page too.
I thoguht just add this
return view('mail.complete', ['data' => $data]);
is fine. but I got this error
Invalid argument supplied for foreach()
Could you teach me right way please?
Here is my code
/*
*confirm page
*/
public function confirm(Request $request)
{
$rules = [
'orderer' => 'required'
];
$this->validate($request, $rules);
$data = $request->all();
$request->session()->put('data',$data);
return view('mail.confirm', compact("data"));
}
/*
* complete page
*/
public function complete(Request $request)
{
$data = $request->session()->pull('data');
$token = array_shift($data);
$Contact = Contact::create($data);
$data = session()->regenerateToken();
return view('mail.complete', ['data' => $data]);
}
UPDATES 2
complete.blade.php
#foreach ($data as $val)
{{ $val->id }}
{{ $val->tel }}
#endforeach
for example you have two step form
first step post method:
public function postCreateStep1(Request $request)
{
$validatedData = $request->validate([
'name' => 'required',
]);
if (empty($request->session()->get('contact'))) {
$contact = new Contact();
$contact->fill($validatedData);
$request->session()->put('contact', $contact);
} else {
$contact = $request->session()->get('contact');
$contact->fill($validatedData);
$request->session()->put('contact', $contact);
}
return redirect('/create-step2');
}
second step post method:
public function postCreateStep2(Request $request)
{
$validatedData = $request->validate([
'family' => 'required',
]);
if (empty($request->session()->get('contact'))) {
$contact = new Contact();
$contact->fill($validatedData);
$request->session()->put('contact', $contact);
} else {
$contact = $request->session()->get('contact');
$contact->fill($validatedData);
$request->session()->put('contact', $contact);
}
$created_contact = Contact::create([
'name' => $contact->name,
'family' => $contact->family,
]);
// Do whatever you want with $created_contact
return redirect('/');
}

Resources