Aipo
Aipo

Reputation: 1985

User routing Laravel 5.4

I want my user to access its profile edit page by URL: /profile/slug/edit, where slug means $user->slug. My web.php contans:

Route::group(['middleware' => 'auth'], function () {
Route::get('/profile/{slug}', [
'uses' => 'ProfilesController@index',
'as' => 'profile'
]);
Route::get('/profile/{slug}/edit', [
'uses' => 'ProfilesController@edit',
'as' => 'profile.edit'
]);

How to call ProfilesController@edit from view, how to pass parameters correctly? Tried:

<a href="{{route('profile', ['slug'=> Auth::user()->slug],'edit')}}">
Edit your profile</a>

Upvotes: 0

Views: 376

Answers (2)

Bhanuka Mahanama
Bhanuka Mahanama

Reputation: 143

You can use following codeline

<a href="{{ route('profile.edit', ['slug' => Auth::user()->slug]) }}"> Edit your profile</a>

Your routes definitions seems to be fine.

Plus if you want to add some get params, you can add directly in the array passed as the second argument

<a href="{{ route('profile.edit', ['slug' => Auth::user()->slug, 'otherparam' => 'value']) }}"> Edit your profile</a>

Hope this helps. :)

Upvotes: 1

Saeed Prez
Saeed Prez

Reputation: 778

Here is how I would do it..

Route::group(['middleware' => 'auth'], function () {
    Route::get('/profile/{slug}', 'ProfilesController@index')->name('profile');
    Route::get('/profile/{slug}/edit', 'ProfilesController@edit')->name('profile.edit');
});

And then in your view, you can use..

<a href="{{ route('profile.edit', Auth::user()->slug) }}">Edit your profile</a>

As you can see, first we have to give the route() the route name we are interested in, in your case it's profile.edit that is the target route, and we know from our routes file that it's missing the slug value, so we provide it the slug value as the second argument (if there are more missing values, the second argument should be an array).

It takes some practice and time but try different ways to see what makes your code more readable. The number of lines doesn't matter that much to the computer, write the code so you can easily read and understand it if you want to change something a year or two from now.

Upvotes: 1

Related Questions