How to set the session value when the link is clicked? - php

When these links are clicked, we have to enter the mobile number and get the confirmation code, and then enter the desired form. that's mean:
Click on the training menu = enter mobile number > enter verification code > open training form.
Click on the shopping menu = enter mobile number > enter verification code > open shopping form.
Click on the services menu = enter mobile number > enter verification code > open services form.
Click on the counseling menu = enter mobile number > enter verification code > open counseling form.
My question is how to set the session value when the link is clicked
app.blade.php
#if (Route::has('register'))
<li class="nav-item dropdown">
<a id="register" class="nav-link dropdown-toggle" href="#" role="button" data-bs-toggle="dropdown" aria-expanded="false">
Register
</a>
<ul class="dropdown-menu dropdown-menu-end" aria-labelledby="register">
<li><a class="dropdown-item" href="{{ route('register') }}" {{ session('training') }}>Training</a></li>
<li><a class="dropdown-item" href="{{ route('register') }}" {{ session('shopping') }}>Shopping</a></li>
<li><a class="dropdown-item" href="{{ route('register') }}" {{ session('service') }}>Service</a></li>
<li><a class="dropdown-item" href="{{ route('register') }}" {{ session('counseling') }}>Counseling</a></li>
</ul>
</li>
#endif
web.php
Route::middleware('training')->group(function () {
Route::get('/training', [App\Http\Controllers\Auth\RegisterController::class, 'training'])->name('training');
Route::get('/training/store', [App\Http\Controllers\Auth\RegisterController::class, 'trainingStore'])->name('training.store');
});
Route::middleware('shopping')->group(function () {
Route::get('/shopping', [App\Http\Controllers\Auth\RegisterController::class, 'shopping'])->name('shopping');
Route::get('/shopping/store', [App\Http\Controllers\Auth\RegisterController::class, 'shoppingStore'])->name('shopping.store');
});
Middleware/Shopping.php
public function handle(Request $request, Closure $next)
{
if ($request->session() == 'shopping') {
redirect()->route('shopping');
}
return $next($request);
}
Middleware/Training.php
public function handle(Request $request, Closure $next)
{
if ($request->session() == 'training') {
redirect()->route('training');
}
return $next($request);
}
Ok, Now how to get session in training.blade.php file?

In training.blade.php you can access the session by
Using the session helper
{{ session('training') }}
Session facade
use Illuminate\Support\Facades\Session; # facade
Session::get('training');

Related

Laravel The GET method is not supported for this route when redirecting back()

I have Laravel project and there is a post route that I pass a parameter in the URL and a form in the Request
Route::post('/gc/verifierQR-{qr_url}', [UserController::class, 'inquiryResult'])->name('inquiry.result');
this route returns to a view file and in this view there is change language button
<div class="nav-item">
<div class="dropdown">
<button class="bg-transparent border-0" type="button" id="dropdownMenuButton1"
data-bs-toggle="dropdown" aria-expanded="false">
<a class="nav-link text-white"><i class="fas fa-globe me-2"></i> العربية <i
class="fas fa-chevron-down"></i></a>
</button>
<ul class="dropdown-menu border-0 shadow" aria-labelledby="dropdownMenuButton1">
<li><a class="dropdown-item fw-bold" href="{{ route('lang', $arabic_locale) }}"><img
src="{{ asset('images/egypt-flag.png') }}" class="egypt-flag">
العربية</a></li>
<li>
<hr class="dropdown-divider">
</li>
<li><a class="dropdown-item" href="{{ route('lang', $english_locale) }}"><img
src="{{ asset('images/usa-flag.png') }}" class="egypt-flag">
English</a></li>
</ul>
</div>
</div>
the route of language changing
Route::get('/language/{locale}', function ($locale) {
app()->setLocale($locale);
session()->put('locale', $locale);
return redirect()->back();
})->name('lang');
but in this page when I change the language and redirect back() I found this error
The GET method is not supported for this route. Supported methods: POST.
When we say redirect, we usually mean the browser, and you can not change the method which the browser uses to open pages (which is GET).
Either redirect to another separate route.
Or allow both GET and POST methods (for your already existing route).
Instead of normal POST route:
Route::post('my-url', function () {
return view('my-view');
})->name('my-route');
Do something like:
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
Route::match(['post', 'get'], 'my-url', function (Request $request) {
return view('my-view');
})->name('my-route');
The answer is simple. The route or url where you returned back definately a post route. you can use any instead of get and post.

