簡體   English   中英

在laravel服務提供商中使用auth

[英]using auth in laravel service provider

每當我嘗試使用\\Auth::User()我得到非對象屬性,因為我的Auth::guest()每當我在服務提供者中使用它時都返回true

use Illuminate\Contracts\View\View;
use Illuminate\Support\ServiceProvider;
use Illuminate\Contracts\View\Factory;
use App\relations;
use App\User;
use DB;
use Illuminate\Support\Facades\Auth;

class RelationServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap the application services.
     *
     * @return void
     */
    public function boot()
    {
        //
        \Auth::User()->id;

        $relation_friend_for_logged_user = DB::select( DB::raw("SELECT * FROM users"));

        $value = "asd";

        // for injecting objct
        View()->share('count', $value);
    }

但是為什么\\Auth::guest()返回true,無論我是否登錄

您可能希望使用View Composer 據我所知,您的服務提供商啟動方法中尚未提供經過身份驗證的用戶。

public function boot(Guard $auth) {
    view()->composer('*', function($view) use ($auth) {
        // get the current user
        $currentUser = $auth->user();

        // do stuff with the current user
        // ...

        // pass the data to the view
        $view->with('currentUser', $currentUser);
    });
}

代碼修改自https://laracasts.com/discuss/channels/general-discussion/how-do-i-get-the-current-authenticated-user-laravel-5

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM