Reputation: 62
I want to share in every view Auth::check() result as a $signedIn variable, i found that i can do it via Parent Controller in Laravel. It works good, but it doesn't want to work for Auth::check() - it returns nothing.
Code for a parent Controller
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());
}
}
Code of the view, in which i use $signedIn variable mentioned before
@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
In the constructor of the controller, from which i redirect to the view, i've called a parent constructor - the problem is that it doesn't want to work for Auth::check().
Laravel 5.3v.
Upvotes: 2
Views: 140
Reputation: 3024
You can't access the session or authenticated user in your controller's constructor because the middleware has not run yet.
try that :
public function __construct()
{
$this->middleware(function ($request, $next) {
view()->share('signedIn', Auth::check());
return $next($request);
});
}
Upvotes: 1
Reputation: 225
You should place calls to share within a service provider's boot method
source: 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()
{
//
}
}
Upvotes: 2
Reputation: 163898
Passing Auth::check()
result to the views doesn't make any sense since Auth
is available in all views by default, so does auth()
global helper. So just use one of these checks in any Blade view. They all do the same:
@if (Auth::check())
@if (auth()->check())
@if (Auth::user())
@if (auth()->user())
Upvotes: 1