authentification doesn't work in Laravel 8 with the #auth

So I have a Laravel application, I login and get redirected to my home page where the header is suppose to be changed but it isn't.
<ul>
<a href="{{URL:: route( 'login' )}}" id="logo">
<img src="{{asset('assets/img/rentalstallLogo.jpg')}}" alt="Logo">
</a>
<li><a >Qui somme-nous</a> </li>
<li><a >Événements & concours </a></li>
#auth
<li>
<form action="{{ route('signout')}}" method="GET">
#csrf
<button type="submit" id='logoutButton'> logout </button>
</form>
</li>
<li><a id="connexion-link" href={{route( 'login' )}}>account</a> </li>
#endauth
#guest
<li><a href={{route( 'register-user' )}} >Inscriptions</a> </li>
<li><a id="connexion-link" href={{route( 'login' )}}>Connexion</a> </li>
#endguest
<li><a id="language-link" href="#">fr</a> </li>
</ul>
i also tried if (Auth::check()) and if (Auth->check())
here is my log in function :
'email' => 'required',
'password' => 'required'
]);
$credentials = $request->except(['_token']);
$user = User::where('email',$request->email)->first();
if (auth()->attempt($credentials)) {
return redirect()->intended('/');
}else{
session()->flash('message', 'Invalid credentials');
return redirect()->back();
}
You can use
#if(Auth::check())
#else
#endif
See it will work
Sounds to me like the authentication process is not been completed correctly. You mentioned that dd($auth()->$user()) return null so that means the user is not being created correctly. In your login controller, you are only redirecting the user and not generating the session.
$request->session()->regenerate();
That line of code should be before the redirect. That should fix the $user returning null issue.

make $user is undefined Make the variable optional in the blade template. Replace {{ $user }} with {{ $user ?? '' }}

I have one-page sidebar.blade.php and I have to import this page in another page as a sidebar
I have variable here that is coming from the controller when I import sidebar to other page using #extends it shows me error undefined variable with solution
" make $user is undefined Make the variable optional in the blade template. Replace {{ $user }} with {{ $user ?? '' }}"
how I can solve this
sidebar code here
#if($user->role =="handlers" )
<li>
<i class="fa fa-user fa-fw"></i> kontaktuppgifter{{-- <span class="fa arrow"></span> --}}
</li>
#endif
<li>
Since Your probably not passing the variable $user in to each of your views, but you are extending the sidebar view, try using Laravel auth() helper instead to get the user model. You can do something like this:
#if(auth()->user()->role == "handlers")
<li>
<a href="{{ url('/kontaktuppgifter') }}">
<i class="fa fa-user fa-fw"></i>
kontaktuppgifter
</a>
</li>
#endif
You can also share a $user variable with all your views, this way you won't have to query the database each time you want to retrieve the user data.
You can do this in your BaseController class __construct() function:
//App\Http\Controller.php
public function __construct()
{
$user = auth()->user();
view()->share('user', $user);
}
Then you can use a user variable in your view, just like you are doing right now:
#if($user->role == "handlers")
<li>
<a href="{{ url('/kontaktuppgifter') }}">
<i class="fa fa-user fa-fw"></i>
kontaktuppgifter
</a>
</li>
#endif
If $user is current user, then You should use Auth for that:
#if(auth()->user()->role =="handlers" )
<li>
<i class="fa fa-user fa-fw"></i> kontaktuppgifter{{-- <span class="fa arrow"></span> --}}
</li>
#endif

Cannot use Auth::user() in blade template in Laravel 5.4

