Laravel 8.0 Create/Generate Slug Example

Hello, artisan today I am going to show you an interesting topic in laravel. In this example you will learn how generate slug form title. This very easy to implement using laravel helper function.

Create project

composer create-project --prefer-dist laravel/laravel Blog

Setup Database Credentials

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel_tutorials
DB_USERNAME=root
DB_PASSWORD=

Create Model and also Migration

php artisan make:model Post -m

Post is the model name and -m create a posts table migration within database/migrations folder.

Update Model and Migration file:

app\Models\Post.php
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    use HasFactory;
    protected $fillable = [
        'title',
        'body',
        'slug',
    ];
}
app\database\migrations\######_create_posts_table.php
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreatePostsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->id();
            $table->string('title');
            $table->text('body');
            $table->text('slug');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('posts');
    }
}

Create a resource Controller

php artisan make:controller PostController --resource

Read also

https://codesnipeet.com/laravel-8-0-resource-routing-example/

Add routes

app\routes\web.php
use App\Http\Controllers\PostController; \\ import at the top
Route::resource('/posts',PostController::class);

This command create bellow routes. You can check it by running

php artisan route:list
"laravel routeresource name" "resource route laravel 8" "laravel resource" "laravel resource route parameters" "laravel resource controller example" "laravel api routes" "laravel restful controller" "laravel controller does not exist"
routes 1
"laravel routeresource name" "resource route laravel 8" "laravel resource" "laravel resource route parameters" "laravel resource controller example" "laravel api routes" "laravel restful controller" "laravel controller does not exist"
routes2

Update PostController

app\Http\Controllers\PostController.php
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Post;


class PostController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
       //
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('add_posts');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $post = new Post();
        $post->title = $request->get('title');
        $post->body = $request->get('body');
        $post->slug = str_slug($request->get('title'),'-');
        $post->save();
        return  back();
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }
}

In the store method, for generating slug using post title we use the str_slug helper function. str_slug takes two inputs first one is a string and the second one is the separator.

Create view file

To save a post to the database, our add_posts.blade.php look likes:

app\resources\views\add_posts.blade.php
<form action="{{route('posts.store')}}" method="post">
    @csrf
    <input type="text" name="title">
    <textarea name="body"></textarea>
    <input type="submit" value="submit">
</form>

we kept it very simple!

After submit to the database, it creates a slug title for every record.

I thinks it will help!