How to Generate Unique slug in Laraval 7.x Example
source link: https://www.laravelcode.com/post/how-to-generate-unique-slug-in-laraval-7-x-example
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
How to Generate Unique slug in Laraval 7.x Example
Want to engender unique slug in Laravel? Its fairly facile. Lets endeavor.
First of all you should have a `slug` column in your Model. Suppose you have Post model. integrate this code inside model class,
Now you can call slugify method anywhere utilizing post object for engender unique slug. Surmise, you optate to store a post with slug. in PostController you can facilely engender slug and store into database.
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
# verify and return custom slug string
public function slugify($text)
{
# remove ? mark from string
$slug = preg_replace('/\?/u', ' ', trim($text));
$slug = preg_replace('/\s+/u', '-', trim($slug));
# slug repeat check
$latest = $this->whereRaw("slug REGEXP '^{$slug}(-[0-9]+)?$'")
->latest('id')
->value('slug');
if($latest){
$pieces = explode('-', $latest);
$number = intval(end($pieces));
$slug .= '-' . ($number + 1);
}
return $slug;
}
}
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use App\Post;
class PostController extends Controller
{
public function store(Request $request)
{
$post = new Post();
//..............................
/* unique slug example
* my name is khan => my-name-is-khan
*/
$post->slug = $post->slugify($request->title); // unique slug generator
//..............................
$post->save();
}
}
i hope you like this article.
Hi, My name is Harsukh Makwana. i have been work with many programming language like php, python, javascript, node, react, anguler, etc.. since last 5 year. if you have any issue or want me hire then contact me on [email protected]
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK