Laravel 5 triggering modal in view conditionally - laravel

I want to check if user is login, if so then display some content, else i want to click a url or call modal.
#if(Auth::check())
.............if user registered display here
#else
I want to click the link below automatically....OR Call a view
<a class="signin_link" href="{{ action('Auth\AuthController#login') }}" rel="get:Loginform"><i class="fa fa-user" style="font-size:20px"></i></a>
#endif

This will redirect your user to the page you want:
#if(Auth::check())
.............if user registered display here
#else
//Redirect user to the link
<script>window.location = "{{ action('Auth\AuthController#login') }}";</script>
#endif
And this would open your modal, if you are using bootstrap for example:
#if(Auth::check())
.............if user registered display here
#else
//Opening a bootstrap modal
<script>$('#myModal').modal('show')</script>
#endif
Note: I assume that you already have your modal html somewhere on your page

While you can do it in the view, you shouldn't. Instead, use the auth middleware (see https://github.com/laravel/laravel/blob/master/app/Http/Middleware/Authenticate.php).
Here's an example:
Route::group(['middleware' => 'auth'], function() {
Route::get('/this/route/needs/a/logged/in/user', 'PageController#account');
});
If there's no user logged in the visitor is redirected to the login page (which you can set in the middleware).

Related

Laravel Dynamic Header

I am new in Laravel. I include Header using #include('header'). but I want to hide profile menu when user is not register. How can I do ?
I use this to get data from table directly in blade.php
$array = App\Table::Select(users)->get();
You can use the Auth facade to determine if the current user is logged in:
header.blade.php
#if(Illuminate\Support\Facades\Auth::check())
<!-- profile menu -->
#endif
Edit: You can use blade directives except the #if to checking user is authenticated or not. like the following:
#auth
<!-- Profile Menu -->
#endauth
If you—for whatever reason— just want to know if some user is registered, change your query to the following:
#if(Profile::find($userId) !== null)
<!-- profile menu -->
#endif
You can use auth facade for this.
#auth // The user is authenticated... #endauth
#guest // The user is not authenticated... #endguest
Simple use this
if(Auth::user())
include('header')
endif

Get current logged-in user in Laravel Layout page

I am using laravel auth application in that layout page is present, So to get name of current logged-in user in layout.blade.php I have use {{Auth :: user () -> name}} and it gives name too. But the problem is that when i get logout and try to login then login page gives error Trying to get property 'name' of non-object.
Please help me.
If no user is logged in so Auth::user() will return null,
so in your blade you can use Auth::check() to verify if a user is logged in
#if(Auth::check())
{{ Auth::user()->name }}
#endif
More info can found in
https://laravel.com/docs/7.x/authentication#retrieving-the-authenticated-user
you can use #auth #endauth helper in blade
#auth
{{ Auth::user()->name }}
#endauth
ref link https://laravel.com/docs/8.x/blade#authentication-directives
You will need to check if User is logged in first
try
#if(auth()->check())
{{auth()->user()->name}}
#endif
or in one line
{{auth()->user()->name ?? ''}}

Laravel 7: How to clear withErrors session

I'm using Gate for permissions and redirect the user to the home if he doesn't have enough permission with an error message
if(Gate::denies('manage-users')){
return redirect(route('home'))->withErrors('You don\'t have enough permissions!');
}
But when the user navigates to another route with correct permission the page displays correctly but with an error handler in the view saying the same message "you don't have enough permissions"
How can I clear errors session once the error get displayed in home to hide it from other views?
Don't know if this is the best solution so please correct me. I Changed the validation to be this
if(Gate::denies('manage-users')){
return redirect(route('home'))->withErrors(['permission_error' => 'You don\'t have enough permissions!']);
}
In the home view
#if(session()->has('permission_error'))
{{session('errors')->get('permission_error')}}
#php session()->forget('permission_error') #endphp
#elseif( !session()->has('permission_error') && $errors->any())
<div class="alert alert-danger">
{{ $errors->first() }}
</div>
#endif

