Laravel 8 Route Macros

Laravel 8 Route Macros

Using Route Macros in Laravel

In Laravel, route macros are a powerful way to define reusable logic for your routes. You can define a custom macro for routes to use across your application. Macros allow you to create reusable blocks of logic, reducing duplication in your code.

1. Creating a Custom Namespace for Routes

You can assign a group of routes that use a specific namespace like App\Http\Controllers\Admin. This is useful for organizing controllers in your application. The syntax for defining a custom namespace using Laravel's fluent routing API is:

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

2. Laravel 8 Route Macros

Laravel's router is macroable, which means you can define custom macros for routing logic. This enables you to create reusable route definitions or packages.

Step-by-Step Process for Creating and Using Route Macros

Step 1: Creating Fake Data Using Faker

Faker is a PHP library used for generating fake data. Laravel 8 includes Faker out-of-the-box, and you can use it to generate fake data for your models.

  • First, create a model using the following command:

php artisan make:model Website -m

This will generate a Website.php model and a migration file.

  • Add the following schema to the create_websites_table.php migration 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, run the migration:

php artisan migrate

Step 2: Create a Model Factory in Laravel 8

Model factories allow you to easily generate fake data for testing and seeding. In Laravel 8, the factory class now includes a definition() method for generating fake data.

To create a factory for the Website model, run:

php artisan make:factory WebsiteFactory

This will create the WebsiteFactory.php file inside database/factories/. The default content will look like this:

// WebsiteFactory.php namespace Database\Factories; use App\Models\Website; use Illuminate\Database\Eloquent\Factories\Factory; class WebsiteFactory extends Factory { protected $model = Website::class; public function definition() { return []; } }

Inside the definition() method, use Faker to generate fake data:

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

Step 3: Database Seeding

Next, create a seeder to populate the database with fake data. Run the following command to generate a seeder:

php artisan make:seeder WebsiteTableSeeder

In the WebsiteTableSeeder.php file, import the Website model and add the logic to create fake data:

// WebsiteTableSeeder.php namespace Database\Seeders; use Illuminate\Database\Seeder; use App\Models\Website; class WebsiteTableSeeder extends Seeder { public function run() { Website::factory()->count(100)->create(); } }

In DatabaseSeeder.php, call the WebsiteTableSeeder:

// DatabaseSeeder.php namespace Database\Seeders; use Illuminate\Database\Seeder; class DatabaseSeeder extends Seeder { public function run() { $this->call(WebsiteTableSeeder::class); } }

Finally, run the following commands to seed the database:

composer dump-autoload php artisan db:seed

This will insert 100 rows of fake data into the websites table.

Step 4: Create a Route Macro ServiceProvider

Now, let's create a custom route macro. We will define a route that returns the domainName from a Website model.

First, create a new service provider:

php artisan make:provider RouteMacroServiceProvider

In the RouteMacroServiceProvider.php file, define a macro that returns a domainName:

// RouteMacroServiceProvider.php namespace App\Providers; use Illuminate\Support\ServiceProvider; use Illuminate\Support\Facades\Response; class RouteMacroServiceProvider extends ServiceProvider { public function boot() { Response::macro('jDomainName', function ($model) { return Response::json([$model->domainName]); }); } public function register() { // } }

This defines a macro jDomainName() that will return the domainName of a given Website model in a JSON response.

Now, register the service provider in config/app.php:

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

Step 5: Define the Route

Next, define a route in routes/web.php that will use the jDomainName() macro:

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

This route will automatically use the jDomainName() macro to return the domainName of a website.

Step 6: Test the Route

Finally, open your browser and navigate to:

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

or

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

You should see a JSON response like this:

{ "domainName": "example.com" }

Conclusion

In this guide, we learned how to:

  1. Use custom namespaces for organizing controllers in Laravel.

  2. Create and use route macros in Laravel 8 to define reusable logic.

  3. Generate fake data using Faker for seeding your database.

  4. Define a route macro in a service provider to return custom JSON responses.

Soeng Souy

Soeng Souy

Website that learns and reads, PHP, Framework Laravel, How to and download Admin template sample source code free.

Post a Comment

CAN FEEDBACK
close