Is it possible in laravel 5 to show a pretty url to the user, and a practical url to the app?

796 views Asked by At

I have this url: mywebsite.com/user/1/edit

I want my users to see this: mywebsite.com/edit-your-profile/

Is this possible when using Route::resource('user', 'UserController');? If yes, how do I do it :) ? I still want my app to be able to see user/1/edit as I use it in my middleware to prevent unauthorized access:

if ( \Auth::user()->id != $request->segment(2) ) {

    return  redirect()->back();

}

So, one pretty url for my user, a practical one for my app.

2

There are 2 answers

1
CrackingTheCode On BEST ANSWER

Based on your explanation, I take that a user can only edit their own profile. So mywebsite.com/user/1/edit should NOT even be allowed. Instead, add this in your Route.php add: Route::get('/edit-your-profile','UserController@edit'); and hardcode \Auth::user()->id into your editController and do not even allow the user to set the id. Why bother asking them for an ID if you already know what the id must be and ALL other ids will be rejected!

PS. The html form for update should be at @update and the output that form should be sent to @edit. I just wanted to simplify the routing in the example.

4
CrackingTheCode On

Additional question:

The slugs are dynamically created, which means you don't have prior knowledge about them. Therefore, you can't statically hardcode these into your route. Even if you could, there might be too many of them. So, I think the only way is to use wildcards to capture the navigated URI and then dynamically create the page.

First identify what the base URI for the slugs is: for example for the username of: <>b4dus3r name<>(baduser name), you have generated bdusr-name slug. You know that this slug is a username slug and you have decided to use the base URI as example.com/user/. So to navigate to this user's profile you want: example.com/user/bdusr-name.

Add this to your route file: Route::get('/user/{username},'UserController@show');

In your UserController:

public function show($userSlug){
    $user = \App\User::where('userslug','=',$userSlug)->get();
    return view('user.show')->with('user',$user);
}

Here I am assuming that the user slug is stored in strings, not a foreign key, in the userslug column in the users table. In otherwords, you substitute the ID or what have you with the the slug.