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.
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);
});
}