I want to make my index page with both guest and auth functions.
When guests visit, they could try logging in; And after login, it will show the user's info such as username.
Below is what I did.
Routes are defined in routes/web.php:
Route::get('/', 'CommonController#index');
Auth::routes();
In blade template of index, I used Auth::user() to validate authentication but failed.
#if(Auth::user())
<div id="user-panel">
<a href="" class="user-panel-button">
New Article
</a>
<div class="btn-group user-panel-button">
<a type="button" class="dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
{{ Auth::user()->name }} <span class="caret"></span>
</a>
<ul class="dropdown-menu">
<li>Logout</li>
</ul>
</div>
</div>
#else
<a href="{{ url('login') }}" class="button">
Login
</a>
#endif
Every time I logged in successfully, it will still show login button instead of user name button, after I REFRESH the index page.
I have checked session information, once I refreshed the page, the login_web_xxxxxxxxxxx session will be disappeared.
Furthermore, When I use Laravel default path for auth /home, it worked. Username could always be presented whatever how many times you refresh the page.
How should I fix this issue? Many thanks.
For Laravel 5.4 you can use:
#if(Auth::check())
// The user is authenticated...
#else
// The user is not authenticated...
#endif
For Laravel 5.5 and above:
#auth
// The user is authenticated...
#endauth
#guest
// The user is not authenticated...
#endguest
Instead of using
<ul class="dropdown-menu">
<li>Logout</li>
</ul>
For log out, it is better to be codes as below, which is provided by official resources/view/layouts/app.php
<ul class="dropdown-menu">
<li>
<a href="{{ route('logout') }}" onclick="event.preventDefault(); document.getElementById('logout-form').submit();">
Logout
</a>
<form id="logout-form" action="{{ route('logout') }}" method="POST" style="display: none;">
{{ csrf_field() }}
</form>
</li>
</ul>
Update routes/web.php file as
Route::group(['middleware' => 'web'], function () {
Route::get('/', 'CommonController#index');
Auth::routes();
}
Now to check auth in your blade template, you can use
#if(\Auth::check())
....
....
#else
....
....
#endif
also you can use the full class path of Auth in blade file like this
#if(\Illuminate\Support\Facades\Auth::check())
// code here
#endif

How can I use Middleware to define a section of a blade template?

I have navigation bar that I'd like to show a link to the Admin Dashboard if the user logged in is an admin. If not, it should display nothing. I have something similar set up with guests e.g.
#if (Auth::guest())
<li>Login</li>
<li>Register</li>
#else
<li class="dropdown">
{{ Auth::user()->name }} <span class="caret"></span>
<ul class="dropdown-menu" role="menu">
<li>Profile</li>
<li>Logout</li>
</ul>
</li>
#endif
But how can I do this for a logged in user and an admin? I currently have
<ul class="nav navbar-nav">
<li>Home</li>
#if (Auth::guest())
#else
<li>Admin Dashboard</li>
#endif
</ul>
I have middleware set up on the admin route like so
Route::get('admin', ['middleware' => 'admin', 'uses' => 'AdminController#index']);
Which looks like
public function handle($request, Closure $next)
{
if ($request->user()->role != 1)
{
return redirect('home');
}
return $next($request);
}
And that's fine, I just don't know how to get it to define a section of a blade template.
Looks like your user model has an attribute named role, so you can do something like this:
<ul class="nav navbar-nav">
<li>Home</li>
#if (Auth::user()->role != 1)
{{-- I am not an admin user --}}
#else
{{-- I am an admin user --}}
#endif
</ul>
If it is not your case, then you need add a new attribute to the user model. By that way you are able emulate the code above.
For a better code structure and order, I suggest to you make a fuction inside of user model like this:
public function isAdmin(){
return (\Auth::check() && $this->role == 1);
}
or another one to check if it is a regular user:
/** An user who is authenticated but it is not an admin */
public function isRegular(){
return (\Auth::check() && $this->role != 1);
}
Then, in you application and views you can use them like:
#if (Auth::user()->isRegular())
{{-- I am not an admin user --}}
#else
{{-- I am an admin user --}}
#endif
Or
#if (Auth::user()->isAdmin())
{{-- I am an admin user --}}
#else
{{-- I am not an admin user --}}
#endif

Categories