henryoladj's avatar

Generating Slug from Post

I am trying to generate slug from my news website, i have a form which has subject and body. Subject also means the title of the post, i would love to generate slug right after making the post automatically without having to enter the slug myself.

NewsController.php

 public function store(Request $request, News $news)
    {
        //validate
        $this->validate($request,[
            'subject'=>'required|min:10',
            'body' => 'required|min:20'
        ]);

        $slug = str_slug("$news","-");
        
        auth()->user()->news()->create($request->all());

        //redirect
        $news= News::paginate(15);
        return view('categories.news', compact('news'));
}

News.php Model

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class News extends Model
{
    protected $fillable=['subject','body','user_id'];


    public function user()
    {
        return $this->belongsTo(User::class);
    }

    public function comments()
    {
        return $this->morphMany(Comment::class, 'commentable');
    }
}

Route

Route::get('/news/{slug}','NewsController@show');

I am getting this error:

SQLSTATE[HY000]: General error: 1364 Field 'slug' doesn't have a default value (SQL: insert into `news` (`subject`, `body`, `user_id`, `updated_at`, `created_at`) values (Rema Is Leading the New School Wave in Nigeria, <p>Really good series, I jumped in around Part 20, your presentation is by far the best I have found for a beginners Laravel tutorial and I'm going to start over from the beginning. One thing I noticed in this video was that the slug had min / max&nbsp;</p>, 1, 2019-09-04 15:47:07, 2019-09-04 15:47:07))
0 likes
2 replies
Sti3bas's avatar

You can use model events for that. Add this code to your model class:

public static function boot() {
    parent::boot();

    static::creating(function ($model) {
        $model->slug = str_slug($model->subject, "-");
    });
}

Please or to participate in this conversation.