Nasrul Hazim Bin Mohamad

Laravel: Observer

Nov
17

Assalamualaikum & Hi,

Eloquent models fire several events, allowing you to hook into the following points in a model’s lifecycle: retrieved, 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.

Based on events above, we can capture all the events mentioned above either by setup in model’s property called $dispatchesEventsor we can setup an observer to capture all the events above.

Here I’m going to show how to setup observer and then how you can manage your observers.

Fundamental

Create a new Laravel Application laravel new observer-app

Go into observer-app directory.

Create a directory called Observers in app directory and create a new file called OnCreatingObserver.php in app/Observers

OnCreatingObserver class will capture Eloquent event on creating a new record for a given model.

Now you need to register your model, to the OnCreatingObserver. Open up your app/Providers/AppServiceProvider.php and add the following in boot method.

Lastly, update your user’s migration file to add in new column called hashslug.

Run php artisan migrate

Tinker

I always love to run and test things using Tinker, rather than test my backend codes on front-end – web.

Now create a folder in your application tinkers and add in a new file called create_user.php.

Open up create_user.php and add the following codes to create a new user.

Now run php artisan tinker tinkers/create_user.php. You should have something like the following:

Create user via tinker

Notice that we have our hashslug inserted – but we don’t even assign the value in the tinker (create_user.php)!

So, that’s how a simple user case on observe events emiited by Eloquent.

Problem Statement

So you know, you have the an observer and it’s awesome. Easy for you. But imagine you have more than 10 models need to observe the OnCreatingObserver. It’s a tedious job to manage and your AppServiceProvider‘s boot method will be bloated.

Issues

Three issues here:

  1. Bloated Codes
  2. Unmanageable Codes
  3. Single Observer, observe by many models.

Solutions

Bloated Codes, UnManageable Codes

For the issue no. 1, the strategy, which I apply to my recent works – refer to how Laravel provide us to register custom commands in their app/Console/Kernel.php.

Same thing I will apply for the Bloated Codes.

Create a file name Kernel.php in app/Observers directory.

Add the following codes in app/Observers/Kernel.php. This kernel.php it’s an endpoint for register all your observers.

Above code will register all your model-observer based on your setup in $observers property. An example of the usage on how you should register your model and observer:

Once you’re done setup your model and observer, you may replace your \App\User::observe(\App\Observers\OnCreatingObserver::class); in AppServiceProvider.php with \App\Observers\Kernel::make()->observes();

Now you observers will be much cleaner and manageable.

BUT, another issue raised – what if you have a single observer, observed by many models? It’s a tedious job to register the same observer for different models.

Single Observer, Observe By Many Models.

For the previous issue, let’s refactor a bit:

Now, to add capability to register multiple models for an observer, we going to add two things:

Add property $observedBy:

Add method observeBy():

Now update your observes() to run both observeSingle() and observeBy().

You’re done now! Here some example on how you can setup your $observeBy property:

Final Kernel File for Observer

Observer App

How to Use Lumen in Laravel

Oct
10

You love the speed of Lumen but you want to have the features of Laravel? No problem, just include Lumen inside Laravel!

Below are the steps to include Lumen inside of the Laravel

Please ensure to create an empty Laravel and Lumen project because you need to copy some files from Lumen to Laravel

Here the working sample of the Lumen in Laravel – Lumen in Laravel

Laravel: How to Create Custom Artisan Command

Aug
16

There’s only 3 steps required to setting up new Artisan command.

1. Step 1 – Create a new console file

php artisan make:console CommandName

2. Step 2 – Open up `app/Console/Commands/CommandName.php` and update the signature and the description property.

     /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'env:db';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Configure database settings';

3. Step 3 – Register your new Artisan command in `app/Console/Kernel.php`

    /**
     * The Artisan commands provided by your application.
     *
     * @var array
     */
    protected $commands = [
        // Commands\Inspire::class,
        Commands\DatabaseEnvironment::class
    ];

Now you’re ready with your new artisan command. Check your command with `php artisan`. It should have something like this one.

Screen Shot 2016-08-16 at 6.05.26 PM

Here the a sample code.

Reference

Artisan

Live: Laravel 101

Aug
10

Assalamualaikum,

It’s been a while since the last time I post in my blog.

Now just to share a bit of Laravel, 101 on my Facebook Live.

Training: Laravel – Batch 4

Apr
10

Registration Open Now!

Please register at Laravel – Batch 4

Course Details

Date: 16th & 17th April 2016

Location: http://bit.ly/cc-training-location

Fee: RM 300

Syllabus Details

Setup

The Basic
– Routing
– Controllers
– Views
– Blade Templates

Database
– Migrations
– Seeding

Eloquent ORM
– CRUD
– Relationship

Packages
– User Management
– Access Control List

Laravel: How to Install Laravel’s Artisan in Windows

Aug
20
$ composer create-project laravel/laravel --pref-dist
$ cd laravel
$ composer install
$ php artisan list

Following are the result

Laravel Artisan List

Laravel Artisan List