简体   繁体   中英

How to properly update a model on laravel? Method Illuminate\Database\Eloquent\Collection::update does not exist

I made a page for a user to update his company information, all companies default values are null, when a user is created. When a user fills the information, i get this error:

 Method Illuminate\Database\Eloquent\Collection::update does not exist 

I am sure this error is because of my CompanyController@edit

     public function edit(Request $request)
{
    $this->validate($request, [
        'company_name' => 'alpha|max:50',
        'phone' => 'integer|max:50',
        'gst_hst_number' => 'integer|max:50',
        'country' => 'alpha|max:50',
    ]);

    $companies = Company::where('id', Auth::user()->id)->get();

    $companies->update([
        'company_name' => $request->input('company_name'),
        'phone' => $request->input('phone'),
        'gst_hst_number' => $request->input('gst_hst_number'),
        'country' => $request->input('country')
    ]);

    return redirect()->route('company.index')->with('info', 'Company information was updated.');
}

I am stuck quite some time on this issue, would gladly apriciate help and information how to properly update my company models fillable fields.

‌As the error message says, you are using the update method on a collection , you have to change the select query to this:

$companies = Company::where('id', Auth::user()->id)->first();

Because the get() method returns a collection, not a single record.

Try this. ->get() is for multiple collections here you can directly update your records.

$companies = Company::where('id', Auth::user()->id)->update([
    'company_name' => $request->input('company_name'),
    'phone' => $request->input('phone'),
    'gst_hst_number' => $request->input('gst_hst_number'),
    'country' => $request->input('country')
]);;

Your using update method on collection, but collection doesn't have update method,

what you need is remove the get() , so you can use update method on eloquent builder:

$companies = Company::where('id', Auth::user()->id);
$companies->update([
        'company_name' => $request->input('company_name'),
        'phone' => $request->input('phone'),
        'gst_hst_number' => $request->input('gst_hst_number'),
        'country' => $request->input('country')
]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM