问题
I have a resource controlling one of my tables "fans". I have a view that shows the information for each respective. The urls for these right now is "url.com/fans/{$id}", where {$id} is the unique id for the row/object in the table.
I would like to maintain this relationship, but I would also like to the url be pointed to another column in the table (another unique identifier). So something like "ulr.com/fans/{$new_column}".
How would I reroute this view/url so that it appears like that? This is what I have so far:
Routes:
Route::resource('fans', 'FansController');
FansController:
public function show($id) {
$fan = Fan::find($id);
return View::make('fans.show', compact('fan'));
}
So ultimately, I would like "url.com/fans/{$id}" to still work, but then it will be rerouted to "url.com/fans/{$new_column}". And going directly to "url.com/fans/{$new_column} should just stay there.
回答1:
If you are able to differentiate between each parameter value between id and *new_column* you can declare all your routes for fans route with Route::get instead of Route::resource and define Regular Expression Route Constraints, so for example if your id column has numbers only and your *new_column* column has alpha values:
Route::get('fans/{new_column}', array('as' => 'anotherColumn', function($new_column)
{
$fan = Fan::where('new_column','=',$new_column);
return View::make('fans.show', compact('fan'));
}))
->where('new_column', '[A-Za-z]+');
Route::get('fans/{id}', function($id)
{
// do something with $id or
return Redirect::route('anotherColumn');
})
->where('id', '[0-9]+');
Then declare the rest of the automatically generated resource routes.
来源:https://stackoverflow.com/questions/22210276/how-to-reroute-a-resource-to-include-a-different-field-besides-id-in-laravel-4