Laravel 5.4:在

编程入门 行业动态 更新时间:2024-10-26 11:28:05
本文介绍了Laravel 5.4:在 __construct() 中获取登录用户 ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我试图在构造函数中访问 Auth::user()->id; 但它总是返回错误试图获取非对象的属性.我在 laravel 文档中研究了 Session 在构造函数中不可访问,并且也在 SO 上搜索了这个.我需要在构造函数中登录用户 ID,因为我必须从数据库中获取数据并使其可用于所有方法.我当前的代码是:

I am trying to access Auth::user()->id; inside constructor but it always return the error Trying to get property of non-object. I study in the laravel documentation that Session is not accessible inside constructor and also search on SO for this. I need logged in user id inside constructor because I have to fetch data from database and make it available for all its method. My current code is :

public function __construct(){ $this->middleware('auth'); $induction_status = TrainingStatusRecord::where('user_id',Auth::user()->id)->where('training','=','induction')->get(); View::share('ind_status',$induction_status); }

有什么方法(简单的方法)可以在构造函数中登录用户 ID.

Is there any way (easy way) to get logged in user id inside constructor.

我将不胜感激.

谢谢

推荐答案

在视图中共享变量 AppServiceProvider 是一个很好的方法

To share a variable in view AppServiceProvider is a good approach

转到AppProvidersAppServiceProvider.php

在页面顶部包含外观

use IlluminateSupportFacadesAuth; use AppTrainingStatusRecord;

并在boot方法中粘贴下面的代码

and paste below code in boot method

view()->composer('*', function($view){ if(Auth::user()){ $induction_status = TrainingStatusRecord::where('user_id',Auth::user()->id)->where('training','=','induction')->get(); View::share('induction_status',$induction_status); } });

现在您可以在您的应用中获取变量 $induction_status.

Now you will be able to get your variable $induction_status in your app.

参考 laravel/docs/5.4/providers#the-boot-method

希望能帮到你.

更多推荐

Laravel 5.4:在

本文发布于:2023-11-14 13:26:10,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1587335.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Laravel

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!