Create record with unique slug in laravel
Create record with unique slug in laravel
In this session, we are going to try to solve the "Create record with unique slug in laravel" puzzle by using the computer language.
You can create a unique slug for a record in the table in laravel. Sometimes you have to create the slug which should be unique so that you can uniquely identify each record without using its id and it’s also required for SEO purposes.-
Create post with unique slug in laravel 8
app\Http\Controllers\HomeController.php
Import class after the namespace and before the class definition
use Illuminate\Support\Str; use App\Models\Post;
Controller's method
public function createSlug($title, $table , $id = 0) { // Normalize the title and create slug $slug = Str::slug($title); // Get any that could possibly be related. // This cuts the queries down by doing it once. $allSlugs = $this->getRelatedSlugs($slug, $table, $id); // If we haven't used it before then we are all good. if (! $allSlugs->contains('slug', $slug)){ return $slug; } // Just append numbers like a savage until we find it is not used. for ($i = 1; $i <= 10; $i++) { $newSlug = $slug.'-'.$i; if (! $allSlugs->contains('slug', $newSlug)) { return $newSlug; } } throw new \Exception('Can not create a unique slug'); } //Function to get all the records which has same slug public function getRelatedSlugs($slug, $table, $id = 0) { return DB::table($table)->select('slug')->where('slug', 'like', $slug.'%') ->where('id', '<>', $id) ->get(); } public function createPost(){ $title = 'Nisi iure id ut molestiae quae'; $slug = $this->createSlug($title, 'posts'); $post = Post::create( ['title' => $title, 'slug' => $slug] ); echo $post; }
//routes\web.php use App\Http\Controllers\HomeController; Route::get('/create-post', [HomeController::class, 'createPost']);
Output :
{"title":"Nisi iure id ut molestiae quae","slug":"nisi-iure-id-ut-molestiae-quae","updated_at":"2021-09-16T04:43:04.000000Z",
"created_at":"2021-09-16T04:43:04.000000Z","id":1}You have to create a posts table with a title and slug column. Create the post model with fillable attributes and add title and slug to this fillable attribute. You have to pass the post title and table name to createSlug() method to create the unique slug by appending 1, 2, 3, … if the slug already exists with the same value in the table.
If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.
Don't forget to share this article! Help us spread the word by clicking the share button below.
We appreciate your support and are committed to providing you valuable and informative content.
We are thankful for your never ending support.
Random Code Snippet Queries: Laravel
- Calculate age from date of birth in Laravel
- Generate unique username in Laravel
- InRandomOrder() method with example in laravel
- Route group with URI prefix using middleware and route name prefixes
- Return view from route Laravel
- Call to a member function update() on null
- Database transactions in laravel
- Laravel change date format
- How to get column names from table in Laravel
- Get previous date data in laravel
- Run artisan command to generate key in laravel
- How to get file extension from input type file in laravel
- Permanently delete a record in laravel
- Target class [App\Http\Controllers\Auth\Request] does not exist.
- Display message with session flash using bootstrap alert class in laravel
- Route not defined in Laravel
- Method chaining in Laravel
- How to return a column with different name in Laravel
- Command to create MySQL Docker image and access the MySQL command-line interface (CLI) within a running Docker container
- Method Illuminate\Database\Eloquent\Collection::appends does not exist
- Validation errors for multiple forms on same page Laravel
- Laravel route parameter
- How to Run CRON Job on LIVE SERVER on Cpanel in Laravel Project
- How to make Copy or Duplicate table row in laravel
- Skip first n record and display rest records in laravel view