[英]Laravel 5 Documentation - route model binding
我正在閱讀Laravel 5文檔,並且在理解路由模型綁定方面存在一些問題。
我從這里使用示例代碼
所以,我在RouteServiceProvider.php中添加了一行:
public function boot(Router $router)
{
parent::boot($router);
$router->model('user', 'App\User');
}
我添加了路線:
Route::get('/profile/{user}', function(App\User $user)
{
die(var_dump($user));
});
使用默認的Laravel用戶模型。
<?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'];
}
我有MySQL表'用戶'。 當我訪問URL http://blog.app/profile/1時 ,我希望看到ID為1的用戶的數據,但我不明白如何獲取實際的模型值。 相反,我看到:
獲取模型值有什么特殊方法嗎? 還是我錯過了什么?
我在這里遇到同樣的問題。 您只需獲取App\\User
的空實例,因為您在Route::get()
聲明了該實例。 永遠不會加載模型。
將模型綁定到參數的另一種方法:
Route::bind('user', function($value)
{
return App\User::find($value);
});
傳遞給bind方法的Closure將接收URI段的值,並且應該返回要注入到路由中的類的實例。
我曾經也有過一樣的問題。
在“RouteServiceProvider”中查找“$ namespace”var並嘗試將其設置為空白:
protected $namespace = '';
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.