Laravel 5中间件“所有者"? [英] Laravel 5 Middleware "Owner"?
本文介绍了Laravel 5中间件“所有者"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在创建所有者"中间件时遇到麻烦.
I'm having a trouble with creating the "owner" middleware.
例如,我有一个与user_id
键关联的Articles
和User
模型.
For example, I have a Articles
and User
model associated with user_id
key.
我想将所有者"中间件添加到ArticlesController
,以便该文章的唯一所有者可以对其进行编辑,更新和删除.
I want to add the "owner" middleware to the ArticlesController
, so the only owner of that article can edit, update and delete it.
我一直在搜索此问题已有一段时间,但从未找到可运行的代码. 他们中的一些人试图使其与Form Requests一起使用,但是我对使用Middleware感兴趣.
I've been searching for this issue for a while, but never found the code, which would work. Some of them tried to make it work with Form Requests, but I'm interested in using Middleware.
推荐答案
- 创建中间件:
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
});
这篇关于Laravel 5中间件“所有者"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文