Home > Back-end >  Laravel how to customize user profile url based on currently logged in user
Laravel how to customize user profile url based on currently logged in user

Time:03-06

I have created a IndexController.php class which handles user related data control.

So I can get the currently logged in user from following method. but the url is kind of universal url. I want it to be custom url based on the logged in user. for ex If userx logged in as the user, his profile should display as http://127.0.0.1:8000/user/userx. How do i fix this?

IndexController.php

class IndexController extends Controller{

 public function Index(){
     return view('dashboard.index');
 }

 public function userLogout(){
     Auth::logout();
     return Redirect()->route('login');
 }

 public function userProfile(){
     $id = Auth::user()->id;
     $user = User::find($id);
     return view('dashboard.profile',compact('user'));
 }



}

Web.php

Route::get('/user/profile',[IndexController::class, 'userProfile'])->name('user.profile');

CodePudding user response:

Create a route with a parameter, then fetch the profile using that variable:

Route::get('/user/profile/{username}',[IndexController::class, 'userProfile'])->name('user.profile');

Then in your controller, you should have access to this username in the method arguments:

public function userProfile(Request $request, $username)
{
   $user = User::query()->where('username', $username)->firstOrFail();
   // ...
}

If you then want to add extra functionality for when you are on your own profile page (like changing password etc), you'd have to check the authenticated user Auth::user(). Alternatively, you can keep the default /user/profile route as the URL to visit when you want to change your own profile. There are multiple ways to solve this :)

CodePudding user response:

You need to check two Laravel concepts:

  1. Route Model Binding
  2. Named route

Route

Route::get('/user/{profile}',[IndexController::class, 'userProfile'])->name('user.profile');

Controller

public function userProfile(User $profile){

     // Check if $profile is the same as Auth::user()
     // If only the user can see his own profile

     $id = Auth::user()->id;
     $user = User::find($id);

     return view('dashboard.profile',compact('user'));
 }

Blade

<a href="{{ route('user.profile', ["profile" => $user->id]) }}"> See profile </a>

Or

<a href="{{ route('user.profile', ["profile" => Auth::user()->id]) }}"> See profile </a>
  • Related