2
votes

I'm trying to call save method on an object of a Model Complaints Model to update a specific resource in Database but when I send a POST request on api url it gives this error

BadMethodCallException: Method Illuminate\Database\Eloquent\Collection::save does not exist.

I also tried calling update method but same error.

Code for edit:

$complaint = Complaint::where('complaint_id', $request->input('id'))->get();

            $complaint->title = $request->input('Complaint_Subject');
            $complaint->description = $request->input('Complaint_Details');
            $complaint->address = $request->input('Complaint_Address');

            $complaint->update();

            return [
                'save_status' => "success"
            ];

the very first line is returning the response and correct response.

AND

also I'm trying to call delete or destroy method to delete the resource but it also gives the same error

BadMethodCallException: Method Illuminate\Database\Eloquent\Collection::delete does not exist.

or

BadMethodCallException: Method Illuminate\Database\Eloquent\Collection::destroy does not exist.

Code for delete:

$complaint = Complaint::where('complaint_id', $request->input('id'))->get();
            $complaint->destroy($request->input('id'));

            return [
                'request_status' => 'success',
                'complaint' => $complaint
            ];

here also the response is being returned correctly.

Note that the complaint_id is not Primary Key in the table so I cannot simply call Complaint::find($request->input('id')) I must have to cross check with this complaint_id column value to find the resource. I have been searching since yesterday but could not find any solution. How can I solve this problem. Thanks!!!

3
"on an object of a Model" You're actually not, the errors state that those are Eloquent\Collection, not a Model. Try replacing ->get() with ->first()brombeer
try my answer. It will work.Senthur
YEP IT'S WORKING !!!! THANKSS!!!!!!!!!!!Abdullah

3 Answers

3
votes

If your $complaint is a collection of output. So save didn't work for this if you change your code like $complaint = Complaint::where('complaint_id', $request->input('id'))->first(); Then save() will work.

1
votes

just use first() instead of get()

Complaint::where('complaint_id', $request->id)->first()

1
votes

In your query

$complaint = Complaint::where('complaint_id', $request->input('id'))->get();

it returns Associative Arrays

But if you use

$complaint = Complaint::where('complaint_id', $request->input('id'))->first();

it returns Indexed or Numeric Arrays. Then you have to use $complaint[0]->destroy($request->input('id')); or $complaint[1]->destroy($request->input('id')); and so one