我在创建“所有者”中间件方面遇到了麻烦。
例如,我有一个与Articles
密钥相关联的User
和user_id
模型。
我想将“所有者”中间件添加到ArticlesController
,因此该文章的唯一所有者可以编辑,更新和删除它。
我一直在寻找这个问题,但从未找到过可行的代码。 他们中的一些人试图使其与Form Requests一起使用,但我对使用中间件感兴趣。
答案 0 :(得分:8)
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);
}
}
app\Http\Kernel.php
:protected $routeMiddleware = [
'owner' => 'App\Http\Middleware\OwnerMiddleware',
];
Route::group(['middleware' => ['owner']], function() {
// your route
});
答案 1 :(得分:5)
或者你可以使用路由和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']]);
}