I have just started learning Laravel and would like to know if it is possible to create a Route::resource that would allow me to access the below URL using RESTful methods:
I would like the URL to look like this:
http://example.com/articles/2014/09/22/this-is-the-article-title
And I would like to access this from my ArticlesController using:
//GET articles/{year}/{month}/{day}/{title}
public function show($year, $month, $day, $title) {
$article = //find article in DB
return View::make('articles.show')->with('article', $article);
}
From what I've gathered so far, this can somehow be accomplished by doing something like the below in the routes.php file:
Route::resource('year.month.day.articles', 'ArticlesController');
But that doesn't quite look right to me.
Does anyone have any suggestions?
Resource controllers are useful for building RESTful controllers that form the backbone of APIs. The general syntax is this:
Route::resource('resourceName', 'ControllerName');
This will create seven different routes in a single call, but is really just a convenience method for doing this:
Route::get('/resourceName', 'ControllerName@index');
Route::get('/resourceName/{resource}', 'ControllerName@show');
Route::get('/resourceName/create', 'ControllerName@create');
Route::get('/resourceName/{resource}/edit', 'ControllerName@edit');
Route::post('/resourceName', 'ControllerName@store');
Route::put('/resourceName/{resource}', 'ControllerName@update');
Route::delete('/resourceName/{resource}', 'ControllerName@destroy');
The URLs are only based off of the resource's name that you specify, and the method names are built in. I am not aware of any way that you can modify those using resource controllers.
If you want pretty URLs, then assign those routes without using a resource controller:
Route::get('/articles/{year}/{month}/{day}/{title}', 'ArticlesController@show');
Note that if you do use the show
method, this will conflict with any REST-ful URL that you may have defined previously (the show
method in a resource controller will only expect 1 parameter passed in, namely the ID of the resource to show). For this reason I would recommend you to change the name of that method to something else.