Laravel 9 Create Record if Not Exists Example Tutorial

Reading Time: 5 minutes
1,515 Views

Inside this article we will see the concept i.e Laravel 9 Create Record if Not Exists Example Tutorial. Article contains the classified information about How to create record if not exists in Laravel.

If you are looking for a solution i.e How to check if a record exists with Laravel Eloquent then this article will help you a lot for this. Tutorial is super easy to understand and implement it in your code as well.

Read More: Laravel 9 How To Get Last 5 Records Using Model Tutorial

Let’s get started.

Laravel Installation

Open terminal and run this command to create a laravel project.

composer create-project laravel/laravel myblog

It will create a project folder with name myblog inside your local system.

To start the development server of laravel –

php artisan serve

URL: http://127.0.0.1:8000

Assuming laravel already installed inside your system.

Create Database & Connect

To create a database, either we can create via Manual tool of PhpMyadmin or by means of a mysql command.

CREATE DATABASE laravel_app;

To connect database with application, Open .env file from application root. Search for DB_ and update your details.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel_app
DB_USERNAME=root
DB_PASSWORD=root

Create Migration

Open project into terminal and run this command to create a migration file.

$ php artisan make:migration create_posts_table

Above command will create 2022_09_29_212520_create_posts_table.php file inside /database/migrations folder.

Read More: Laravel 9 How To Set Default Values in Model For Columns

Open xxx_create_posts_table.php file and write this code into it.

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->id();
            $table->string('title', 120);
            $table->string('slug', 120);
            $table->text('body');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('posts');
    }
};

Run Migration

Back to terminal and run this command for migrations.

$ php artisan migrate

It will create posts table into your database.

Create Model

Back to terminal and run this command to create model.

$ php artisan make:model Post

It will create a model file Post.php inside /app/Models folder.

Read More: Laravel 9 How To Get Request Headers Example Tutorial

Open Post.php and write this following code into it.

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    use HasFactory;

    protected $fillable = [
        'title', 'slug', 'body'
    ];
}

Create Controller

Back to project terminal and run this command to create a controller file.

$ php artisan make:controller PostController

Above command will create a file i.e PostController.php inside /app/Http/Controllers folder.

Example #1

Open PostController.php and write this following code into it.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Post;

class PostController extends Controller
{
    public function index(Request $request)
    {
        Post::firstOrCreate(

            ['slug' => $request->slug],

            ['title' => $request->title, 'body' => $request->body]
        );
    }
}

firstOrCreate method is used to create a record if it does not already exist in the table in laravel. It has two parameters, conditions and fields and these parameters should be an array.

It tries to find a model matching the attributes you pass in the first parameter. If a model is not found, it automatically creates and saves a new record after applying attributes passed in the second parameters including first parameter field and values. 

Read More: Laravel 9 How To Get Database Name Example Tutorial

This code snippet will create a new post record including title, body and slug fields in the post table if the record is not already exist with this particular slug.

Example #2

Open PostController.php and write this following code into it.

<?php
   
namespace App\Http\Controllers;
  
use Illuminate\Http\Request;
use App\Models\Post;
  
class PostController extends Controller
{
    public function index()
    {
        $slug = 'platinum';
        $post = Post::where('slug', $slug)->first();
  
        if (is_null($post)) {

            $post = new Post();

            $post->title = 'Platinum';
            $post->slug = 'platinum';
	        $post->body = 'Test platinum';
	  
	        $post->save();
	  
	        dd($post);
        }
    }
}

We hope this article helped you to learn Laravel 9 Create Record if Not Exists Example Tutorial in a very detailed way.

Online Web Tutor invites you to try Skillshike! Learn CakePHP, Laravel, CodeIgniter, Node Js, MySQL, Authentication, RESTful Web Services, etc into a depth level. Master the Coding Skills to Become an Expert in PHP Web Development. So, Search your favourite course and enroll now.

If you liked this article, then please subscribe to our YouTube Channel for PHP & it’s framework, WordPress, Node Js video tutorials. You can also find us on Twitter and Facebook.