Tamara
Tamara

Reputation: 2980

Laravel 5 Documentation - route model binding

I'm reading Laravel 5 documentation and have some problem with understanding route model binding.

I use example code from here

So, I added line to RouteServiceProvider.php:

public function boot(Router $router)
{
    parent::boot($router);

    $router->model('user', 'App\User');
}

I added route:

Route::get('/profile/{user}', function(App\User $user)
{
    die(var_dump($user));
});

Default Laravel user model is used.

<?php namespace App;

 use Illuminate\Auth\Authenticatable;
 use Illuminate\Database\Eloquent\Model;
 use Illuminate\Auth\Passwords\CanResetPassword;
 use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
 use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;

 class User extends Model implements AuthenticatableContract,    CanResetPasswordContract {

     use Authenticatable, CanResetPassword;

/**
 * The database table used by the model.
 *
 * @var string
 */
     protected $table = 'users';

/**
 * The attributes that are mass assignable.
 *
 * @var array
 */
     protected $fillable = ['name', 'email', 'password'];

/**
 * The attributes excluded from the model's JSON form.
 *
 * @var array
 */
     protected $hidden = ['password', 'remember_token'];

 }

And I have MySQL table 'users'. When I go to URL http://blog.app/profile/1, I expect to see data for user with ID 1, but I don't understand how to get actual model values. Instead I see:

enter image description here

Is there any special methods for getting model values? Or did I miss something?

Upvotes: 3

Views: 3235

Answers (2)

Steeve Lefort
Steeve Lefort

Reputation: 89

I have had the same problem.
Look for the "$namespace" var in the "RouteServiceProvider" and try to set it blank :

protected $namespace = '';

Upvotes: 0

Cas Bloem
Cas Bloem

Reputation: 5040

I have the same problem here. You just get an empty instance of App\User, since you declared that in your Route::get(). The model is never loaded.

Another way to bind model to the parameter:

Route::bind('user', function($value)
{
    return App\User::find($value);
});

The Closure you pass to the bind method will receive the value of the URI segment, and should return an instance of the class you want to be injected into the route.

Upvotes: 4

Related Questions