mardi 27 mars 2018

Laravel set mutator remove the attribute from statement in create method

I am encoutering a problem with Laravel. I have a model named News

class News extends Model {

    protected $fillable = ['title', 'content', 'published_at'];

    protected $dates = ['created_at', 'updated_at', 'published_at'];

    public function author() {
        return $this->belongsTo(User::class, 'user_id');
    }

    public function setPublishedAtAttribute($value) {
        return Carbon::createFromFormat('d/m/Y H:i', $value)->toDateTimeString();
    }

    public function scopePublished($query) {
        return $query->whereDate('published_at', '<', Carbon::now());
    }

    public function scopeLatestNews($query) {
        return $query->latest()->with('author');
    }

}

When i try to store a new News resource :

public function store(StoreBlogPost $request) {
    $news = Auth::user()->news()->create($request->all());

    return redirect()->route('blog.show', $news);
}

I got a QueryException SQLSTATE[HY000]: General error: 1364 Field 'published_at' doesn't have a default value.
And the query looks like that

insert into `news` (`title`, `content`, `user_id`, `updated_at`, `created_at`)

But when i remove the mutator setPublishedAtAttribute the error disappear but i got a non-formatted date error instead (that's why i use a mutator).



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire