Reputation: 10077
New to Laravel 5, and building a little Rest test app. So I'm envisioning 2 different endpoints for a single controller.
/myApp/public/index.php/states/{state}/cities //returns cities in a state
and
/myApp/public/index.php/states/{state}/cities/{city} //will do somethin else
its a little unclear to me how to set up the routes for this. I suppose I could have these endpoints use the same controller method, but it seems like better architecture to just route each to its own method.
So far, I've got 2 things that each individually work, but dont work together:
in routes.php
//route to the first endpoint
Route::resource('states.cities', 'StatesController');
//routes to the second endpoint if first is uncommented,otherwise blank page with no errors in log
Route::resource('states.cities', 'StatesController@cities');
And the relevant part of my controller code:
class StatesController extends Controller
{
/**
* Display a listing of the resource.
*
* @return Response
*/
public function index(Request $request, $state)
{
//works
$cities = States::where('state', '=', $state)->lists('name');
echo json_encode($cities);
}
public function cities(Request $request, $state, $city)
{
echo "second request";
echo $state;
echo $city;
}
......
Any one have any ideas on the proper way to handle this going forward? Cheers!
Upvotes: 0
Views: 252
Reputation: 2943
Try this.
Route::get('states/{state}/cities', [
'as' => 'state.cities',
'uses' => 'StatesController@index'
]);
And second.
Route::get('states/cities/{state}/{city}', [
'as' => 'city.of.state',
'uses' => 'StatesController@cities'
]);
Note: There is no need to use resource
route in this case. The resource
routes creates the whole array of different routes which you really don't need. Resource controllers
Upvotes: 3