AppDividend
Latest Code Tutorials

Laravel 8 Route Macros Step by Step Example

0

You can assign a group of routes that uses a namespace like App\Http\Controllers\Admin. And you can create a namespace using the fluent routing API.

As we have discussed in Custom Namespace in Laravel, The namespace is defined as a class of elements in which each element has a unique name to the associated class. See the following syntax of Laravel custom namespace.

Route::namespace('Admin')->group(function () {
    // Controllers Within The "App\Http\Controllers\Admin" Namespace
});

Laravel 8 Route Macros

Macros are techniques to build little pieces of reusable logic that we can create and load anywhere in Laravel. You can create as many macros as you want for just about anything in Laravel.

The router in Laravel is macroable, which means if you have a group of routes that you need to provide via reusable groups of route definitions or package, you can define the macro in a service provider.

Let’s check out one by one steps to create and use Route Macros in Laravel.

Step 1: Create fake data using faker

For this example, we will use the Faker library to create fake data. Faker is the PHP library that generates fake data for you. You can find the faker documentation here.

After installing fresh Laravel 8, create a model called Website.php.

php artisan make:model Website -m

It will create a Website.php model and migration.

Add the following schema to the create_websites_table.php file.

public function up()
{
        Schema::create('websites', function (Blueprint $table) {
            $table->id();
            $table->string('safeEmail');
            $table->string('domainName');
            $table->string('url');
            $table->string('ipv6');
            $table->timestamps();
        });
}

Now, migrate using the following command.

php artisan migrate

Okay, so now the table is created in the database. Let’s create a model factory.

Step 2: Create a Model Factory in Laravel 8

With the model factories, you can use them to build out “dummy” models, which can be used for both seed data and testing. To create a model factory in Laravel, type the following command.

php artisan make:factory WebsiteFactory

It will create a WebsiteFactory.php file inside the database >> factories >> WebsiteFactory.php file.

In Laravel 8, by default, the WebsiteFactory.php file looks like below.

<?php

// WebsiteFactory.php

namespace Database\Factories;

use App\Models\Website;
use Illuminate\Database\Eloquent\Factories\Factory;

class WebsiteFactory extends Factory
{
    /**
     * The name of the factory's corresponding model.
     *
     * @var string
     */
    protected $model = Website::class;

    /**
     * Define the model's default state.
     *
     * @return array
     */
    public function definition()
    {
        return [ ];
    }
}

In the previous version, there was no definition() function. In this version, there is, and it returns an empty array. In this array, we need to define the faker fields which needed to be filled in the database.

Write the following code inside the definition() method.

// WebsiteFactory.php

public function definition()
{
        $faker = $this->faker;
            return [
                'safeEmail' => $faker->safeEmail,
                'domainName' => $faker->domainName,
                'url' => $faker->url,
                'ipv6' => $faker->ipv6
            ];
}

Step 3: Database seeding

The next step is to create a table seeder. So type the following command to generate a table seeder for the websites table.

php artisan make: seeder WebsiteTableSeeder

If you check out that file, then you will see that it contains one function called run(). First, import the Website.php model.

<?php

// WebsiteTableSeeder.php

namespace Database\Seeders;

use Illuminate\Database\Seeder;
use App\Models\Website;

Write the following code inside that run() method.

// WebsiteTableSeeder.php

public function run()
{
        Website::factory()->count(100)->create(); 
}

It will create 100 rows with fake data. The final step to seed the database is to run the seeder file.

So write the code inside the DatabaseSeeder.php file, that will call the WebsiteTableSeeder. This will seed the fake values in the database.

<?php

// DatabaseSeeder.php

namespace Database\Seeders;

use Illuminate\Database\Seeder;

class DatabaseSeeder extends Seeder
{
    /**
     * Seed the application's database.
     *
     * @return void
     */
    public function run()
    {
        $this->call(WebsiteTableSeeder::class);
    }
}

Go to the command line and type the following commands one by one.

composer dump-autoload
php artisan db:seed

That is it. If you check the database and websites table, you will see the 100 rows with fake data. This is how you can add as many fake data as possible to the database in Laravel.

Now, let’s get to our main topic. Create a RouteMacroServiceProvider.

Step 4: Create a ServiceProvider

We first need to create a Service Provider to create a macro.

To create a ServiceProvider in Laravel, type the following command.

php artisan make:provider RouteMacroServiceProvider

Go to the app >> Providers folder, and you will see the new file called RouteMacroServiceProvider file.

Inside that file, there is one function called boot(). Add the following code inside the boot() method.

// RouteMacroServiceProvider.php

public function boot()
{
        Response::macro('jDomainName', function($model) {
            return Response::json([$model->domainName]);
        });
}

As you know, our table contains the domainName column. So we will fetch all the domainName in the json array using routing macro based on the id.

Now, register the service provider in Laravel inside the app >> config >> app.php file.

Append the RouteMacroServiceProvider inside the providers array.

'providers' => [
...
...
...
 App\Providers\RouteMacroServiceProvider::class,

The last step is to define the route that returns jDomainName() macro.

Add the following code inside the routes >> web.php file.

// web.php

Route::get('/websites/{website}/domainname', function(\App\Models\Website $website) {
    return response()->jDomainName($website);
});

As you can see that now, we can use jDomainName() macro anywhere in the Laravel project without any import because we have registered a service provider that will boot when we run the application.

Here, we have used Laravel’s explicit model binding in which you need to pass any property of the model instance, and it will fetch the domain name based on the property. 

In our case, it is the model object’s property id. So we are fetching the domain name based on the id. It binds website parameter to website model instance.

Now, go to the browser and type the following URL.

https://laravel8crud.test/websites/2/domainname

or

http://localhost:8000/websites/2/domainname

You will see this kind of output.

 

Laravel macros

That is how you can create a macro and use the macro in Laravel.

Finally, the Laravel 8 route macros example is over.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.