Laravel 5:如何通过构造函数添加Auth :: user()-> id? [英] Laravel 5: How to add Auth::user()->id through the constructor ?

查看:383
本文介绍了Laravel 5:如何通过构造函数添加Auth :: user()-> id?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以这样获得经过身份验证的用户的ID:

I can get the ID of the authenticated user like this:

Auth::user()->id = $id;

它很好用,但是我有很多需要它的方法,而且我想要一种更干净的方法将它添加到整个类中,因此我可以在每个方法中引用$ id.我本来打算将其放入构造函数中,但是由于Auth :: user是静态的,因此我弄得一团糟,不知道该怎么做.

Great it works, ... but I have a load of methods which need it and I want a cleaner way of adding it to the class as a whole,so I can just reference the $id in each method. I was thinking of putting it into the constructor, but as Auth::user is a static, I am making a mess of things and don't know how to do it.

非常感谢您的帮助!

推荐答案

您可以在整个应用程序中使用Auth :: user().不管你在哪里.但是,针对您的问题,您可以使用controllers文件夹中的'Controller'类.在此处添加构造函数,并引用用户ID.

You can use Auth::user() in the whole application. It doesn't matter where you are. But, in response to your question, you can use the 'Controller' class present in your controllers folder. Add a constructor there and make the reference to the user ID.

<?php namespace App\Http\Controllers;

use Illuminate\Foundation\Bus\DispatchesCommands;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests;

/* Don't forget to add the reference to Auth */
use Auth;

abstract class Controller extends BaseController {

    use DispatchesCommands, ValidatesRequests;

    function __construct() {
        $this->userID = Auth::user()?Auth::user()->id:null;
    }
}

然后,在任何控制器的任何方法中,都可以使用$ this-> userID变量.

Then, in any method of any controller you can use the $this->userID variable.

这篇关于Laravel 5:如何通过构造函数添加Auth :: user()-&gt; id?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