Do you know we can fire specific event from model without passing data from controller ? In this tutorial i am going to show you how we can do it without passing data from controller. We can do it using Laravel model events.
Suppose, let think when new user is created then we will fire a event. For doing this we can pass newly created user from controller, but now we can do it without passing data. Let's try.
Step 1 : First Create a Event
Now checking our required thing just create a event. For creating it just run below command.
php artisan make:event TestEvent
Now a new folder will be created inside app folder. Our newly created file location is app/Events/TestEvent.php.
Step 2 : Setup Model
Now we have to manage our model as we won't pass data from controller. So open User model and paste this following code. Eloquent models fire several events, allowing you to hook into various points in the model's lifecycle using the following methods:
creating
, created
, updating
, updated
, saving
, saved
, deleting
, deleted
, restoring
, restored
. Events allow you to easily execute code each time a specific model class is saved or updated in the database.
Read also : How to Create Middleware with Parameters in Laravel 6
The retrieved
event will fire when an existing model is retrieved from the database. When a new model is saved for the first time, the creating
and created
events will fire
Note : When issuing a mass update or delete via Eloquent, the
saved
,updated
,deleting
, anddeleted
model events will not be fired for the affected models.
app/User.php
protected $dispatchesEvents = [
'saved' => \App\Events\TestEvent::class,
];
Here i call $dispatchesEvents for firing events. Now when a user is created , this event will be fired. Now open TestEvent and paste this following code.
app/Events/TestEvent.php
namespace App\Events;
use App\User;
use Illuminate\Broadcasting\Channel;
use Illuminate\Queue\SerializesModels;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
class TestEvent
{
use Dispatchable, InteractsWithSockets, SerializesModels;
public $user;
public function __construct(User $user)
{
$this->user = $user;
info("Now this user {$this->user->name} is created");
}
public function broadcastOn()
{
return [];
}
}
Look here we log our current created user instance but not passing data from controler. We catch all current created user from constructor and print user anme in log file to check it. Now just open terminal and run below command.
php artisan tinker
//then
factory(\App\User::class,1)->create()
After running this command you will see the followng output from our log file. See you just created this user.
Now to check it, open your log file and se the magic.
storage/logs/laravel.log
Look we just created name: "Ellsworth Gulgowski" this user and this user name is our log file. So hope you will understand this tutorial that what i am trying to tell you.
Now you have no need to pass data from controller like that
event( new \App\TestEvent($user))
So your controller will remain fresh and code looks clean. Hope it will help you.
If you are listening for many events on a given model, you may use observers to group all of your listeners into a single class. To create observer, run following command.
php artisan make:observer UserObserver --model=User
This command will place the new observer in your App/Observers
directory.
app/Observers/UserObserver.php
namespace App\Observers;
use App\User;
class UserObserver
{
public function created(User $user)
{
//your logic gose here
}
public function updated(User $user)
{
//
}
public function deleted(User $user)
{
//
}
public function forceDeleted(User $user)
{
//
}
}
To register an observer, use the observe
method on the model you wish to observe. You may register observers in the boot
method of one of your service providers.
In this example, we'll register the observer in the AppServiceProvider
: You may use your own custom provider by running this following command.
php artisan make:provider MyOwnServiceProvider
and just register it inside your config/app.php providers array. And just registered your UserObserver like below inside boot method.
app/Providers/AppServiceProvider.php
namespace App\Providers;
use App\Observers\UserObserver;
use App\User;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
public function register()
{
//
}
public function boot()
{
User::observe(UserObserver::class);
}
}
Hope this tutorial will help you. If you have any query, feel free to comment or if you have find any error, you can inform me.
#laravel-6 #models #evenst