0
當我在我的routes/web.php文件中使用以下代碼時,每次訪問/ user/{id}/post url時,都會收到錯誤'試圖獲取非對象的屬性'。如何從Laravel的默認用戶類讀取數據庫數據?
路線/ web.php
use App\Post;
use App\User;
Route::get('/user/{id}/post', function($id) {
return User::find($id)->name;
});
應用/ user.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');
}
}
應用/ 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 = [''];
}
如何查看存儲在表中的用戶數據?我在裏面放了一些虛擬數據來嘗試和檢索它。