I use Laravel 9 with Breeze and the package spatie Laravel-permission. I have created 2 roles and one of them is a super-admin role who should be able to do everything.
class AuthServiceProvider extends ServiceProvider
{
/**
* The model to policy mappings for the application.
*
* @var array<class-string, class-string>
*/
protected $policies = [
// 'App\Models\Model' => 'App\Policies\ModelPolicy',
];
/**
* Register any authentication / authorization services.
*
* @return void
*/
public function boot()
{
$this->registerPolicies();
// Implicitly grant "Super-Admin" role all permission checks using can()
Gate::before(function ($user, $ability) {
if ($user->hasRole('Super-Admin')) {
return true;
}
});
}
}
But when I tried to delete a row from my table "comments" using the CRUD than I had created: it doesn't seems to work (no error message or anything but nothing happen)
Blade where the button to delete is:
@foreach ($comments as $comment)
<tr>
<td>"{{ $comment->com }}"</td>
<br>
@hasrole('user')
USER
@endhasrole
@hasrole('Super-Admin')
<a class="btn btn-primary" href="{{ route('comments.destroy',$comment->id) }}">Delete</a>
@endhasrole
</tr>
@endforeach
Route I use for the controlleur:
Route::resource('comments', App\Http\Controllers\CommentController::class);
destroy function in controller:
public function destroy(Comment $Comment)
{
$Comment->delete();
return redirect()->route('comments.index')
->with('success','Comment deleted successfully');
}
Model:
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Comment extends Model
{
use HasFactory;
protected $fillable = [
'user_id', 'com'
];
}
I dont think the problem come from Eloquent(ORM) because when I use the all() function it seems to work like it should and the permissions seems to also be ok.
You are using wrong endpoint. href
attribute of a
element sends the request using GET
method. So you are not sending the request to destroy
endpoint.
You need to use a form and pass the @method
blade directive specifying DELETE
method:
<form action="{{ route('comments.destroy', $comment->id) }}" method="POST">
@csrf
@method('DELETE')
@hasrole('Super-Admin')
<button type="submit" class="btn btn-danger">Delete</button>
@endhasrole
</form>