Skip to content

Instantly share code, notes, and snippets.

@Galibri
Last active July 3, 2020 21:59
Show Gist options
  • Save Galibri/1ca95014af47c6fe1fa6214e8e8bb4fa to your computer and use it in GitHub Desktop.
Save Galibri/1ca95014af47c6fe1fa6214e8e8bb4fa to your computer and use it in GitHub Desktop.
Laravel Unique slug, Very easy stuffs..
<?php
/**
* Crate method
* Change Product to your desired model name, dont' forget to import the Model and Str classname.
* Change whereSlug to where_(your_slug_field_name) with CamelCase
*/
public function store(Request $request) {
$unique_slug = Str::slug($request->title);
$unique_next = 2;
while(Product::whereSlug($unique_slug)->first()) {
$unique_slug = Str::slug($request->title) . '-' . $unique_next;
$unique_next++;
}
$product = new Product;
$product->slug = $unique_slug;
$product->save();
}
/**
* Update method
* Change Product to your desired model name
* Change whereSlug to where_(your_slug_field_name) with CamelCase
*/
public function update(Request $request, Product $product) {
$unique_slug = Str::slug($request->name);
$unique_next = 2;
while(Product::whereSlug($unique_slug)->first()) {
if($product->name == $request->name) {
$unique_slug = $product->slug;
break;
}
$unique_slug = Str::slug($request->name) . '-' . $unique_next;
$unique_next++;
}
$product->slug = $unique_slug;
$product->save();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment