Samir Sabri
Samir Sabri

Reputation: 977

How to set dynamic routes?

Lets say I have blog model, and it has a title, how would I set each blog to this signature:

mywebsite.com/blogs/{blog title}-{blog id}

Is there a recommended package to use? or shall I write my own? where to start?

Upvotes: 0

Views: 1131

Answers (2)

nozzleman
nozzleman

Reputation: 9649

The easiest would be to use a slash (/) as delimiter for blog-title and blog-id. this way, you could define your routes like the following:

Route::get('blogs/{title}/{id}', function($title, $id)
{
    // your code here
});

Call it like this: https://yourdomain.com/blogs/yourFirstTitle/1

Otherwise, you could explode the dash-delimited parameter you are passing by defining your route like this:

Route::get('blogs/{titleAndId}', function($titleAndId)
{
    $params = explode("-", $titleAndId);
    $title = $params[0];
    $id = $params[1];

    // your code here
});

Call it like this: https://yourdomain.com/blogs/yourFirstTitle-1. As you can see, this is not very readable (both, the code and the URI).

I would highly recommend the first version. Of course you should also route to controllers, but as for the routing, the examples should get you started.

Upvotes: 0

Khan Shahrukh
Khan Shahrukh

Reputation: 6361

I would suggest you having a url like mywebsite/blogs/id/title and for that in your routes.php have a route for blogs which accepts two parameter

Route::get('/blogs/{id}/{title}', 'BlogController@blog');

in your controller

public function blog($title, $id)
{
    /**  in the function parameter it is not mandatory to catch both 
    *   just take the one which is required
    */
    Blog::where('id', '=', $id)->get();
}

and when you want to create links dynamically in your views and then you can link to your blog by

<a href="/blogs/{{$array->id}}/<?php echo Str::slug($array->title);?>">{{$array->title}}</a>

Edited the answer just saw that you are using laravel 4

Upvotes: 2

Related Questions