Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 408
Tamara Avatar asked Dec 03 '25 15:12

Tamara


1 Answers

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.

like image 165
Cas Bloem Avatar answered Dec 05 '25 05:12

Cas Bloem



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!