我正在关注laracast关于easy auth(Easy Auth)的教程,但视频中存在一些空白,我必须声明
use Auth;
能够获得当前用户,但是,当我保存文章时,我收到此错误
FatalErrorException in ArticleController.php line 42:
Call to undefined method Illuminate\Database\Eloquent\Collection::save()
我的ArticleController中的相应代码是
public function store(ArticleRequest $request)
{
$article = new Article($request->all());
Auth::user()->articles->save($article);
return redirect('blog');
}
我的文章模型:
<?php namespace App;
use Illuminate\Database\Eloquent\Model;
use Carbon\Carbon;
class Article extends Model {
protected $fillable = [
'title',
'body',
'published_at',
'user_id'
];
protected $dates = ['published_at'];
public function scopePublished ($query)
{
$query->where('published_at', '<=', Carbon::now());
}
public function scopeUnpublished ($query)
{
$query->where('published_at', '>', Carbon::now());
}
public function setPublishedAtAttribute($date)
{
$this->attributes['published_at'] = Carbon::parse($date);
}
public function user()
{
return $this-> belongsTo('App\User');
}
}
我的用户模型
<?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'];
public function articles()
{
return $this-> hasMany('App\Article');
}
}
答案 0 :(得分:1)
试试这个
Auth::user()->articles()->save($article);
存储操作
public function store(ArticleRequest $request)
{
$article = new Article($request->all());
Auth::user()->articles()->save($article);
return redirect('blog');
}