我在创建“所有者”中间件时遇到麻烦。
例如,我有一个Articles
and User
模型关联于user_id
key.
我想将“所有者”中间件添加到ArticlesController
,因此该文章的唯一所有者可以编辑、更新和删除它。
我已经搜索这个问题有一段时间了,但从未找到可以工作的代码。
他们中的一些人尝试使其与表单请求一起使用,但我对使用中间件感兴趣。
- 创建中间件:
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
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)