In my laravel application, I'm trying to update some content using the following controller function. But every time when I try to run the following function am getting an error
public function update_tcp(Request $request, $id)
{
try{
Session::put('tcpSession', '1');
$request->merge(['gender' => 'M']);
$this->validate($request, [
'first_name_tcp2' => 'required',
'last_name_tcp2' => 'required',
'image_id' => 'image|mimes:jpeg,png,jpg,gif,svg|max:2048',
'user_id'=>'required',
'gender'=>'required',
'date_of_birth_tcp2'=>'required'
]);
//$input = $request->except('_method', '_token');
$input = $request->all();
unset($input['_token']);
unset($input['_method']);
if ($image = $request->file('image_id')) {
$destinationPath = 'propics/';
$profileImage = date('YmdHis') . "." . $image->getClientOriginalExtension();
$image->move($destinationPath, $profileImage);
$input['image_id'] = "$profileImage";
//dd($profileImage);
}else{
//unset($input['image']);
$profileImage='default-avatar.png';
$request->merge(['image_id' => 'default-avatar.png']);
}
$data = $request->input();
$tcp = TakeCarePerson::WHERE('id','=',''.$id.'');
$tcp->first_name = $data['first_name_tcp2'];
$tcp->last_name = $data['last_name_tcp2'];
$tcp->date_of_birth = $data['date_of_birth_tcp2'];
$tcp->user_id = $data['user_id'];
$tcp->image_id = $profileImage;
$tcp->gender= $data['gender'];
$tcp->update();
return redirect()->route('participants.index')
->with('success',__('texts.Take care person updated successfully.'));
} catch(Exception $e){
return back() ->with('failedTcp',__('texts.Le fichier sélectionné doit être une image.'));
}
}
This is the error,
ArgumentCountError Too few arguments to function
Illuminate\Database\Eloquent\Builder::update(), 0 passed
Where do I need to fix in order to function my update function properly?
You are not passing data to update .Instead where find by id and then call save()
$tcp = TakeCarePerson::find($id);
$tcp->first_name = $data['first_name_tcp2'];
$tcp->last_name = $data['last_name_tcp2'];
$tcp->date_of_birth = $data['date_of_birth_tcp2'];
$tcp->user_id = $data['user_id'];
$tcp->image_id = $profileImage;
$tcp->gender= $data['gender'];
$tcp->save();
or
$tcp = TakeCarePerson::where('id','=',$id)->update([
'first_name'=> $data['first_name_tcp2'],
'last_name'=>$data['last_name_tcp2'],
'date_of_birth'=>$data['date_of_birth_tcp2'],
'user_id'=>$data['user_id'],
'image_id'=>$profileImage,
'gender'=>$data['gender']
]);
Related
I'm building a blog on Laravel 7 and when I try to create a post I get this error:
Call to a member function categories() on bool
Here is my store method from my controller:
public function store(Request $request)
{
// Validate incoming data
$this->validate($request, [
'title' => 'required',
'image' => 'required',
'categories' => 'required',
'body' => 'required',
]);
$data = array();
$data['title'] = $request->title;
$data['slug'] = str_slug($request->title);
$data['user_id'] = Auth::id();
$data['meta_title'] = $request->meta_title;
$data['meta_description'] = $request->meta_description;
$image = $request->file('image');
$data['body'] = $request->body;
$data['created_at'] = \Carbon\Carbon::now();
$slug = str_slug($request->title);
if($image) {
$image_name = $slug . "-" . date('dmy_H_s_i');
$ext = strtolower($image->getClientOriginalExtension());
$image_full_name = $image_name . '.' . $ext;
$upload_path = "public/assets/frontend/uploads/posts/";
$image_url = $upload_path . $image_full_name;
$success = $image->move($upload_path, $image_full_name);
$data['image'] = $image_url;
$post = DB::table('posts')->insert($data);
$post->categories()->attach($request->categories);
return redirect(route('admin.posts.index'))->with('successMsg', 'Post has been saved successfully!');
}
}
The laravel error page has a problem with this line:
$post->categories()->attach($request->categories);
I have a separate table in my database to connect a post id with a category id, it's called category_post
The post content is inserted into the database except the new record in the category_post table
So how do I change that code to work?
Thanks
DB::table('posts')->insert($data);
Returns true|false based on successful / failed execution of query. If you want to write like
$post->categories()->attach($request->categories);
Then you need mode Post and create instance like this:
$post = new Post;
$post->title = $request->title;
// ...
$post->save();
And then you will have instance of Post class
//Controller
public function create(Request $request)
{
// dd($request->all());
$this->validate($request, [
'emp_nm' => 'required',
'emp_email' => 'required | email',
'emp_password' => 'required' ,
'mobile' => 'required | max:20' ,
'emp_type_id' => 'required',
'emp_img' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
]);
$employee = new Employee();
$employee->emp_nm = $request->input('emp_nm');
$employee->emp_email = $request->input('emp_email');
$employee->emp_password = Hash::make($request->input('emp_password'));
$employee->mobile = $request->input('mobile');
$employee->emp_type_id = $request->input('emp_type_id');
if ($request->hasfile('emp_img')) {
$file = $request->file('emp_img');
$extention = $file->getClientOriginalExtension(); // get img extension
$filename = time() . '.' . $extention;
$file->move('upload/employee/',$filename);
$employee->emp_img = $filename;
}else{
return $request;
$employee->emp_img = '';
}
$employee->save();
$id = $employee->id;
$created_at = $employee->created_at;
$updated_at = $employee->updated_at;
$post = Employee::find($id);
// $created = Employee::get('created_at');
// $updated = Employee::get('updated_at');
$employee = DB::table('employees')->get();
$admin = new Admin();
$admin->name = $request->input('emp_email');
$admin->password = $request->input('emp_password');
$admin->employee_id = $post;
// $admin->created_at = $created;
// $admin->updated_at = $updated;
$admin->save();
return redirect()->back();
}
//ERROR
SQLSTATE[22007]: Invalid datetime format: 1366 Incorrect integer
value:
'{"id":1,"emp_nm":"admin","emp_email":"admin#gmail.com","emp_password":"$2y$10$NLkdEn1ohHvHKU/uummrvOrwhJ3iEy7PPfxpk9dj9u6.pOVu1' for column mycrm.admins.employee_id at row 1 (SQL: insert into
admins (name, password, employee_id, updated_at,
created_at) values (admin#gmail.com, admin#1234#,
{"id":1,"emp_nm":"admin","emp_email":"admin#gmail.com","emp_password":"$2y$10$NLkdEn1ohHvHKU/uummrvOrwhJ3iEy7PPfxpk9dj9u6.pOVu10YTa","mobile":9426399403,"emp_type_id":"1","emp_img":"1581590201.jpg","created_at":"2020-02-13
10:36:41","updated_at":"2020-02-13 10:36:41"}, 2020-02-13 10:36:41,
2020-02-13 10:36:41))
In the Controller the code is inserting 2 tables at the same time now it is return the error of date formate if i am assign date so it is..
Unexpected data found.
Trailing data
so how i can solve this error??
Your code is wrong $admin->employee_id = $post;
Try to use $admin->employee_id = $post->id;
Your first table insertion is correct. But when you insert record in the admin is wrong:
So update your code:
$id = $employee->id;
$admin = new Admin();
$admin->name = $request->input('emp_email');
$admin->password = $request->input('emp_password');
$admin->employee_id = $id;
$admin->created_at = $created;
$admin->updated_at = $updated;
$admin->save();
I want to Update an image using Laravel storage file system in my admin data. However, there's an error when I attempt to upload an image
Iam using Laravel 5.7
Here is my create, the create is success
public function store(Request $request)
{
//
$product = new \App\Product;
$product->product_name = $request->get('product_name');
$product->desc = $request->get('desc');
$product->stock = $request->get('stock');
$product->price = $request->get('price');
$product->category = $request->get('category');
$img = $request->file('img');
$new_name = rand() . '.' . $img->getClientOriginalExtension();
$img->move(public_path('img'), $new_name);
$product->img = $new_name;
$product->save();
return redirect('admin')->with('success', 'Data Produk telah ditambahkan');
}
Here is my update
public function update(Request $request, $id)
{
//
$product = $request->all();
$product= \App\Product::find($id);
$new_name = $request->file('img')->getClientOriginalName();
$destinationPath = 'img/';
$proses = $request->file('img')->move($destinationPath, $new_name);
if($request->hasFile('img'))
{
$product = array(
'product_name' => $product['product_name'],
'desc'=> $product['desc'],
'stock'=> $product['stock'],
'price'=> $product['price'],
'category'=> $product['category'],
'img' => $new_name,
);
$product->save() ;
return redirect('admin')->with('success', 'Data Produk telah ditambahkan');
}
}
Call to a member function getClientOriginalName() on null
I think there is no image file attach while updating. You can use my code as reference.
Don't forget to check for the input field in your update field.
First check if there is image file or not. Then, go for getting name, extension and other staff.
public function update($id, Request $request)
{
$input = $request->all();
$product= \App\Product::find($id);
if (empty($product)) {
Flash::error('product not found');
return redirect(route('products.index'));
}
if ($request->hasFile('product_img')) {
$fileNameWithExt = $request->file('product_img')->getClientOriginalName();
$filename = pathinfo($fileNameWithExt, PATHINFO_FILENAME);
$extension = $request->file('product_img')->getClientOriginalExtension();
$new_product_img = $filename . '_' . time() . '.' . $extension;
$path = $request->file('product_img')->move('images/products', $new_product_img);
Storage::delete('products/'.$product->product_img);
$input['product_img']= $new_product_img;
}
$product= $this->productRepository->update($input, $id);
Flash::success('product updated successfully.');
return redirect(route('products.index'));
}
I have some problem with updating file. I have a form with the following attributes :
title
text
pdf file
The problem is the update operation will save the pdf file as the following value :
with file : ["example.pdf"]
no file : [""]
It will include [""] to the pdf file value when updated.
I want the pdf file updated to a new file when a new file is selected, old file remained when there is no new file selected and null value to file when there is no file, to begin with.
Here is the update controller.
public function update()
{
if (Auth::check()) {
$user_id = Auth::user()->id;
$main_id = Input::get('edit_id');
$announcements = Announcement::find($main_id);
$getFile = Input::file('new_brochure');
$rules = array(
'title' => 'required',
'text' => 'required',
);
$validator = Validator::make(Input::all(), $rules);
if ($validator->fails()) {
return back()->withInput()
->withErrors($validator)
->withInput();
}
if ($getFile) {
$file = array('new_brochure' => Input::file('new_brochure'));
$destinationPath = 'img/brochures/announcements'; // upload path
$extension = Input::file('new_brochure')->getClientOriginalExtension();
$fileName = rand(11111,99999).'.'.$extension; // renaming image
Input::file('new_brochure')->move($destinationPath, $fileName);
$announcements->brochure = $fileName;
}
$old = Announcement::where('id',$main_id)->pluck('brochure');
if (empty($old)) {
$announcements->brochure = null;
}
else {
$announcements->brochure = $old;
}
$announcements->title = (Input:: get('title'));
$announcements->from = (Input:: get('from'));
$announcements->to = (Input:: get('to'));
$announcements->text = (Input:: get('text'));
$announcements->is_active = '1';
$announcements->created_by = $user_id;
$announcements->updated_by = $user_id;
$current_date = date("Y-m-d H:i:s");
$announcements->created_at = $current_date.".000";
if ($announcements->save()){
$this->request->session()->flash('alert-success', 'Updated successfully!');
}
else{
$this->request->session()->flash('alert-warning', 'Could not update!');
}
return redirect()->route('Announcements_view');
}
}
What am I doing wrong in this code? Please help me. Thank you.
Change this:
$old = Announcement::where('id',$main_id)->pluck('brochure');
To:
$old = Announcement::where('id',$main_id)->value('brochure');
The thing is pluck() will return a collection of brochure, not a string. And value() will return a string or null.
public function update()
{
if (Auth::check()) {
$user_id = Auth::user()->id;
$main_id = Input::get('edit_id');
$announcements = Announcement::find($main_id);
$getFile = Input::file('new_brochure');
$rules = array(
'title' => 'required',
'text' => 'required',
);
$validator = Validator::make(Input::all(), $rules);
if ($validator->fails()) {
return back()->withInput()
->withErrors($validator)
->withInput();
}
if (!empty(Input::file('new_brochure'))) {
$file = array('new_brochure' => Input::file('new_brochure'));
$destinationPath = 'img/brochures/announcements'; // upload path
$extension = Input::file('new_brochure')->getClientOriginalExtension();
$fileName = rand(11111,99999).'.'.$extension; // renaming image
Input::file('new_brochure')->move($destinationPath, $fileName);
$announcements->brochure = $fileName;
}
else
$old = Announcement::where('id',$main_id)->value('brochure');
$announcements->brochure = $old;
}
$announcements->title = (Input:: get('title'));
$announcements->from = (Input:: get('from'));
$announcements->to = (Input:: get('to'));
$announcements->text = (Input:: get('text'));
$announcements->is_active = '1';
$announcements->created_by = $user_id;
$announcements->updated_by = $user_id;
$current_date = date("Y-m-d H:i:s");
$announcements->created_at = $current_date.".000";
if ($announcements->save()){
$this->request->session()->flash('alert-success', 'Updated successfully!');
}
else{
$this->request->session()->flash('alert-warning', 'Could not update!');
}
return redirect()->route('Announcements_view');
}
}
Ok, when insert data in the database, in the form of my field is to image, but if you insert data without image, appears to me the following error.
Call to a member function getClientOriginalName() on a non-object
public function store() {
$unos = Input::all();
$obavezno = array('name' => 'required',
'number' => 'required|unique:os',
'zajednica' => 'required',
'slika' => 'image|size:3000',
);
$valid = Validator::make($unos, $obavezno);
if($valid->passes()) {
$biraci = new Biraci();
$filename = Input::file('slika')->getClientOriginalName();
$biraci->name = Input::get('name');
$biraci->slika = Input::file('slika')->move('public/uploads', $filename);
$biraci->path = $filename;
$biraci->number = Input::get('number');;
$biraci->zajednica = Input::get('zajednica');
$biraci->save();
return Redirect::to('biraci/dodaj')->with(array('ok' => 'Birac je uspjesno dodat.'));
} else {
return Redirect::to('biraci/dodaj')->withErrors($valid);
}
}
Try this:
if($valid->passes()) {
$biraci = new Biraci();
if (Input::hasFile('slika')) {
$filename = Input::file('slika')->getClientOriginalName();
}
$biraci->name = Input::get('name');
$biraci->slika = isset($filename) ? Input::file('slika')->move('public/uploads', $filename); : null;
$biraci->path = isset($filename) ? $filename : null;
$biraci->number = Input::get('number');;
$biraci->zajednica = Input::get('zajednica');
$biraci->save();
}
$filename = Input::file('slika')->getClientOriginalName();
// change to
$filename = Input::hasFile('slika') ? Input::file('slika')->getClientOriginalName() : null;