kendaop
kendaop

Reputation: 127

Laravel Routing to Wrong View

I'm working with Laravel 4.2. I have an app that's routing to the wrong view, although the URL is correct. On a button click, it's supposed to route to users.create (UsersController@create), but is instead routing to UsersController@show. The resolved URL is correct, though, and the DOM element has the correct URL listed. Can anyone help me out?

Here is my Routes file:

// Home page
Route::get('/', 'BaseController@index');

// Define User model to pass through routes
Route::model('user', 'User');

// Create custom route for editing a user
Route::get('users/edit/{user}', 
    array('as' => 'users.edit', 'uses' => 'UsersController@edit'));

// Create custom route for showing a user
Route::get('users/{user}',
    ['as' => 'users.show', 'uses' => 'UsersController@show']);

// Remaining routes
Route::resource('users', 'UsersController', 
    array('except' => array('edit', 'show')));

Here is my UsersController with the two functions in question:

class UsersController extends \BaseController {

protected $user;

public function create()
{
    return View::make('users/create');
}

public function show($user)
{   
    return View::make('users/show', ['user' => $user]);
}}

And here are the relevant results from php artisan routes:

GET:HEAD    users/{user}    users.show      UsersController@show
GET:HEAD    users/create    users.create    UsersController@create

Thanks for your help!

Edit: The answer to the problem was to simply re-order the routes so that the resource is defined first. I was aware that Laravel grabs the first route that matches a URI, but I still don't understand why a route that isn't passed a user object would select a route defined as users/{user}. Furthermore, I was accessing the route via link_to_route(), that is to say, by name. Why would Laravel pick a different route from the one I explicitly named?

I suppose these questions are beyond the scope of the initial question, but I would greatly appreciate further explanation from someone. Problem solved!

Upvotes: 2

Views: 2237

Answers (2)

DoverAudio
DoverAudio

Reputation: 333

The first thing that jumps out at me is there is no route for "create". There is the "restful" controller, but maybe you want to just try putting the route in. I'm slightly uncomfortable using restful routes when serving html. In the project i'm working on i've been trying to preserve those for data/json transmission, in order to support outside api action.

Upvotes: 2

Lee Han Kyeol
Lee Han Kyeol

Reputation: 2481

I think your routes setup recognizes create as {user} in user/{user}, thus redirect to user/show/create as your "custom route for showing a user" setup.

You may have to avoid getting string variable right after users/ route.

Upvotes: 2

Related Questions