Laravel 10 Model Create Events Example Tutorial

Reading Time: 6 minutes
182 Views

Model Events in Laravel 10 give a powerful mechanism to respond to various model activities such as generating, updating, or deleting records. Model Create Events, in particular, let you to take action when a new model instance is generated.

In this article, we will look at Model Create Events in Laravel 10 and provide you with a complete explanation as well as practical examples.

When a new record is produced, you may use these events to trigger activities such as sending notifications, changing linked records, or performing custom logic. This is particularly beneficial in cases like as user registration, order creation, and content posting.

Read More: Laravel 10 How to Add Qr Code in PDF Using DomPDF

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.

What are Model Events in Laravel?

A Model in Laravel 10 provides an abstraction for working with a database table via a high-level API. Among these APIs are events, which are fired when actions are performed on the model.

Model events are simply life cycle hooks that you may use to easily run code when database records are saved, changed, or removed.

Events receive the model instance that is being saved, modified, or removed.

Here are the following events which we can use with laravel model –

  • creating and created: Fires before and after records have been created.
  • updating and updated: Fires before and after records are updated.
  • saving and saved: Fires before and after records are saved (i.e created or updated).
  • deleting and deleted: Fires before and after records are deleted or soft-deleted.
  • restoring and restored: Fires before and after soft-deleted records are restored.
  • retrieved: Fires after records have been retrieved.

Laravel Model Create Events

Here, you will understand the complete concept of model create events with an example.

Model create events means the events which fired when you create an instance of any Model and perform create operation (to save data).

Let’s consider an example.

Step #1: Create a Model (Say Post)

Open project terminal and run this command to create a Post model,

php artisan make:model Post

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

Step #2: Register Model Create Events

Open Post.php and write this code into it.

<?php
  
namespace App;
  
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;
  
class Post extends Model
{
    /**
     * The attributes that are mass assignable.
     *
     * @var array<int, string>
     */
    protected $fillable = [
        'title', 
        'content', 
        'slug'
    ];
    
    // Model create events
    protected static function boot()
    {
        parent::boot();
   
        static::creating(function ($post) {
            info('Creating event call: '.$post);
   
            $post->slug = Str::slug($post->title);
        });
  
        static::created(function ($post) {
        	info('Created event call: '.$post);
        });
    }
}

Here, when a new Post model is being created. The creating event is triggered, and you can see we used a closure to generate a slug based on the title attribute.

Read More: How To Convert an Image to Webp in Laravel 10 Tutorial

For slug, we are using Str::slug method of Laravel to create a URL-friendly slug from the title.

Step #3: Create Post data via Model

Next, when you create a new Post instance and save data via it, the creating event will automatically set the slug for you.

Here’s how you can create a new post:

<?php
     
namespace App\Http\Controllers;
    
use Illuminate\Http\Request;
use App\Models\Post;
    
class PostController extends Controller
{
    public function index(Request $request)
    {
        $post = Post::create([
            "title" => "This is Testing",
            "content" => "This is a Testing"
        ]);
  
        dd($post);
    }
}

Now, Once you run following code and you will find following log for calling creating event and created event as:

Output

[2023-10-27 14:37:26] local.INFO: Creating event call: {"title":"This is Testing","content":"This is a Testing"}

[2023-10-27 14:37:26] local.INFO: Created event call: {"title":"This is Testing","content":"This is a Testing","slug":"this-is testing","updated_at":"2023-10-27T14:37:26.000000Z","created_at":"2023-10-27T14:37:26.000000Z","id":10}

That’s it.

We hope this article helped you to learn about Laravel 10 Model Create Events 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.

Sanjay KumarHello friends, I am Sanjay Kumar a Web Developer by profession. Additionally I'm also a Blogger, Youtuber by Passion. I founded Online Web Tutor and Skillshike platforms. By using these platforms I am sharing the valuable knowledge of Programming, Tips and Tricks, Programming Standards and more what I have with you all. Read more