Reputation: 448
I am trying to delete a category by clicking on a button
Blade:
<td class="center"><a href="{{URL::to('/deletecat/'.$category->name) }}"><span class="glyphicon glyphicon-trash"></span></a></td>
Route:
Route::get('/deletecat/{name}','CategoryController@delete');
Controller:
public function delete($name)
{
category::find($name)->delete();
return Redirect::route('managecategory');
}
but I am getting an error while clicking on a button that
Call to a member function delete() on a non-object
Any help appreciated.
Upvotes: 9
Views: 59102
Reputation: 1418
In your view: it has to be a form to submit a POST request like below:
<form action="/deletecat/{{$data->id}}" method="post">
@csrf
@method('DELETE')
<input type="submit" value="delete " >
</form>
Because this is POST Request has to use csrf and delete action.
In your route, it has be with delete() method,followwing with the controller.
Route::delete('/deletecat/{name}', 'CategoryController@destory');
In the controller:
public function destory($name)
{
category::find($name)->delete();
return Redirect::route('managecategory');
}
This is how laravel name format role:
Upvotes: 0
Reputation: 46
The error is obviously because of the returned NON-OBJECT.
::find($name) returns an empty object or null
This is because the search was empty.
Make sure name is the primary key in order to use find.
Otherwise:
use ::where('name', $name)->delete();
or:
::where('name','=', $name)->delete();
*I pointed =
because if you ever need to search different than =
use >=
<>
and so on...
Secondly, it is not very important to use destroy
. It is recommended but not a must-have!
Upvotes: 0
Reputation: 33186
The ::find($id)
method expects $id
to be a number, the primary key of the row you want to find.
If you want to delete a row by name, you should use the following code:
category::where('name', $name)->delete();
Upvotes: 22