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.
Related
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);
}
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.
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.');
}
I want to update some records. Though I didnot want update image and click on update buuton, It shows me error-
Call to a member function getClientOriginalName() on null
Here is my controller
public function update(Request $request)
{
$participants = new participants;
$file = $request->file("select_file");
if($request->hasfile("select_file"))
{
$file->move("public/images/",$file->getClientOriginalName());
}
$id = $request->id;
$First_name = $request->First_name;
$Last_name = $request->Last_name;
$Date_of_Birth = $request->Date_of_Birth;
$GST_no = $request->GST_no;
$email = $request->email;
$Mobile_No = $request->Mobile_No;
$Company_name = $request->Company_name;
$Address = $request->Address;
$State = $request->State;
$City = $request->City;
$Pincode = $request->Pincode;
$Country = $request->Country;
$Amount = $request->Amount;
// $Image = $request->Image;
$Image = $file->getClientOriginalName();
DB::table('participants')
->where('id',$id )
->update(['First_name'=>$First_name,'Last_name'=>$Last_name,'Date_of_Birth'=>$Date_of_Birth,'GST_no'=>$GST_no,'email'=>$email,'Mobile_No'=>$Mobile_No,'Company_name'=>$Company_name,'Address'=>$Address,'State'=>$State,'City'=>$City,'Pincode'=>$Pincode,'Country'=>$Country,'Amount'=>$Amount,'Image'=>$Image]);
$participants->update();
session()->flash('success','Data Updated successfully!');
return redirect()->back();
//return back()->with('error','Update Data successfully!');
}
view page
<div class="form-group row">
<label for="File" class="col-md-2 col-form-label text-md-left">{{ __('Image') }}</label>
<div class="col-md-10">
<input type="file" name="select_file" class="form-control" value="{{$input[0]->Image}}">
<img src="/public/images/{{$input[0]->Image}}" alt="Image not Found" style="width:100px; height:100px;" />
</div>
</div>
I want the data to be updated with previous image(since I donot want to update image).
Make the change like this:
$file = $request->file("select_file");
if($request->hasfile("select_file"))
{
$file->move("public/images/",$file->getClientOriginalName());
$Image = $file->getClientOriginalName();
}
$id = $request->id;
$First_name = $request->First_name;
$Last_name = $request->Last_name;
$Date_of_Birth = $request->Date_of_Birth;
$GST_no = $request->GST_no;
$email = $request->email;
$Mobile_No = $request->Mobile_No;
$Company_name = $request->Company_name;
$Address = $request->Address;
$State = $request->State;
$City = $request->City;
$Pincode = $request->Pincode;
$Country = $request->Country;
$Amount = $request->Amount;
// $Image = $request->Image;
Now $file->getClientOriginalName(); will only be called when there is file uploaded.
More like you should change the image only when a new one is uploaded otherwise leave it the same
$file = $request->file("select_file");
if($request->hasfile("select_file")) {
$file->move("public/images/",$file->getClientOriginalName());
$Image = $file->getClientOriginalName();
} else {
$Image = $request->Image;
}
because you are using $Image variable in your update statement later on which will give an undefined error if you only define $Image in your if statement.
Or you could take a better approach to enhance your overall script like so:
public function update(Request $request)
{
$id = $request->id;
$update = [
'First_name' => $request->First_name,
'Last_name' => $request->Last_name,
'Date_of_Birth' => $request->Date_of_Birth,
'GST_no' => $request->GST_no,
'email' => $request->email,
'Mobile_No' => $request->Mobile_No,
'Company_name' => $request->Company_name,
'Address' => $request->Address,
'State' => $request->State,
'City' => $request->City,
'Pincode' => $request->Pincode,
'Country' => $request->Country,
'Amount' => $request->Amount
];
$file = $request->file("select_file");
if ($request->hasfile("select_file")) {
$file->move("public/images/", $file->getClientOriginalName());
$update['Image'] = $file->getClientOriginalName();
}
DB::table('participants')->where('id', $id)->update($update);
session()->flash('success', 'Data Updated successfully!');
return redirect()->back();
}
public function update(Request $request)
{
$participants = new participants;
$id = $request->id;
$file = $request->file("select_file");
if($request->hasfile("select_file"))
{
$file->move("public/images/",$file->getClientOriginalName());
$Image = $file->getClientOriginalName();
DB::table('participants')
->where('id',$id )
->update(['Image'=>$Image]);
}
$id = $request->id;
$First_name = $request->First_name;
$Last_name = $request->Last_name;
$Date_of_Birth = $request->Date_of_Birth;
$GST_no = $request->GST_no;
$email = $request->email;
$Mobile_No = $request->Mobile_No;
$Company_name = $request->Company_name;
$Address = $request->Address;
$State = $request->State;
$City = $request->City;
$Pincode = $request->Pincode;
$Country = $request->Country;
$Amount = $request->Amount;
DB::table('participants')
->where('id',$id )
->update(['First_name'=>$First_name,'Last_name'=>$Last_name,'Date_of_Birth'=>$Date_of_Birth,'GST_no'=>$GST_no,'email'=>$email,'Mobile_No'=>$Mobile_No,'Company_name'=>$Company_name,'Address'=>$Address,'State'=>$State,'City'=>$City,'Pincode'=>$Pincode,'Country'=>$Country,'Amount'=>$Amount]);
$participants->update();
session()->flash('success','Data Updated successfully!');
return redirect()->back();
//return back()->with('error','Update Data successfully!');
}
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('/');
}