在Laravel中对嵌套路由进行授权,通常涉及到使用中间件来检查用户的权限。以下是实现这一功能的基础概念、优势、类型、应用场景以及解决方案。
app/Policies
目录下。假设我们有一个博客应用,其中有文章(posts)和评论(comments)两个嵌套资源。我们希望只有文章的作者才能编辑或删除自己的文章及其评论。
// app/Policies/PostPolicy.php
namespace App\Policies;
use App\Models\Post;
use Illuminate\Auth\Access\HandlesAuthorization;
class PostPolicy
{
use HandlesAuthorization;
public function update(User $user, Post $post)
{
return $user->id === $post->user_id;
}
public function delete(User $user, Post $post)
{
return $user->id === $post->user_id;
}
}
在AuthServiceProvider
中注册策略:
// app/Providers/AuthServiceProvider.php
namespace App\Providers;
use App\Models\Post;
use App\Policies\PostPolicy;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
use Laravel\Passport\Passport;
class AuthServiceProvider extends ServiceProvider
{
protected $policies = [
Post::class => PostPolicy::class,
];
public function boot()
{
$this->registerPolicies();
Passport::routes();
}
}
// routes/web.php
use App\Http\Controllers\PostController;
use App\Http\Controllers\CommentController;
Route::middleware(['auth'])->group(function () {
Route::resource('posts', PostController::class);
Route::resource('posts.comments', CommentController::class);
});
在控制器中使用中间件来检查权限:
// app/Http/Controllers/PostController.php
namespace App\Http\Controllers;
use App\Models\Post;
use Illuminate\Http\Request;
class PostController extends Controller
{
public function edit(Post $post)
{
$this->authorize('update', $post);
return view('posts.edit', compact('post'));
}
public function update(Request $request, Post $post)
{
$this->authorize('update', $post);
// 更新文章逻辑
}
public function destroy(Post $post)
{
$this->authorize('delete', $post);
// 删除文章逻辑
}
}
通过以上步骤,你可以在Laravel中实现对嵌套路由的授权。
领取专属 10元无门槛券
手把手带您无忧上云