Laravel 8 Create Unique Slug Example

Hello Dev,

Right now, i we’ll present you laravel eight create distinctive slug instance. This text gives you easy instance of laravel eight create distinctive slug instance. you’ll laravel eight create distinctive slug instance. On this article, we’ll implement a laravel eight create distinctive slug instance.

So let’s observe few step to create instance of laravel eight create distinctive slug instance.

Slug Instance

app/Fashions/Pages.php


<?php
namespace AppModels;
use IlluminateDatabaseEloquentModel;
use IlluminateSupportStr;

class Pages extends Mannequin
{

	/**
	 * The attributes which can be mass assignable.
	 *
	 * @var array
	 */
	protected $fillable = [
		'title', 'contant', 'slug'
	];


    protected static operate boot()
    {
        father or mother::boot();
        static::created(operate ($submit) {
            $post->slug = $post->createSlug($post->title);
            $post->save();
        });
    }

    personal operate createSlug($title){
        if (static::whereSlug($slug = Str::slug($title))->exists()) {
            $max = static::whereTitle($title)->newest('id')->skip(1)->worth('slug');
            if (is_numeric($max[-1])) {
                return preg_replace_callback('/(d+)$/', operate ($mathces) {
                    return $mathces[1] + 1;
                }, $max);
            }
            return "{$slug}-2";
        }
        return $slug;
    }
}


Controller Code:


<?php
  
namespace AppHttpControllers;
  
use AppModelsPages;
use IlluminateHttpRequest;
  
class PageController extends Controller
{
    /**
     * Show a list of the useful resource.
     *
     * @return IlluminateHttpResponse
     */
    public operate index()
    {
        $web page = Pages::create([
            "title" => "Laravel CRUD"
        ]);
        dd($web page);
    }
}

Output:


Laravel-CRUD
Laravel-CRUD-2
Laravel-CRUD-3

I hope it’ll help you…

Komentar

Postingan populer dari blog ini

PHP 8 Multiple Select Dropdown Example

Laravel 8 Get HTTP Hostname

JQuery Drag And Drop Menu Example