Right way to build a link in laravel 5.3

17,473

Solution 1

You can use named routes for this

// Your route file
URL::get('articles/{articleId}/edit', 'ArticlesController@edit')->name('articles.edit');

//Your view
<a href="{{ URL::route('articles.edit', $article->id) }}">Edit</a>

Much more cleaner IMO

Solution 2

You can use named routes for cleaner in code

In your app/Http/routes.php (In case of laravel 5, laravel 5.1, laravel 5.2) or app/routes/web.php (In case of laravel 5.3)

Define route

Route::get('articles/{id}/edit',[
             'as'   =>'articles.edit',
             'uses' =>'YourController@yourMethod'
            ]);

In Your view page (blade) use

<a href="{{ route('articles.edit',$article->id) }}">Edit</a>

One benefits of using named routes is if you change the url of route in future then you don't need to change the href in view (in your case)

Share:
17,473
JahStation
Author by

JahStation

Updated on June 07, 2022

Comments

  • JahStation
    JahStation almost 2 years

    Im trying to build a dynamic link with a view page (blade) with Laravel 5.3.

    My approach is:

    <a href=" {{ URL::to('articles') }}/{{ $article->id}}/edit">Edit></a>  
    

    that will output the right url with my base url and some other slug: http://mydomain/articles/23/edit
    Where "23" is my article's id.

    This works but I wonder if there is a cleaner way to do that?

    many thanks

  • JahStation
    JahStation over 7 years
    thanks it works! the route file was already filled ok by using the Route::resource('articles','ArticlesController'); " method
  • JahStation
    JahStation over 7 years
    the minus is not mine...by the way i try your approach but it fails due the output that is equal to article.edit/id so not what im looking for
  • JahStation
    JahStation over 7 years
    i forgot to put the name() on the route so maybe it fail due this problem
  • Sebastian
    Sebastian over 7 years
    Yeah, my comment was addressed to the guy who downvoted my answer. And like you said: you need to give the route a name to use the route() helper. If you don't have a name on the route you can use the url() helper instead.