<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>Forem: Elisha Ukpong</title>
    <description>The latest articles on Forem by Elisha Ukpong (@drumzminister).</description>
    <link>https://forem.com/drumzminister</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F59279%2F4b2c7603-d34b-475f-bccf-39374f9b7328.jpeg</url>
      <title>Forem: Elisha Ukpong</title>
      <link>https://forem.com/drumzminister</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://forem.com/feed/drumzminister"/>
    <language>en</language>
    <item>
      <title>Laravel Events and Listeners</title>
      <dc:creator>Elisha Ukpong</dc:creator>
      <pubDate>Sun, 19 Jul 2020 23:09:07 +0000</pubDate>
      <link>https://forem.com/drumzminister/laravel-events-and-listeners-25fp</link>
      <guid>https://forem.com/drumzminister/laravel-events-and-listeners-25fp</guid>
      <description>&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--UbqoC_kV--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/1024/1%2Aac0dNvKuaAZ_A715J49lrg.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--UbqoC_kV--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/1024/1%2Aac0dNvKuaAZ_A715J49lrg.png" alt=""&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Previously, I wrote about Laravel Observers and mentioned it as a feature of Laravel framework that I love, since I came across it.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Read about it &lt;a href="https://medium.com/@elishaukpongson/introducing-laravel-observers-8f0198c6c9c"&gt;here&lt;/a&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Today, I will be shedding light on another part of the Laravel framework that interests me too, events and listeners.&lt;/p&gt;

&lt;p&gt;Events are just ways to alert your application that an action has happened, and the events can be dispatched at any point of your application, the controller, the model, the middleware, anywhere — even in the blade files(you shouldn’t do this, but you get my point).&lt;/p&gt;

&lt;p&gt;Listeners, like the name implies, listens for events that occur in your application, but they do not just listen to any event, each listener must be mapped to an event before it listens for that event.&lt;/p&gt;

&lt;p&gt;For a listener to respond to a dispatched event, the listener class must be mapped to a particular event class. These mappings happen in the EventServiceProvider class which can be found in the &lt;em&gt;app\Providers&lt;/em&gt; folder.&lt;/p&gt;

&lt;p&gt;An event can have multiple listeners mapped to it and when it is dispatched, all listening classes will be triggered in succession following the order in which it is mapped.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;//Default EventServiceProvider Class


&amp;lt;?php

namespace App\Providers;

use Illuminate\Auth\Events\Registered;
use Illuminate\Auth\Listeners\SendEmailVerificationNotification;
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;
use Illuminate\Support\Facades\Event;

