![](/img/trans.png)
[英]Laravel - Allow only the owner of the note to view it and edit it: Middleware or FormRequests?
[英]Laravel 5 Middleware “Owner”?
我在创建“所有者”中间件时遇到了麻烦。
例如,我有一个与user_id
键关联的Articles
和User
模型。
我想将“所有者”中间件添加到ArticlesController
,因此该ArticlesController
的唯一所有者可以编辑,更新和删除它。
我一直在寻找这个问题,但从未找到过可行的代码。 他们中的一些人试图使其与Form Requests一起使用,但我对使用中间件感兴趣。
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
});
或者你可以使用路由和中间件参数 ,它有一些优点:
这是中间件( 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']]);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.