on my web page there are 3 options available, Login, Register and Logout.
If I want to display only the available buttons eg if the user is loged in I only want to show the logout button, but if the user is a guest they need the login and register buttons.
Now I added a provider to check if the user ist authenticated. Here is my code.
<?php
namespace App\Providers;
use View;
use Auth;
use Illuminate\Support\ServiceProvider;
class ShareServiceProvider extends ServiceProvider
{
/**
* Bootstrap the application services.
*
* @return void
*/
public function boot()
{
echo "Provider boot check ";
var_dump(Auth::check());
if(Auth::check())
{
View::share(['loged_in' => true]);
}
else
{
View::share(['loged_in' => false]);
}
}
/**
* Register the application services.
*
* @return void
*/
public function register()
{
//
}
}
But the user is every time shown as a guest. When I make the Auth::check() in other controllers, everything works fine. But I dont want to check it in every controller.
I can offer you an alternative to achieve a solution to your problem, that works within your contraints.
Rather than having it as a service provider, you could have it as a helper function that you can call in your blades or controllers.
Create a helpers.php
file and place it as such app/Http/helpers.php
.
Afterwards add it in your composer.json
inside the autoload
array
"autoload": {
"files": [
"app/Http/helpers.php"
],
composer dump-autoload
, in your terminal afterwards.
Now, inside your helpers.php
file add the following method:
function userLoggedIn(){
$logged_in = false;
if(Auth::check()){
$logged_in = true;
}
return $logged_in;
}
Now, you should be able to use this method inside any controller/blade.
@if(userLoggedIn())
<p>Logged in</p>
@else
<p>Not Logged in</p>
@endif
This way, you are not having to bear the overhead of having to perform an Auth:check in every controller and you can still use it Anywhere you need it in your project.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.