Reputation: 25
I want to delete a row from table. The function I used in controller is:
public function destroy($id) {
$category = Category::find($id);
$category->delete();
return redirect()->back();
}
However it throws me an error:
Call to a member function delete() on null
When I use this code:
public function destroy($id) {
$category = Category::find($id);
dd($id);
}
It is showing the correct id i.e.
"1"
And when I use
public function destroy($id) {
$category = Category::find($id);
dd($category); // or
dd(Category::find($id);
}
I get the output
null
on the screen.
Upvotes: 0
Views: 5807
Reputation: 71
What worked for me is the following (I ensured that the $id was passing from the view):
public function destroy($id)
{
$vendor = Vendor::findorFail($id);
$vendor->delete():
}
for some reason when I did the following it showed null
public function destroy($id)
{
$vendor = Vendor::find($id);
$vendor->delete():
}
This is the view part:
{!! Form::open(array(
'style' => 'display: inline-block;',
'method' => 'DELETE',
'onsubmit' => "return confirm('".trans("global.app_are_you_sure")."');",
'route' => ['vendor.destroy', $vendor->vendor_id])) !!}
{!! Form::submit(trans('global.app_delete'), array('class' => 'btn btn-xs btn-danger')) !!}
{!! Form::close() !!}
Upvotes: 0
Reputation: 66
As mentioned in comments, the error you're getting is probably due to no category exists in the database for the given ID.
Then, when you try to find the category for that ID:
$category = Category::find($id);
The value of $category
variable is null
. Therefore, you get an error for trying to call delete()
method on null
. Under the hood, it would be the same as doing the following:
null->delete();
Which, doesn't work.
You could check the value of $category
before trying to delete it. Or you may use a query to delete all records matching a given condition, in your case id = $id
. This way:
public function destroy($id)
{
Category::where('id', $id)->delete();
return redirect('/')->back();
}
Refer to Deleting Models By Query in the Eloquent docs for details on how that works.
Upvotes: 2