无法通过视图() - >分享在App \ Http \ Controllers \ Controller中共享Auth :: check()

时间:2016-10-23 14:15:30

标签: php laravel laravel-5 laravel-5.3

我想在每个视图中分享 Auth :: check()结果作为 $ signedIn 变量,我发现我可以通过Laravel中的父控制器来完成。它运行良好,但它不想用于 Auth :: check() - 它什么都不返回。

父控制器的代码     

    namespace App\Http\Controllers;

    use Illuminate\Foundation\Bus\DispatchesJobs;
    use Illuminate\Routing\Controller as BaseController;
    use Illuminate\Foundation\Validation\ValidatesRequests;
    use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
    use Illuminate\Support\Facades\Auth;


    class Controller extends BaseController
    {
        use AuthorizesRequests, DispatchesJobs, ValidatesRequests;

        public function __construct()
        {
            view()->share('signedIn', Auth::check());
        }
    }

视图代码,其中我使用前面提到的$ signedIn变量

@if($signedIn)

    @include('question.answer-form')

@else

    <div class="alert alert-warning">
        <p>
            <a href="{{ url('login') }}">Sign in</a> in order to answer a question
        </p>
    </div>

@endif

在控制器的构造函数中,我从中重定向到视图,我调用了一个父构造函数 - 问题是它不想用于 Auth :: check()

Laravel 5.3v。

3 个答案:

答案 0 :(得分:2)

您应该在服务提供商启动方法中分享要分享的电话

来源:https://laravel.com/docs/5.3/views#sharing-data-with-all-views

<?php

namespace App\Providers;

use Illuminate\Support\Facades\View;
use Illuminate\Support\Facades\Auth;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        View::share('signedIn', Auth::check());
    }

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        //
    }
}

答案 1 :(得分:1)

Auth::check()结果传递给视图没有任何意义,因为默认情况下Auth在所有视图中都可用,auth()全局帮助器也是如此。因此,只需在任何Blade视图中使用其中一个检查。他们都这样做:

@if (Auth::check())
@if (auth()->check())
@if (Auth::user())
@if (auth()->user())

答案 2 :(得分:1)

您无法访问控制器构造函数中的会话或经过身份验证的用户,因为中间件尚未运行。

试试:

public function __construct()
{
     $this->middleware(function ($request, $next) {
          view()->share('signedIn', Auth::check());

          return $next($request);
     });
}

Docs