Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Laravel how to customize user profile url based on currently logged in user

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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');

>Solution :

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading