Laravel 5.3: How to use Auth in Service Provider?

不问归期 提交于 2019-12-19 11:27:07

问题


I am passing a value in shared view by taking value from table. I need to know user ID for the purpose but Auth::check() returns false. How do I do it? Below is code:

public function boot()
    {
        $basket_count = 0;
        if (Auth::check()) { //always false
            $loggedin_user_id = Auth::user()->id;
            $basket_count = Cart::getBasketCount();
        }
        view()->share('basket_count', $basket_count);
    }

回答1:


OK turns out that ServiceProviders are not place for such things. The best thing is a Middleware. So if you want to call Auth, create middleware and pass value to views.

public function handle($request, Closure $next)
    {            
        $basket_count = 0;
        if ($this->auth) { //always false
            $loggedin_user_id = $this->auth->user()->id;
            $basket_count = Cart::getBasketCount($loggedin_user_id);
        }
        view()->share('basket_count', $basket_count);

        return $next($request);
    }



回答2:


You can use authentication directly in the controller file. Adding it in the middleware is a cleaner way of doing the authentication.

For eg. In CategoriesController.php

...

class CategoryController extends Controller {

/**
 * CategoryController constructor.
 */
public function __construct()
{
    $this->middleware('auth');
}

...

If you want to have a look at a complete example http://deepdivetuts.com/basic-create-edit-update-delete-functionality-laravel-5-3



来源:https://stackoverflow.com/questions/41588918/laravel-5-3-how-to-use-auth-in-service-provider

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!