class EventServiceProvider extends _ServiceProvider_  
{
_/\*\*  
     \* The event listener mappings for the application.  
     \*  
     \*_ **_@var_** _array  
     \*/_ protected $listen = [
        Registered::class =&amp;gt; [
            SendEmailVerificationNotification::class,
        ],
    ];

_/\*\*  
     \* Register any events for your application.  
     \*  
     \*_ **_@return_** _void  
     \*/_ public function boot()
    {
        parent::_boot_();

        //
    }
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;h3&gt;
  
  
  Creating an event and listener class
&lt;/h3&gt;

&lt;p&gt;To create an event class, make use of the &lt;strong&gt;&lt;em&gt;make:event&lt;/em&gt;&lt;/strong&gt; artisan command:&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;php artisan make:event &lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;This command will create a new class into the &lt;em&gt;app\Events&lt;/em&gt; folder of your application and that is all you need to create an event class.&lt;/p&gt;

&lt;p&gt;To create a listener class, make use of the &lt;strong&gt;&lt;em&gt;make:listener&lt;/em&gt;&lt;/strong&gt; artisan command:&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;php artisan make:listener &lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;This command, like in the Event creation, will create a new class into the &lt;em&gt;app\Listeners&lt;/em&gt; folder of your application and that is all you need to create a listener class.&lt;/p&gt;

&lt;p&gt;Another way of creating events and listeners, this way might even be termed easier than the ones earlier mentioned, is to register events and listeners in the EventServiceProvider class, then run:&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;php artisan event:generate&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;This command will scan through the EventServiceProvider class and generate the missing events and listeners based on registration.&lt;/p&gt;

&lt;p&gt;You might already be wondering how to register an event and map a listener to it, yea? To do that, follow the pattern below:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;_//Event Service Provider Class_

_/\*\*  
 \* The event listener mappings for the application.  
 \*  
 \*_ **_@var_** _array  
 \*/_ protected $listen = [
    'Event Class' =&amp;gt; [
        'Listener Class',
        'Another Listener Class',
        'Yet Another Listener Class',
    ],
];
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;Like I earlier said, you can map more than one listener to a particular event and it will get processed in succession, following the order in which they are mapped.&lt;/p&gt;

&lt;h3&gt;
  
  
  Dispatching an event
&lt;/h3&gt;

&lt;p&gt;To dispatch your event and trigger the listeners, there are two methods known to me as at the time of this writing:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;event(new EventClass());&lt;/li&gt;
&lt;li&gt;EventClass::dispatch();&lt;/li&gt;
&lt;/ul&gt;

&lt;blockquote&gt;
&lt;p&gt;If your event uses the &lt;em&gt;Illuminate\Foundation\Events\Dispatchable&lt;/em&gt; trait, you may call the static &lt;em&gt;dispatch&lt;/em&gt; method on the event. Any arguments passed to the &lt;em&gt;dispatch&lt;/em&gt; method will be passed to the event's constructor.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;You should note that &lt;strong&gt;public&lt;/strong&gt; properties declared in the event class, can be accessed in the listener class which is mapped to it.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;//Registered Event using in register controller.

&amp;lt;?php

namespace Illuminate\Auth\Events;

use Illuminate\Queue\SerializesModels;

class Registered
{
    use SerializesModels;

_/\*\*  
     \* The authenticated user.  
     \*  
     \*_ **_@var_** _\Illuminate\Contracts\Auth\Authenticatable  
     \*/_ public $user;

_/\*\*  
     \* Create a new event instance.  
     \*  
     \*_ **_@param_** _\Illuminate\Contracts\Auth\Authenticatable $user  
     \*_ **_@return_** _void  
     \*/_ public function \_\_construct($user)
    {
        $this-&amp;gt;user = $user;
    }
}

&amp;lt;?php

namespace App\Listeners;

use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;

class RegisteredListener
{
_/\*\*  
     \* Create the event listener.  
     \*  
     \*_ **_@return_** _void  
     \*/_ public function \_\_construct()
    {
        //
    }

_/\*\*  
     \* Handle the event.  
     \*  
     \*_ **_@param_** _object $event  
     \*_ **_@return_** _void  
     \*/_ public function handle($event)
    {
        $event-&amp;gt;user 
        //this will have the content of the user property from the event class
    }
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;h3&gt;
  
  
  Use Case
&lt;/h3&gt;

&lt;p&gt;A very straightforward use-case of events and listeners would be the default user creation flow on the Laravel Framework.&lt;/p&gt;

&lt;p&gt;For a lot of applications, there might be numerous processes that happen right after a user is created, and having all these logic in the controller method, might not just cluster up the controller method but for every additional process I want to take after a user signs up on my app.&lt;/p&gt;

&lt;p&gt;I will have to go back to that method and do edits which defies both the Open/Close and the Single Responsibility Principle of the S.O.L.I.D principles, events, and listeners come to the rescue.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;What is S.O.L.I.D Principle?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;S.O.L.I.D is an acronym that represents five principles of object-oriented programming and code design theorized by our beloved &lt;strong&gt;Uncle Bob&lt;/strong&gt; (Robert C. Martin) by the year 2000. The author Michael Feathers was responsible for creating the acronym:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;[S]&lt;/strong&gt;ingle Responsibility Principle&lt;br&gt;&lt;br&gt;
&lt;strong&gt;[O]&lt;/strong&gt;pen/Closed Principle&lt;br&gt;&lt;br&gt;
&lt;strong&gt;[L]&lt;/strong&gt;iskov Substitution Principle&lt;br&gt;&lt;br&gt;
&lt;strong&gt;[I]&lt;/strong&gt;nterface Segregation Principle&lt;br&gt;&lt;br&gt;
&lt;strong&gt;[D]&lt;/strong&gt;ependency Inversion Principle&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Single Responsibility Principle (SRP) &lt;/strong&gt;— A class should have one, and only one, reason to change.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Open/Closed Principle (OCP)&lt;/strong&gt; — You should be able to extend a classes behavior, without modifying it.&lt;/p&gt;

&lt;p&gt;Excerpts taken from: &lt;a href="https://medium.com/@mari_azevedo/s-o-l-i-d-principles-what-are-they-and-why-projects-should-use-them-50b85e4aa8b6"&gt;https://medium.com/@mari_azevedo/s-o-l-i-d-principles-what-are-they-and-why-projects-should-use-them-50b85e4aa8b6&lt;/a&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;On your default Register controller, you will see that a trait called RegisterUsers is used and this houses most of the logic for user creation. Inside the trait, there is a register method and that will be our concern.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;_/\*\*  
 \* Handle a registration request for the application.  
 \*  
 \*_ **_@param_** _\Illuminate\Http\Request $request  
 \*_ **_@return_** _\Illuminate\Http\Response  
 \*/_ public function register(Request $request)
{
    $this-&amp;gt;validator($request-&amp;gt;all())-&amp;gt;validate();

**event(new Registered($user = $this-&amp;gt;create($request-&amp;gt;all())));**

    $this-&amp;gt;guard()-&amp;gt;login($user);

    if ($response = $this-&amp;gt;registered($request, $user)) {
        return $response;
    }

    return $request-&amp;gt;wantsJson()
                ? new Response('', 201)
                : redirect($this-&amp;gt;redirectPath());
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;In the above code snippet, take notice of the emboldened line of code, this dispatches an event called Registered, for every time a user is registered on your application which can be listened to, by creating a listener class and mapping it to the event in the EventServiceProvider.&lt;/p&gt;

&lt;p&gt;Imagine I am building a student portal and when a student is registered I have to:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Assign the student a class&lt;/li&gt;
&lt;li&gt;Assign the student a seat in the class&lt;/li&gt;
&lt;li&gt;Assign the student a lab partner&lt;/li&gt;
&lt;li&gt;Assign the student a library card, and the list goes on and on and on.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;A typical way to do this might be to dump all the logic into the register controller method, like below:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;_/\*\*  
 \* Handle a registration request for the application.  
 \*  
 \*_ **_@param_** _\Illuminate\Http\Request $request  
 \*_ **_@return_** _\Illuminate\Http\Response  
 \*/_ public function register(Request $request)
{
    $this-&amp;gt;validator($request-&amp;gt;all())-&amp;gt;validate();

    event(new Registered($user = $this-&amp;gt;create($request-&amp;gt;all())));

   //Assign the student a class
   //Assign the student a seat in the class
   //Assign the student a lab partner
   //Assign the student a library card
   //more

    $this-&amp;gt;guard()-&amp;gt;login($user);

    if ($response = $this-&amp;gt;registered($request, $user)) {
        return $response;
    }

    return $request-&amp;gt;wantsJson()
                ? new Response('', 201)
                : redirect($this-&amp;gt;redirectPath());
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;While this may work, it breaks more than one principle as mentioned earlier. A way around this will be to create listeners and map it to the Registered event.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;_//Event Service Provider Class_

_/\*\*  
 \* The event listener mappings for the application.  
 \*  
 \*_ **_@var_** _array  
 \*/_ protected $listen = [
    Registered::class =&amp;gt; [
        AssignClassToStudent::class,
        AssignSeatToStudent::class,
        AssignLabPartnerToStudent::class,
        AssignLibraryCardToStudent::class,
    ],
];
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;With our provider having the above content, the &lt;em&gt;php artisan event:generate&lt;/em&gt; command will generate 4 listener class in the &lt;em&gt;app\Listener&lt;/em&gt; folder, but for brevity, I’ll continue with one — the assignClassToStudent listener&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;?php

namespace App\Listeners;

use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;

class assignClassToStudent
{
_/\*\*  
     \* Create the event listener.  
     \*  
     \*_ **_@return_** _void  
     \*/_ public function \_\_construct()
    {
        //
    }

_/\*\*  
     \* Handle the event.  
     \*  
     \*_ **_@param_** _object $event  
     \*_ **_@return_** _void  
     \*/_ public function handle($event)
    {
        $event-&amp;gt;user-&amp;gt;assignClassToStudentLogic();
    }
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;Following this pattern means, if there is more logic to do after a user is registered, you do not need to edit the register method, you just need to spin up a new listener and map it to the event. This way the register method only handles student registration and the other listeners handle the other responsibilities.&lt;/p&gt;

&lt;p&gt;The End.&lt;/p&gt;




</description>
      <category>events</category>
      <category>laraveldevelopment</category>
      <category>codenewbie</category>
      <category>laravel</category>
    </item>
    <item>
      <title>Introducing Laravel Observers.</title>
      <dc:creator>Elisha Ukpong</dc:creator>
      <pubDate>Sun, 19 Jul 2020 07:29:10 +0000</pubDate>
      <link>https://forem.com/drumzminister/introducing-laravel-observers-2k62</link>
      <guid>https://forem.com/drumzminister/introducing-laravel-observers-2k62</guid>
      <description>&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--YbtCnkQw--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/1024/1%2A0nzFC6JRXsr8J3Zq9BYvGw.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--YbtCnkQw--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/1024/1%2A0nzFC6JRXsr8J3Zq9BYvGw.png" alt=""&gt;&lt;/a&gt;Laravel Observers&lt;/p&gt;

&lt;p&gt;Laravel framework comes with lots of awesome features, the outstanding one for me is the model &lt;strong&gt;observers&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;According to the Laravel framework’s documentation:&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;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. Observers classes have method names which reflect the Eloquent events you wish to listen for. Each of these methods receives the model as their only argument. The make:observer Artisan command is the easiest way to create a new observer class.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;The observers helps me to declutter my controller of clean-up codes that I might have to run before or after making a model event, and also gives me a way to plug into the model’s event’s lifecycle and run any logic I might see fit.&lt;/p&gt;

&lt;p&gt;The model events that can be observed are spread across the model’s CRUD and includes:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Retrieved&lt;/li&gt;
&lt;li&gt;Creating&lt;/li&gt;
&lt;li&gt;Created&lt;/li&gt;
&lt;li&gt;Updating&lt;/li&gt;
&lt;li&gt;Updated&lt;/li&gt;
&lt;li&gt;Saving&lt;/li&gt;
&lt;li&gt;Saved&lt;/li&gt;
&lt;li&gt;Deleting&lt;/li&gt;
&lt;li&gt;Deleted&lt;/li&gt;
&lt;li&gt;Restoring&lt;/li&gt;
&lt;li&gt;Restored&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The above events can be observed for every model in the Laravel Framework and business logic attached to it, you can also dispatch custom events from the observer and listen to it from other parts of your application.&lt;/p&gt;

&lt;p&gt;You might not see yourself using the observer class just yet and that is fine, having fair knowledge about it too, is okay.&lt;/p&gt;

&lt;p&gt;Before that, to create an observer class, run:&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;php artisan make:observer &lt;/p&gt;

&lt;p&gt;(replace observerName with the name of the model you are observing).&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;This will create a folder in your application’s app directory called &lt;em&gt;Observers&lt;/em&gt; and store the observer class.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;?php

namespace App\Observers;

class BankObserver
{
    // an empty observer class
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;From here you can populate the classes with methods that match events I listed earlier, it is worthy to note that you can attach a model to an observer when creating the observer, like:&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;php artisan make:observer  -m=&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;This will create the class with some method filled in by default, see below.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;?php

namespace App\Observers;

use App\Task;

class Task
{
_/\*\*  
     \* Handle the task "created" event.  
     \*  
     \*_ **_@param_** _\App\Task $task  
     \*_ **_@return_** _void  
     \*/_ public function created(Task $task)
    {
        //
    }

_/\*\*  
     \* Handle the task "updated" event.  
     \*  
     \*_ **_@param_** _\App\Task $task  
     \*_ **_@return_** _void  
     \*/_ public function updated(Task $task)
    {
        //
    }

_/\*\*  
     \* Handle the task "deleted" event.  
     \*  
     \*_ **_@param_** _\App\Task $task  
     \*_ **_@return_** _void  
     \*/_ public function deleted(Task $task)
    {
        //
    }

_/\*\*  
     \* Handle the task "restored" event.  
     \*  
     \*_ **_@param_** _\App\Task $task  
     \*_ **_@return_** _void  
     \*/_ public function restored(Task $task)
    {
        //
    }

_/\*\*  
     \* Handle the task "force deleted" event.  
     \*  
     \*_ **_@param_** _\App\Task $task  
     \*_ **_@return_** _void  
     \*/_ public function forceDeleted(Task $task)
    {
        //
    }
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;You might be wondering what model action triggers what observer action, I’ll briefly explain the different methods and what triggers them.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Retrieved — This observer method is called when a model record is retrieved from the database.&lt;/li&gt;
&lt;/ul&gt;

&lt;blockquote&gt;
&lt;p&gt;Model::findOrFail($id); //this triggers the retrieved method in the observer class&lt;/p&gt;
&lt;/blockquote&gt;

&lt;ul&gt;
&lt;li&gt;Creating — This observer method is called when a model record is in the process of creation, and not yet stored into the database, this is before the id, and default timestamps are generated for the model, at this point you can dynamically check for and assign a default value to a missing column.&lt;/li&gt;
&lt;li&gt;Created — This observer method is called after a model record is created successfully. If there is an error in the process of creation, say a missing column data, this method doesn’t get called.&lt;/li&gt;
&lt;/ul&gt;

&lt;blockquote&gt;
&lt;p&gt;Model::create([]); //this triggers the creating method first, then created method in the observer class.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;ul&gt;
&lt;li&gt;Updating — This observer method is called when a model record is in the updating process, at this point, the updates has not yet been persisted to the database.&lt;/li&gt;
&lt;li&gt;Updated — This observer method is called after a model record is updated successfully. If there is an error in the process of updating, this method doesn’t get called.&lt;/li&gt;
&lt;/ul&gt;

&lt;blockquote&gt;
&lt;p&gt;Model::update([]); //this triggers the creating method first, then created method in the observer class.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;ul&gt;
&lt;li&gt;Saving and Saved — These model observer methods might seem a bit like a swiss army knife, it gets called before and after any event that requires persistence of data to the database, so if you’re creating a new model record, the saving method runs first, then the creating method, then the created method and finally the saved method, the same routine applies when updating a model, saving, updating, updated, saved.&lt;/li&gt;
&lt;li&gt;Deleting — This observer method is called when a model record is in the deletion process, at this point, the record has not yet been deleted from the database, and using its id to retrieve it from the database will return appropriate data.&lt;/li&gt;
&lt;li&gt;Deleted — This observer method is called after a model record is successfully deleted, at this point, the record has been deleted from the database.&lt;/li&gt;
&lt;/ul&gt;

&lt;blockquote&gt;
&lt;p&gt;Model::destroy($id);&lt;/p&gt;
&lt;/blockquote&gt;

&lt;ul&gt;
&lt;li&gt;Restoring and Restored — These observer methods are called when a deleted model record is restored (using soft deletes implementation)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Important things to note:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;The updating and updated methods only run when the update changes a column of the model in the database, as such, if the update request does not effect a change, the updating and updated observers don’t trigger, only the saving and saved methods get triggered.&lt;/li&gt;
&lt;li&gt;When restoring a deleted record, series of methods gets triggered one after the other, retrieved, restoring, saving, updating, updated, saved, then restored.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;In any case where you want to make a model event without triggering any observer method, you can save it without observer events. An example of a method to use when creating a model without triggering any of the events:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public function saveQuietly(array $options = [])
{
    return static::_withoutEvents_(function () use ($options) {
        return $this-&amp;gt;save($options);
    });
}

Note: This method should be added in the respective model.
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;You can refactor it to suit other model events, as necessary.&lt;/p&gt;

&lt;p&gt;Finally, the last part, binding the observer to a particular model.&lt;/p&gt;

&lt;p&gt;This can be done in the boot method of the AppServiceProvider’s class:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;_/\*\*  
 \* Bootstrap any application services.  
 \*  
 \*_ **_@return_** _void  
 \*/_ public function boot()
{
    Model::_observe_(Observer::class);
}

Model is the model to be observed and observer is the observer class
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;This ends the introduction to Laravel observers, and I hope it was enlightening to you.&lt;/p&gt;




</description>
      <category>softwaredevelopment</category>
      <category>laravel</category>
      <category>softwareengineering</category>
      <category>laraveldevelopment</category>
    </item>
    <item>
      <title>Overriding Laravel’s Default Models Folder using Artisan Command</title>
      <dc:creator>Elisha Ukpong</dc:creator>
      <pubDate>Fri, 17 Jul 2020 12:55:57 +0000</pubDate>
      <link>https://forem.com/drumzminister/overriding-laravel-s-default-models-folder-using-artisan-command-197n</link>
      <guid>https://forem.com/drumzminister/overriding-laravel-s-default-models-folder-using-artisan-command-197n</guid>
      <description>&lt;p&gt;A few weeks ago, the creator of Laravel, Taylor Otwell made a poll asking the framework’s users how they arrange their model files in the app folder.&lt;/p&gt;


&lt;blockquote class="ltag__twitter-tweet"&gt;

  &lt;div class="ltag__twitter-tweet__main"&gt;
    &lt;div class="ltag__twitter-tweet__header"&gt;
      &lt;img class="ltag__twitter-tweet__profile-image" src="https://res.cloudinary.com/practicaldev/image/fetch/s--d82WxQYh--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://pbs.twimg.com/profile_images/914894066072113152/pWD-GUwG_normal.jpg" alt="Taylor Otwell 🏜 profile image"&gt;
      &lt;div class="ltag__twitter-tweet__full-name"&gt;
        Taylor Otwell 🏜
      &lt;/div&gt;
      &lt;div class="ltag__twitter-tweet__username"&gt;
        @taylorotwell
      &lt;/div&gt;
      &lt;div class="ltag__twitter-tweet__twitter-logo"&gt;
        &lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--P4t6ys1m--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://practicaldev-herokuapp-com.freetls.fastly.net/assets/twitter-f95605061196010f91e64806688390eb1a4dbc9e913682e043eb8b1e06ca484f.svg" alt="twitter logo"&gt;
      &lt;/div&gt;
    &lt;/div&gt;
    &lt;div class="ltag__twitter-tweet__body"&gt;
      Spicy Monday poll... don't respond with some "I follow DDD and put them in contextual directories" thing either 💋
    &lt;/div&gt;
    &lt;div class="ltag__twitter-tweet__date"&gt;
      21:05 PM - 29 Jun 2020
    &lt;/div&gt;


    &lt;div class="ltag__twitter-tweet__actions"&gt;
      &lt;a href="https://twitter.com/intent/tweet?in_reply_to=1277709898244141062" class="ltag__twitter-tweet__actions__button"&gt;
        &lt;img src="/assets/twitter-reply-action.svg" alt="Twitter reply action"&gt;
      &lt;/a&gt;
      &lt;a href="https://twitter.com/intent/retweet?tweet_id=1277709898244141062" class="ltag__twitter-tweet__actions__button"&gt;
        &lt;img src="/assets/twitter-retweet-action.svg" alt="Twitter retweet action"&gt;
      &lt;/a&gt;
      68
      &lt;a href="https://twitter.com/intent/like?tweet_id=1277709898244141062" class="ltag__twitter-tweet__actions__button"&gt;
        &lt;img src="/assets/twitter-like-action.svg" alt="Twitter like action"&gt;
      &lt;/a&gt;
      339
    &lt;/div&gt;
  &lt;/div&gt;
&lt;/blockquote&gt;


&lt;p&gt;The framework default stores all models in the app folder directly but most developers and me inclusive would prefer to have a specific models folder to house all models.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--s7MgOmqZ--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/820/1%2AFeKKecKWXvuMRBXZcSRBcw.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--s7MgOmqZ--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/820/1%2AFeKKecKWXvuMRBXZcSRBcw.png" alt=""&gt;&lt;/a&gt;Default Laravel Models arrangement.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--HASc1W3m--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/784/1%2AbvuDOwGl5Cu_7FRVB33SOw.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--HASc1W3m--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/784/1%2AbvuDOwGl5Cu_7FRVB33SOw.png" alt=""&gt;&lt;/a&gt;My way of arranging models.&lt;/p&gt;

&lt;p&gt;Following this method of arranging models comes with a bit of tediousness as the folder name has to be specified as a namespace when creating the model using the artisan command. To create a model the default way, you can run this command below in the terminal:&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;php artisan make:model Bank&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;This command will create a new Bank model class and put the file directly in the app folder.&lt;/p&gt;

&lt;p&gt;To create a model directly into any other folder, for me, the Models folder, this has to be specified when running the command, see below:&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;php artisan make:model Models\Bank&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;While doing this might not look like a big deal any time you want to create a new model, but having more than one developer on the project or creating a lot of models over time, you might tend to forget adding the _Models\_ prefix every time and that will create the model into the default app folder, not what we want.&lt;/p&gt;

&lt;p&gt;To fix this, we can extend the Laravel’s default model creation artisan command and edit the default namespace/folder so we do not have to prepend the namespace/folder name while creating a new model.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Note: The folder name, is the namespace name too.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Firstly, create a new artisan command:&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;php artisan make:command ModelMakeCommand&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;This creates a new command class/file in the app\Console\Commands folder with contents:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;?php

namespace App\Console\Commands;

use Illuminate\Console\Command;

class ModelMakeCommand extends Command
{
_/\*\*  
     \* The name and signature of the console command.  
     \*  
     \*_ **_@var_** _string  
     \*/_ protected $signature = 'command:name';

_/\*\*  
     \* The console command description.  
     \*  
     \*_ **_@var_** _string  
     \*/_ protected $description = 'Command description';

_/\*\*  
     \* Create a new command instance.  
     \*  
     \*_ **_@return_** _void  
     \*/_ public function \_\_construct()
    {
        parent::_\_\_construct_();
    }

_/\*\*  
     \* Execute the console command.  
     \*  
     \*_ **_@return_** _int  
     \*/_ public function handle()
    {
        return 0;
    }
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;Secondly, we will change the class that our ModelMakeClass extends from &lt;em&gt;Illuminate\Console\Command&lt;/em&gt; to &lt;em&gt;Illuminate\Foundation\Console\ModelMakeCommand&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Thirdly, we will empty the ModelMakeClass of its default methods and create a new method called &lt;em&gt;getDefaultNamespace&lt;/em&gt; in the class to handle the task we want it to do (this method overrides the one in the &lt;em&gt;Illuminate\Foundation\Console\ModelMakeCommand we are extending&lt;/em&gt;).&lt;/p&gt;

&lt;p&gt;The ModelMakeClass becomes:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;?php

namespace App\Console\Commands;

use Illuminate\Foundation\Console\ModelMakeCommand as Command;

class ModelMakeCommand extends _Command_  
{

_/\*\*  
     \* Get the default namespace for the class.  
     \*  
     \*_ **_@param_** _string $rootNamespace  
     \*_ **_@return_** _string  
     \*/_ protected function getDefaultNamespace($rootNamespace)
    {
        //logic to change default behaviour
    }

}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;The final thing to add to the new command class we just created is the logic to make our folder the default folder to put model files, in my case the Models folder.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--VtO4YyEB--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/1024/1%2AzS6JkDth1F-bWfJFblLUjQ.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--VtO4YyEB--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/1024/1%2AzS6JkDth1F-bWfJFblLUjQ.png" alt=""&gt;&lt;/a&gt;The two different versions of the getDefaultNamespace methods.&lt;/p&gt;

&lt;p&gt;Our new command class now becomes:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;?php

namespace App\Console\Commands;

use Illuminate\Foundation\Console\ModelMakeCommand as Command;

class ModelMakeCommand extends _Command_  
{
_/\*\*  
     \* Get the default namespace for the class.  
     \*  
     \*_ **_@param_** _string $rootNamespace  
     \*_ **_@return_** _string  
     \*/_ protected function getDefaultNamespace($rootNamespace)
    {
        return "{$rootNamespace}\Models";
    }
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;Finally, running the artisan command to create a new model will put the models in the &lt;em&gt;app\Models&lt;/em&gt; folder by default 🙂.&lt;/p&gt;

&lt;p&gt;TL;DR:&lt;/p&gt;

&lt;p&gt;To change the default model folder in a Laravel app&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Create a new artisan command with name ModelMakeCommand&lt;/li&gt;
&lt;li&gt;Extend the &lt;em&gt;Illuminate\Foundation\Console\ModelMakeCommand&lt;/em&gt; class instead of the &lt;em&gt;Illuminate\Console\Command&lt;/em&gt; class.&lt;/li&gt;
&lt;li&gt;Remove other methods and attributes from the class and then create a new method called &lt;em&gt;getDefaultNamespace&lt;/em&gt; with content:
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;_/\*\*  
     \* Get the default namespace for the class.  
     \*  
     \*_ **_@param_** _string $rootNamespace  
     \*_ **_@return_** _string  
     \*/_ protected function getDefaultNamespace($rootNamespace)
    {
        return "{$rootNamespace}\Models";
    }
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;The full class becomes:
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;?php

namespace App\Console\Commands;

use Illuminate\Foundation\Console\ModelMakeCommand as Command;

class ModelMakeCommand extends _Command_  
{
_/\*\*  
     \* Get the default namespace for the class.  
     \*  
     \*_ **_@param_** _string $rootNamespace  
     \*_ **_@return_** _string  
     \*/_ protected function getDefaultNamespace($rootNamespace)
    {
        return "{$rootNamespace}\Models";
    }
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;Run model creation artisan command and the models will be seen in the app\Models folder.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Thanks&lt;/p&gt;

</description>
      <category>laravel</category>
      <category>laraveldevelopment</category>
      <category>laravelframework</category>
    </item>
    <item>
      <title>One Laravel Form Request Class, Multiple HTTP Methods</title>
      <dc:creator>Elisha Ukpong</dc:creator>
      <pubDate>Thu, 16 Jul 2020 23:36:38 +0000</pubDate>
      <link>https://forem.com/drumzminister/one-laravel-form-request-class-multiple-http-methods-3i3p</link>
      <guid>https://forem.com/drumzminister/one-laravel-form-request-class-multiple-http-methods-3i3p</guid>
      <description>&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--c2sbPQCq--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/1024/1%2AC5XhH_g5pyHjKzRJjGg-9g.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--c2sbPQCq--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/1024/1%2AC5XhH_g5pyHjKzRJjGg-9g.png" alt="Laravel Default Form Request Class"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Laravel comes with request validations out of the box and this makes it a whole lot easier to validate user inputs when receiving form submissions. In this short post, I will be explaining the form request class, its default methods, and how to utilize this form request to match more than one HTTP method.&lt;/p&gt;

&lt;p&gt;Just to point out, Laravel also has a validation factory (Illuminate\Validation\Factory) class, which in my opinion, is more often used by developers than the form request class.&lt;/p&gt;

&lt;p&gt;The validation factory class seems to be the default validation method Laravel ships out with the controller and this validation factory can be accessed in the controller without any user setup via:&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;$this-&amp;gt;validate($request,$rules,$messages,$customAttributes).&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--ji0lxGwc--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/1024/1%2AhKs-p3BJhbW06UdgLncuxQ.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--ji0lxGwc--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/1024/1%2AhKs-p3BJhbW06UdgLncuxQ.png" alt=""&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The $messages and $customAttributes arrays are optional and the function can be called without them, like this:&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;$this-&amp;gt;validate($request, $rules).&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;This method works pretty fine but when the validation logic grows, it is often advised to move it to its own class, hence the Form Request Class.&lt;/p&gt;

&lt;p&gt;The form request class can be created using Laravel’s artisan command:&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;php artisan make:request RequestClassName&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;This command will create a Requests folder in the app\Http directory of your Laravel application and create a FormRequest Class, using the class name you passed when creating the FormRequest Class, in our case requestClassName.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--xeT1XWTm--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/572/1%2Ab-jShBe7idGr5pZIbR60Pw.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--xeT1XWTm--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/572/1%2Ab-jShBe7idGr5pZIbR60Pw.png" alt=""&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;To briefly explain the content of the FormRequest class, the class comes with two methods: authorize and rules.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class CreateNewRequest extends FormRequest
{
_/\*\*  
     \* Determine if the user is authorized to make this request.  
     \*  
     \*_ **_@return_** _bool  
     \*/_ public function authorize()
    {
        return false;
    }

_/\*\*  
     \* Get the validation rules that apply to the request.  
     \*  
     \*_ **_@return_** _array  
     \*/_ public function rules()
    {
        return [
            //
        ];
    }
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;The authorize method checks if a user is authorized to make a request, so an example use case here can be a blogging system where only a post creator can edit his/her post. Assuming the blog post has a column user_id that tracks which user made the post, the authorize function can look like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;_/\*\*  
 \* Determine if the user is authorized to make this request.  
 \*  
 \*_ **_@return_** _bool  
 \*/_ public function authorize()
{
   return $blogPost-&amp;gt;user\_id === auth()-&amp;gt;id();
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;So this returns true and then moves to process the edit request only when the blog post edit request is made by the blog post owner, else it will return false and throw an exception back to the user, moving to the next method.&lt;/p&gt;

&lt;p&gt;The rules method contains the validation logic of any form that utilizes the FormRequest class.&lt;/p&gt;

&lt;p&gt;The FormRequest class can be injected into any method in which you want the FormRequest validation logic to hold true, and this cleans up your controller.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--oSN6eN_K--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/1024/1%2AJGOPDQaYTcu03EksO9S0Tw.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--oSN6eN_K--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/1024/1%2AJGOPDQaYTcu03EksO9S0Tw.png" alt=""&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Having explained the concepts surrounding the readily available validate method and the user-created form request class, let me move to the main problem that this post aims to shed light on.&lt;/p&gt;

&lt;p&gt;Ideally, creating and updating a model’s record might require differing validations for the model’s column, to make an example, let us continue using the blog analogy.&lt;/p&gt;

&lt;p&gt;To create a blog, we might decide that an image is required, the blog post name is required, same as the blog post content, but on updating the post, the blog post image would necessarily not be required, it becomes an optional validation.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;_/\*\*  
 \* Get the validation rules that apply to the request.  
 \*  
 \*_ **_@return_** _array  
 \*/_ public function rules()
{
    //blog post creation rules

    return [
        'name' =&amp;gt; 'string | required',
        'content' =&amp;gt; 'string | required',
        'image' =&amp;gt; 'image | required'
    ];
}

_/\*\*  
 \* Get the validation rules that apply to the request.  
 \*  
 \*_ **_@return_** _array  
 \*/_ public function rules()
{
    //blog post update rules

    return [
        'name' =&amp;gt; 'string | required',
        'content' =&amp;gt; 'string | required',
        'image' =&amp;gt; 'image'
    ];
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;The above two rules are different and if I want to stick to the Form Request class way of validation I might have to make more form requests classes should I have differing validation logic for POST, PUT, PATCH and DELETE. To solve this with only one form class, it is possible to edit the form request to make it more versatile such that it serves different rules for different HTTP verbs. See code sample below:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;protected $rules = [

];

_/\*\*  
 \* Get the validation rules that apply to the request.  
 \*  
 \*_ **_@return_** _array  
 \*/_ public function rules()
{
    $method = $this-&amp;gt;method();
    if (null !== $this-&amp;gt;get('\_method', null)) {
        $method = $this-&amp;gt;get('\_method');
    }
    $this-&amp;gt;offsetUnset('\_method');
    switch ($method) {
        case 'DELETE':
        case 'GET':
                $this-&amp;gt;rules = [];
            break;

        case 'POST':

            break;
        // in case of edit
        case 'PUT':
        case 'PATCH':

            break;
        default:
            break;
    }

    return $this-&amp;gt;rules;
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;Explanation:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$method = $this-&amp;gt;method();
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;The code snippet above retrieves the HTTP method from the request object and stores it to a variable, $method, next.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;if (null !== $this-&amp;gt;get('\_method', null)) {
        $method = $this-&amp;gt;get('\_method');
    }
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;Knowing that Laravel has a way of masking or changing the original request method using the @method() directive, the code tests to see if a method is specified in the request object, if it is, then it updates the method variable with it.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$this-&amp;gt;offsetUnset('\_method');
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;This removes the “_method” attribute from the request object, and as such we have realized the type of HTTP request that is been sent to our application and can then serve differing rules for each request type.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;switch ($method) {
        case 'DELETE':
                $this-&amp;gt;rules = [//rules here for delete request];
            break;

        case 'GET':
                $this-&amp;gt;rules = [//rules here for get request];
            break;

        case 'POST':
               $this-&amp;gt;rules = [//rules here for post request];
            break;

        case 'PUT':
               $this-&amp;gt;rules = [//rules here for put request];
            break;   

        case 'PATCH':
               $this-&amp;gt;rules = [//rules here for patch request];
            break;

        default:
            break;
    }

    return $this-&amp;gt;rules;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;The above switch statement updates the rules array with appropriate validation logic for each request type and helps you have them all in one request class.&lt;/p&gt;

&lt;p&gt;Thank you for reading until the end 🙂&lt;/p&gt;

</description>
      <category>laravel</category>
      <category>laraveldevelopment</category>
      <category>laravelframework</category>
      <category>phpdevelopers</category>
    </item>
  </channel>
</rss>
