我正在开发一个项目,该项目有一个带有顶栏的控制面板,其中包含有关用户的详细信息,如用户名、电子邮件、图像网址等。此顶栏几乎在所有控制面板 View 上运行。现在在每个控制面板 Controller 中我都会做这样的事情
/***** PostController *********/
class PostController extends Controller
{
protected $user;
public function __construct()
{
$user = Auth::user(); // Note: here $user is not a global variable
$this->user['user_name'] = $user->name;
$this->user['user_email'] = $user->email;
$this->user['user_role'] = $user->getRolesName()->first();
$this->user['user_image'] = $user->image;
}
然后在索引 Controller 中,我将传递当前用户的角色以及帖子详细信息,如下所示。
public function index()
{
$user = $this->user;
$posts = json_decode( Post::with('author')->get()->toJson() );
return view('globaladmin.posts.viewposts',compact('posts'), $user);
}
我认为可能有更好的方法来做到这一点(也许是像存储库这样的设计模式),就像任何帮助一样,我们将不胜感激。
最佳答案
您可以使用称为 View 共享的东西。如果您查看文档 ( http://laravel.com/docs/master/views#sharing-data-with-all-views ),您将能够创建一个可以在其中放置代码的服务提供者。
一个快速(可能很脏)的修复是使用 app\Http\Controllers\Controller.php ,如下所示:
public function __construct()
{
$user = Auth::user(); // Note: here $user is not a global variable
$global_user = [];
if ($user !== null) {
$global_user['user_name'] = $user->name;
$global_user['user_email'] = $user->email;
$global_user['user_role'] = $user->getRolesName()->first();
$global_user['user_image'] = $user->image;
}
view()->share('global_user', $global_user);
}
编辑:要在 Blade 中使用它,类似这样的东西会起作用:
@if($global_user)
{!! $global_user->user_name !!}
@endif
关于php - 在某些 Controller 上运行某些代码的最佳方式 - Laravel 5,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33538205/