php Laravel 9:无法以超级管理员身份删除(spatie Laravel-permission)

bqf10yzr  于 2023-04-19  发布在  PHP
关注(0)|答案(1)|浏览(201)

我使用Laravel 9与微风和包空间Laravel-permission.我已经创建了2个角色,其中一个是超级管理员角色谁应该能够做的一切.

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;
        }
    });
    }
}

但是,当我试图使用CRUD从表中删除一行“注解”时,我创建了:它似乎不工作(没有错误消息或任何东西,但什么也没发生)
刀片式服务器,其中要删除的按钮为:

@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::resource('comments', App\Http\Controllers\CommentController::class);
控制器中的销毁功能:

public function destroy(Comment $Comment)
    {
        $Comment->delete();

        return redirect()->route('comments.index')
                        ->with('success','Comment deleted successfully');
    }

型号:

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'
    ];
}

我不认为问题来自Eloquent(ORM),因为当我使用all()函数时,它似乎像它应该的那样工作,权限似乎也没问题。

qhhrdooz

qhhrdooz1#

您使用了错误的端点。a元素的href属性使用GET方法发送请求。因此您没有将请求发送到destroy端点。
您需要使用表单并传递@method刀片指令,指定DELETE方法:

<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>

相关问题