code-8
code-8

Reputation: 58810

How do I call the right controller function in Laravel?

I have a button, and when I click on that button, it will being me to user/create. I'm clueless trying to debug why my show() function is executing rather than my create function.

enter image description here

Route

// Auth Group 
$router->group(['middleware' => 'auth'], function() {

    //Users
    Route::get('user/{id}', array('before' =>'profile', 'uses'=>'UserController@show'));
   
});

// Auth and Admin Group 
$router->group(['middleware' => ['auth', 'admin']], function() {

    Route::get('user/create', array('as'=>'user.create', 'uses'=>'UserController@create'));
    
});

Obviously, I set user/create to call the create function.


UserController

Show - I have no idea why this function get executed.

public function show($id)
{
    dd("I'm inside the show function ");

    $user = User::findOrFail($id);
    return View::make('users.show')
        ->with('user', $user);
}

Create - suppose to call this function

// Bring up create form for Aveniros user
public function create(){
    return View::make('users.create');
}

Does anybody know why ?

Upvotes: 1

Views: 215

Answers (2)

Rob_vH
Rob_vH

Reputation: 780

Funny thing.. this is actually a specific example covered in the Laracasts on Laravel 5. Yes, put the route for the non-wildcard task (/create) before the wildcard ({id}) otherwise ({id}) handles everything and it never gets to /create.

Upvotes: 0

Jake Opena
Jake Opena

Reputation: 1525

Note that /user/create matches the route Route::get('user/{id}', array());
You can add a costraint to user id so that only integers will be matched:

Route::get('user/{id}', array(
    'before' =>'profile', 
    'uses'=>'UserController@show'
))->where('id', '[0-9]+');

Also you can interchange the order of your routes so that Route::get('/user/create') will be matched FIRST.

Upvotes: 3

Related Questions