【发布时间】:2016-10-06 15:54:48
【问题描述】:
当我在 routes/web.php 文件中使用以下代码时,每次访问 /user/{id}/post url 时都会收到“尝试获取非对象的属性”的错误。
路由/web.php
use App\Post;
use App\User;
Route::get('/user/{id}/post', function($id) {
return User::find($id)->name;
});
应用程序/用户.php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token',
];
public function posts() {
return $this->hasOne('Post');
}
}
App/Post.php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Post extends Model
{
// protected $table = 'posts';
use SoftDeletes;
protected $dates = ['deleted_at'];
protected $fillable = [''];
}
如何查看存储在 users 表中的数据?我在里面放了一些虚拟数据来尝试检索它。
【问题讨论】: