简体   繁体   中英

Laravel: dependency injection of logged user?

Is this possible to be less boilerplate in controllers when current user must be known?

class FooController extends Controller
{
    function index(Request $request) {
        $user = Auth::user(); // <------
        return Foo::where('user_id', $user->id)->get()->toArray();
    }
}

Is this possible to receive $user directly from a dependency injection?

You can do so from the Request class

$user = $request->user();

OR - using helper functions

$user = auth()->user();

in Controller.php you can add protected property

protected $user;


public function __construct()
{
    $this->user = auth()->user ?? null;
}

then in all contoller you can do $this->user

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM