php - laravel 中的命名空间控制器和路由
问题描述
假设,我有一个模型“Post”,并为它创建了两个资源控制器——User/PostController 和 Admin/PostController。
所以当我想消耗资源时,我的路线看起来像这样:
/user/post/:id
/admin/post/:id
根据惯例这是正确的还是我做错了?
解决方案
当用户具有不同的访问类型时,这是我在 Laravel 中解决这个问题的方法。
假设我们有一个像您这样的模型,称为 Post。现在我们要做的是,为该模型添加一个范围,我们将在此处进一步定义:
use App\Scopes\AdminScope;
class Post extends Model {
// Apply a global scope to this controller
protected static function boot(){
parent::boot();
static::addGlobalScope(new AdminScope);
}
在路由器中,您将其定义为常规资源路由:
Route::resource('posts', 'PostsController');
在 Controller 中,您可以像往常一样获取 index 方法上的所有帖子。这将在我们创建管理范围后,为管理员用户返回系统中的所有帖子,为普通用户返回属于特定用户的帖子:
class PostsController extends Controller {
public function index(){
$posts = Post::all();
}
No 是根据登录的用户类型区分是返回系统中的所有帖子还是只返回属于当前用户的帖子的部分:
在您的应用程序文件夹中创建一个名为 Scopes 的新文件夹。在此文件夹中,创建一个名为 AdminScope.php 的新文件,该文件如下所示:
namespace App\Scopes;
use Illuminate\Database\Eloquent\Scope;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Builder;
use Auth;
class AdminScope implements Scope
{
/**
* Apply the scope to a given Eloquent query builder.
*
* @param \Illuminate\Database\Eloquent\Builder $builder
* @param \Illuminate\Database\Eloquent\Model $model
* @return void
*/
public function apply(Builder $builder, Model $model)
{
// IF THE CURRENT USER TYPE IS NOT ADMIN, ALTER THE QUERIES:
if( Auth::user()->type != "admin" ){
$builder->where('user_id', '=', Auth::user()->id)
}
}
}
当然,您需要更改最后一个文件以满足区分普通用户和管理员的要求。
这种方法的好处是,您现在可以将此 Scope 应用于您认为合适的任何模型,并且它将更改非管理员用户的所有查询,以仅显示他们拥有的模型应用范围。
笔记:
这是一个全局范围,它将应用于所有已添加它的 Eloquent 模型,以及针对该模型进行的所有查询。如果需要,您还可以编写条件本地范围,您可以在此处阅读更多信息:
推荐阅读
- r - R:来自 seq() 函数的“length.out”参数无法正常工作
- maven - 构建dss库最新版本
- visual-studio-code - VS Code 侧边栏前景色变暗(使用 FireFly Pro Midnight)
- firebase - firebase fetchSignInMethodsForEmail 返回什么?
- javascript - 如何在 lit-element css 样式属性中导入 CSS 框架?
- python - 使用带有回调函数的 python pool.apply_async() 的最佳实践
- php - PHP - 如何在类方法中调用外部名称空间?
- python - Python:在解决 EOFError 后,代码在 while 循环的第二次运行中不要求输入
- django - 根据用户的属性迭代 Django 模板中的上下文变量
- python - Keras:什么是“浅层结构”?