Laravel - Impersonation redirect issue

I currently have an admin panel that allows admins to login via other users accounts and view their accounts as the user would which redirects to a subdomain.
so ill be on the url http://example.local/admin/users which is a list of the users then when you log in as a particular user via this route.
Login as user
Route::get('/users/{id}/login_as', function ($id) {
$user = App\User::withTrashed()->find($id);
$user->changelogs()->create([
'action' => 'Admin logged in as user'
]);
session()->put(['og_user' => auth::user()]);
\Auth::logout();
\Auth::loginUsingId($id);
return redirect('/dashboard');
});
This will then redirect to the users page on how they see the platform but this will change to a sub domain http://subdomain.example.local/.......
I currently have a header that appears once logged in that contains a return to admin button which then logs you out of that user and returns you back to the admin page you was originally on.
Return to admin button
#if(session()->has('og_user') && auth::user())
<div class="signed_in">
<div class="container inner">
<h5 class="text-light mb-0">
Logged-in as {{ auth::user()->name }}
</h5>
<a href="/admin/{{session()->get('og_user')['id']}}/log_in_as" class="btn btn-secondary ml-auto">
Return to admin
</a>
</div>
</div>
#endif
Login as admin
Route::get('/admin/{id}/log_in_as', function ($id) {
session()->forget('og_user');
\Auth::logout();
\Auth::loginUsingId($id);
return back();
});
the problem i am having is once im logged in under another user on a subdomain and then i return to admin it directs me back to the admin page but under the sub domain still http://subdomain.example.local/dashboard with that domains UI theme when i want it to go back to example.local/dashboard
Can anyone point me in the right direction on how to do this?
You use
return back();
This function will return you to the previous page: in your case, the previous page is in the subdomain. So you don't want to go back.
Use a direct link to the page you want to visit instead:
return redirect('your desired route');

Laravel Blade check user role

In laravel Blade templating we can exclude some parts of HTML with this code:
#if (Auth::user())
<li>Mein Profil</li>
<li>Admin</li>
#else
<li>Mein Profil</li>
#endif
If user is authenticated then show home and admin links and if user is not authenticated then show only home link.
My question is how to make a check here if user is admin?
I have default login system from laravel and i just added one more column in table users -> ('admin') with tinyint value 1 and in this video
https://www.youtube.com/watch?v=tbNKRr97uVs
i found the code for checking if user is admin
if (!Auth::guest() && Auth::user()->admin )
and it works in AdminMiddleware.php
but it doesn't work in blade. How to make this working??
I find such a long winded, check if logged in, check role, being added all around my blade files to distracting. You may consider adding a custom blade directive. Add something like this to AppServiceProvider boot() function
Blade::if('admin', function () {
return auth()?->user()?->admin === true;
});
in blade just use
#admin
<p>Only admin sees this</p>
#endadmin
#if (!Auth::guest() && Auth::user()->admin)
<li>Mein Profil</li>
<li>Admin</li>
#else
<li>Mein Profil</li>
#endif
this works just to be clear (just add one more column tinyint 'admin' in user table and set to 1)
You can use the method> HasRole
You can call this from artisan tinker from command line, just to see it before writing code:
php artisan tinker
Check if the user with id 1 has role 'user';
User::find(1)->hasRole('user');
Check if the user with id 1 has role 'admin';
User::find(1)->hasRole('admin');
The same way while coding for example in app.blade template:
#if (Auth::user()->hasRole('admin'))
<li>Main Profile</li>
<li>Admin</li>
#else
<li>Main Profile</li>
#endif
The method hasRoles comes from the package spatie/laravel-permission
composer.json:
"spatie/laravel-permission": "^3.16"
full path of the class:
vendor\spatie\laravel-permission\src\Traits\HasRoles.php

Resources