Last active
July 3, 2020 21:59
-
-
Save Galibri/1ca95014af47c6fe1fa6214e8e8bb4fa to your computer and use it in GitHub Desktop.
Laravel Unique slug, Very easy stuffs..
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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