Archive

Posts Tagged ‘Laravel 9’

Laravel Events

January 23, 2023 Leave a comment

Laravel events are a powerful tool for decoupling different parts of your application and allowing for more modular and maintainable code. In this blog post, we’ll take a closer look at what events are, how they work, and how you can use them in your Laravel projects.

What are Laravel Events?

An event in Laravel is simply a way to perform an action or trigger some logic in your application when a certain condition is met. For example, you might want to send an email to a user when they register for your website, or log a message to the database when a user completes a purchase. Events allow you to separate this type of logic from the rest of your application, making it easier to maintain and test.

Laravel includes a number of built-in events, such as:

The Event class, which is the base class for all events in Laravel.
The Event facade, which provides a simple way to raise and handle events.
The Event service provider, which is responsible for registering event listeners and subscribers.
There are two types of events in Laravel:

Simple Events: These are basic events that are triggered using the event() helper function or the Event facade. They can be handled by a single listener or multiple listeners.

Advanced Events: These are events that can be queued and dispatched using Laravel’s built-in queue worker. They can also be handled by multiple listeners, and you can use the Event class to create advanced events.

How do Laravel Events Work?

Laravel events work by using a “publisher-subscriber” model. When a certain event is fired, it is “published” to any listeners that are registered to listen for that event. The listeners then “subscribe” to the event and perform some action when it is fired.

For example, let’s say you want to send a welcome email to a user when they register for your website. You would create an event class that represents the user being registered, and a listener class that sends the welcome email. When a user is registered, the event is fired and the listener is called, sending the welcome email to the user.

Creating and Firing Events

To create a new event in Laravel, you simply create a new class that extends the base Event class and contains any relevant data that needs to be passed to the listener(s). Then, in the appropriate place in your application (such as a controller or model), you can fire the event using the event() helper function or the Event facade.

Here is an example of how events can be used in Laravel:

Let’s say you have a “User” model in your application and you want to perform some action every time a user is created.

First, you would create a new event class that represents the user being created. This class should extend the base Event class and contain any relevant data that needs to be passed to the listener(s).

class UserCreated extends Event
{
    public $user;

    public function __construct(User $user)
    {
        $this->user = $user;
    }
}

Next, you would create a listener class that will handle the event. This class should implement the Listener interface and define a handle method that will be called when the event is fired.

class SendWelcomeEmail implements Listener
{
    public function handle(UserCreated $event)
    {
        // Send a welcome email to the user
        Mail::to($event->user->email)->send(new WelcomeEmail);
    }
}

In the User model, you can fire the event when the user is created:

class User extends Model
{
    protected $dispatchesEvents = [
        'created' => UserCreated::class,
    ];
}

Finally, you would register the listener in the EventServiceProvider:

protected $listen = [
    UserCreated::class => [
        SendWelcomeEmail::class,
    ],
];

Now, every time a new user is created, the UserCreated event will be fired and the SendWelcomeEmail listener will be called, sending a welcome email to the user.

This way you can make your code more modular and clean, you can create multiple events for multiple actions, and you can create multiple listeners for each event.

If you’re new to using events in Laravel, we recommend starting with a simple example like the one we discussed in this post, and then experimenting with different events and listeners in your own projects. With a little practice, you’ll soon find that events can be a valuable tool for making your Laravel code cleaner and more maintainable.

Laravel Blade Templates: An Introduction to Laravel’s Templating Engine

January 22, 2023 Leave a comment

Laravel is a powerful PHP web application framework that provides developers with a wide range of tools and features to help them build robust and high-performing web applications. One of the most important features in Laravel is its templating engine, known as Blade.

Blade is a simple yet powerful templating engine that allows developers to create and reuse template files for their views. It provides a clean and elegant syntax for creating templates and eliminates the need for complex PHP code in views. This makes it easy to separate the concerns of the application and keep the view files clean and organized.

One of the key features of Blade is its use of template inheritance. With template inheritance, you can create a layout template that contains the common elements of your site, such as the header and footer, and then extend this template in your other views. This allows you to change the layout of your entire site by modifying just one file.

Blade also supports template sections, which allow you to define reusable sections of a template that can be overridden in child templates. This is useful for creating reusable components, such as sidebars and modals, that can be easily customized for different pages.

In addition to these features, Blade also supports template directives, which are special tags that can be used to control the flow of a template. These directives include @if, @else, @foreach, @while, and many more. These directives make it easy to add logic to your views and keep the code clean and organized.

Laravel’s Blade templating engine is a powerful tool that makes it easy to create and maintain complex views. With its clean syntax, template inheritance, sections, and directives, Blade makes it easy to separate the concerns of the application and keep the code organized and maintainable.

In summary, Blade is a templating engine that allows you to create views in a clean and elegant way by providing you with a simple and easy to use syntax. With Blade, you can use template inheritance, sections, and directives, making it easy to create reusable, maintainable and robust views.

Here’s an example of how you can use Blade templates in a Laravel 9 application:

Let’s say you have a home controller with an index method that returns a view.

class HomeController extends Controller
{
    public function index()
    {
        return view('home');
    }
}

In your resources/views folder, you would create a file called home.blade.php which would contain the HTML for your home page.

<!DOCTYPE html>
<html>
<head>
    <title>Home Page</title>
</head>
<body>
    <h1>Welcome to our website!</h1>
    <p>Here's some content on the home page.</p>
</body>
</html>

Now, when a user visits the home page of your application, they will see the content of the home.blade.php file.

You can also use template inheritance in Blade. For example, you can create a layouts folder in your resources/views folder, and create a file called app.blade.php. This file can contain the common elements of your site, such as the header and footer.

<!DOCTYPE html>
<html>
<head>
    <title>@yield('title')</title>
</head>
<body>
    <header>
        <nav>
            <a href="#">Home</a>
            <a href="#">About</a>
            <a href="#">Contact</a>
        </nav>
    </header>
    <main>
        @yield('content')
    </main>
    <footer>
        <p>Copyright © {{ date('Y') }}</p>
    </footer>
</body>
</html>

In your home.blade.php you can use @extends(‘layouts.app’) to extend the common layout and @section to define the unique content.

@extends('layouts.app')

@section('title', 'Home Page')

@section('content')
    <h1>Welcome to our website!</h1>
    <p>Here's some content on the home page.</p>
@endsection

Now, when a user visits the home page of your application, they will see the common elements from the app.blade.php and the unique content from home.blade.php.

These are just a few examples of how you can use Blade templates in a Laravel application.

Laravel 9 Create Custom Artisan Command

January 7, 2023 Leave a comment

Artisan is the command-line interface that is included with Laravel. It is driven by the Symfony Support component.

Today we will learn how to create a custom artisan command in the Laravel application and how to use the custom laravel artisan command.

Following command will generate a file under ‘app\Console\Commands\’ with name CreateUsers.php

php artisan make:command CreateUsers

Here is the file code

<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;

class CreateUsers 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';

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $numberOfUsers = $this->argument('count');
  
        for ($i = 0; $i < $numberOfUsers; $i++) { 
            User::factory()->create();
        }  
        return Command::SUCCESS;
    }
}
?>

The handle() function holds the logic to insert the records in the database.

Let’s run our custom command to create 3 users

php artisan create:users 3

You can also view list of commands with following command.

php artisan list