get current username in laravel route file without passing from controller - php

Hello i want to know that how can i access the current username in my laravel route file? i want to add current user name as prefix in my url but i don't want to pass username as parameter for every route call because project is already completed so its is a complex and time consuming task. so please suggest how can I get current username.
Here is my code:
Route::prefix(/Auth::user()->name)->group(function () {
Route::get('/test', 'HomeController#test')->name('test');
});
<a href="{{route('test')}}">
Thanks in advance.
Note:- I don't want to pass username from templates or controller because its complex and time consuming as project is already done.

You can not pass Auth user from routes/web.php , you need to pass paramter in your route .
Route::group(['middleware'=>'auth','prefix'=>'/'],function () {
Route::get({username}, 'HomeController#test');
});
in your controller :
public function test(Request $request,$username){
$user=User::where('name',$username)->first();
if($user){
return response()->json((array('status'=>'success','user'=>$user));
}else{
return response()->json(array('status'=>'error','message'=>'user not found'));
}
}

Routes are registered before Session is initialized. So you can't access the authenticated user in the routes file.
So you have to register new routes with a dummy username prefix as,
Route::prefix('{username}')->group(function () {
Route::get('/test', 'HomeController#index');
});
Just add a param {username} & no need it use anywahere. Keep this route group at the end of the routes file.
Re-generate your routes as,
<a href="{{ url(auth()->user()->name . '/test') }}">

Related

What is the uses of naming the route in Laravel 9?

For example, this line exist in my web.php file. I just follow tutorials on Youtube, they did it like this.
// Show Login Form
Route::get('/login', [UserController::class, 'login'])->name('login');
So if I name the route, how could it benefits me?
You can call this route with a helper method like this:
// Generating URLs for login page
$url = route('login');
// Generating Redirects to login page
return redirect()->route('login');
return to_route('login');
Check to Laravel docs

How to use session data (auth) in the Laravel routes page

We have a large website with many pages. Almost all of them require the user to log in. Instead of specifying "Auth" on every single page, or on every single controller, I would like to set the routes based on if the user is logged in, like this:
// in web.php
if (Auth::isLoggedIn()) {
Route::get('/', function () { return view('pages/dashboard'); });
... lots more
}
The reason I can't do this is because Auth uses sessions, and sessions are not yet initialized in web.php, since it is done as middleware which is not run yet at this point.
I'm using Laravel 8, I believe.
Thanks.
you can group the route that need the user to be logged in, then use auth middleware
for the grouped routes:
Route::middleware(['auth'])->group(function () {
Route::get('/', function () {
//
});
Route::get('/', function () { return view('pages/dashboard'); });
});
Try using Laravel's Route middleware. Route middleware can be used to only allow authenticated users to access a given route.

How can I redirect a Laravel route without a parameter to a controller method with a default parameter?

Assume the following routes in a Laravel 5.5 API:
// custom routes for THIS user (the user making the request)
Route::get('/user', 'UserController#show');
Route::get('/user/edit', 'UserController#edit');
// register CRUDdy resource routes for users
Route::resource('users', 'UserController');
Let's use edit as the example:
public function edit(User $user)
{
...
}
As you can see, the edit route contains a type-hinted $user parameter. This works just fine for the users/13/edit route, as expected. However, I'd to configure the route /user/edit to pass along the $request->user() user object to the function. I don't want to check for the user object in the actual edit method as that could interfere with other validation (for instance, I don't want to default to the current user if someone passes a non-existent user ID, I want to return an error in that case).
In short: how can I register a route to first create a parameter, then pass it to the given controller method? My first thought was to use a closure:
Route::get('/user/edit', function(Request $request){
$user = $request->user();
});
But once inside the closure, I'm not certain how to then carry the request forward to the appropriate controller method.
Instead of a closure, you could make a new controller method that calls edit with the current user.
Let's say your route is this:
Route::get('/user/edit', 'UserController#editSelf');
Then in your controller:
public function editSelf(Request $request)
{
$this->edit($request->user());
}

Hesto multi-auth guard is not redirecting where page was before after login

I am on page : http://laravel.dev/lists
which shows me list of item
Item 1
Item 1
Item 1
but above item can only accessible to authorized user
Issue
when i click on Item 1 so if user is not logged in then it goes to http://laravel.dev/login then user proceed to login but after login it must redirect to http://laravel.dev/lists/1 but it is redirecting to http://laravel.dev/home.
I have tried
public function showLoginForm()
{
session()->put('url.intended',url()->previous());
// or
session()->put('url.intended', url()->current());
return view('user.auth.login');
}
but above is not working, it is redirecting to http://laravel.dev/lists
laravel own auth is working fine.
but hesto multi-auth is not working
I am using this Hesto-multi-auth package for multiple authentication like admin, user, employee
is there any solution for this
If you're using the default user Authentication system in Laravel, and if you added auth middleware in your routes, it's automatically done by Laravel.
In your routes:
Route::group(['middleware' => 'auth'], function() {
. . . Your Routes goes Here
});
You can take a look at the docs https://laravel.com/docs/5.4/authentication#protecting-routes
You can use middleware. For example :
Route::get('lists/{id}', function () {
//
})->middleware('auth');
Please refer here : https://laravel.com/docs/5.5/middleware for more information
First of all find the place where you redirect unauthenticated user to the login page (probably in app/Exceptions/Handler.php function unauthenticated) and save to the session current url ("/lists/1") before redirect.
Afrer that add in your Auth controller property $redirectTo and fill it from the session or define method redirectTo (method also nust return url).
Out of the box laravel redirects to /home because of trait /Illuminate/Foundation/Auth/RedirectsUsers.
You can try this idea: After you've successfully logged in, you'll be redirected to the page you want (e.g. http://laravel.dev/lists/1)
Auth::attempt(...);
return redirect()->route('the name of your route here where redirected to http://laravel.dev/lists/1');
What you had tried in the showLoginForm() won't be work, because neither url()->previous() nor url()->current() you specified were not the url you want.
Solution:
Changed in the middleware:
public function handle($request, Closure $next, $guard = 'user')
{
if (!Auth::guard($guard)->check()) {
session()->put('url.intended', \URL::current()); // Add this line
return redirect('user/login');
}
return $next($request);
}

Laravel Different Route Same Controller

I'm building an API for user and admin.
Got stuck at edit user profile routing.
on admin route i use Route::resource('user', 'UserController')
on user route i use Route::get('profile', 'UserController#show')
At the show method Laravel default has
public function show($id)
{
}
the different between them is on admin I can use /id but on user i check their token from middleware and merge the request to get their user_id so there is no need for the API to use profile/{id}.
The question is how can I use the same method but there is an argument to fill and the route still /profile?
One of my solution is :
public function show($id){
if ($request->has('user_id')):
$id = $request->query('user_id');
endif;
}
It working but when i read the code, it's really redundant always checking it and replace the id.
Just place the request object as a parameter in your controller and get the input from the request object when you use your user route.
Thanks

Categories