Laravel 5中间件"Owner"?

Laravel 5 Middleware "Owner"?

我在创建 "owner" 中间件时遇到了问题。

例如,我有一个 ArticlesUser 模型与 user_id 键关联。

我想将 "owner" 中间件添加到 ArticlesController,以便该文章的唯一所有者可以编辑、更新和删除它。

我已经搜索这个问题一段时间了,但从未找到有效的代码。 他们中的一些人试图让它与表单请求一起工作,但我对使用中间件很感兴趣。

  1. 创建中间件:
php artisan make:middleware OwnerMiddleware
namespace App\Http\Middleware;

use App\Article;
use Closure;
use Illuminate\Contracts\Auth\Guard;

class OwnerMiddleware
{
    /**
     * The Guard implementation.
     *
     * @var Guard
     */
    protected $auth;

    /**
     * Create a new filter instance.
     *
     * @param  Guard  $auth
     * @return void
     */
    public function __construct(Guard $auth)
    {
        $this->auth = $auth;
    }

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $articleId = $request->segments()[1];
        $article = Article::findOrFail($articleId);

        if ($article->user_id !== $this->auth->getUser()->id) {
            abort(403, 'Unauthorized action.');
        }

        return $next($request);
    }
}
  1. 将其添加到 app\Http\Kernel.php:
protected $routeMiddleware = [
    'owner' => 'App\Http\Middleware\OwnerMiddleware',
];
  1. 在路由中使用中间件:
Route::group(['middleware' => ['owner']], function() {
    // your route
});

或者你可以使用 route 和 middleware parameters,它有一些优点:

  • 即使请求结构发生变化,您的中间件仍然可以工作
  • 中间件可重复用于不同的资源
  • 您可以在控制器中使用它

这是中间件(app/Http/Middleware/AbortIfNotOwner.php):

<?php

namespace App\Http\Middleware;

use Closure;

class AbortIfNotOwner
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @param  string    $resourceName
     * @return mixed
     */
    public function handle($request, Closure $next, $resourceName)
    {
        $resourceId = $request->route()->parameter($resourceName);

        $user_id = \DB::table($resourceName)->find($resourceId)->user_id;

        if ($request->user()->id != $user_id) {
            abort(403, 'Unauthorized action.');
        }

        return $next($request);
    }
}

里面 app\Http\Kernel.php:

protected $routeMiddleware = [
     'owner' => 'App\Http\Middleware\AbortIfNotOwner',
];

在你的路由文件中(app/Http/routes.php):

Route::group(['middleware' => ['owner:articles']], function() {
    // your route
});

并可选择在控制器中调用它:

public function __construct()
{
    $this->middleware('owner:articles', ['only' => ['edit', 'update']]);
}