Raviya Technical
Published in

Raviya Technical

Laravel Advance | Generate Unique Slug

<?phpnamespace App\Models;use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;
class Product extends Model{use HasFactory;protected $fillable = ['title', 'detail', 'slug'];protected static function boot(){parent::boot();static::created(function ($product) {$product->slug = $product->createSlug($product->title);$product->save();});}private function createSlug($title){if (static::whereSlug($slug = Str::slug($title))->exists()) {$max = static::whereTitle($title)->latest('id')->skip(1)->value('slug');if (is_numeric($max[-1])) {return preg_replace_callback('/(\d+)$/', function ($mathces) {return $mathces[1] + 1;}, $max);}return "{$slug}-2";}return $slug;}}
<?phpnamespace App\Http\Controllers;use App\Models\Product;
use Illuminate\Http\Request;
class ProductController extends Controller{public function index(){$product = Product::create(["title" => "Laravel 8 Image Upload"]);dd($product);}}
laravel-8-image-uploadlaravel-8-image-upload-2laravel-8-image-upload-3laravel-8-image-upload-4

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store