Laravel 5 - Laracast Easy Auth - Save Article
I followed the laracast tutorial on simple auth ( Easy Auth ) but there were some gaps in the video I had to declare
use Auth;
to be able to get the current user, however, when I save the article I get this error
FatalErrorException in ArticleController.php line 42:
Call to undefined method Illuminate\Database\Eloquent\Collection::save()
where is the relevant code in my ArticleController
public function store(ArticleRequest $request)
{
$article = new Article($request->all());
Auth::user()->articles->save($article);
return redirect('blog');
}
My article model:
<?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');
}
}
My user model
<?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 JSON form.
*
* @var array
*/
protected $hidden = ['password', 'remember_token'];
public function articles()
{
return $this-> hasMany('App\Article');
}
}
+3
source to share