Laravel 9 Concept of Route Model Binding with Example

Reading Time: 7 minutes
4,321 Views

Laravel route model binding provides a convenient way to automatically inject the model instances directly into application routes. Article contains classified information about the concept of Laravel route model binding.

For example, instead of injecting a user’s ID, you can inject the entire User model instance that matches the given ID. We will see the entire concept of binding model with routes in this Laravel v9 tutorial.

Inside this article we will see Laravel 9 Concept of Route Model Binding step by step.

Learn More –

Let’s get started.

Laravel Installation

Open terminal and run this command to create a laravel project.

composer create-project laravel/laravel myblog

It will create a project folder with name myblog inside your local system.

To start the development server of laravel –

php artisan serve

URL: http://127.0.0.1:8000

Assuming laravel already installed inside your system.

Create Database & Connect

To create a database, either we can create via Manual tool of PhpMyadmin or by means of a mysql command.

CREATE DATABASE laravel_app;

To connect database with application, Open .env file from application root. Search for DB_ and update your details.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel_app
DB_USERNAME=root
DB_PASSWORD=root

Create Migration

We will create a students table using migration and then we seed test data inside it.

Open project into terminal and run this command to create migration file.

$ php artisan make:migration create_students_table

It will create 2022_04_17_031027_create_students_table.php file inside /database/migrations folder. Open migration file and write this following code into it.

The code is all about for the schema of students table.

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('students', function (Blueprint $table) {
            $table->id();
            $table->string("name", 120);
            $table->string("email", 50)->nullable();
            $table->string("mobile", 50)->nullable();
            $table->integer("age");
            $table->enum("gender", ["male", "female", "others"]);
            $table->text("address_info");
            $table->timestamp("created_at")->useCurrent();
            $table->timestamp("updated_at")->useCurrent();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('students');
    }
};

Run Migration

Back to terminal and run this command.

$ php artisan migrate

It will create students table inside database.

Create Model

Back to project terminal and run this command to create model.

$ php artisan make:model Student

It will create Student.php file inside /app/Models folder. This file will help when we generate data using factory and insert into table.

Create Data Factory

Next,

Copy this command and run into terminal to create a factory file.

$ php artisan make:factory StudentFactory

It will create a file StudentFactory.php inside /database/factories folder. Open file and write this following code into it.

<?php

namespace Database\Factories;

use Illuminate\Database\Eloquent\Factories\Factory;

/**
 * @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\Student>
 */
class StudentFactory extends Factory
{
    /**
     * Define the model's default state.
     *
     * @return array<string, mixed>
     */
    public function definition()
    {
        return [
            "name" => $this->faker->name(),
            "email" => $this->faker->safeEmail,
            "mobile" => $this->faker->phoneNumber,
            "age" => $this->faker->numberBetween(25, 45),
            "gender" => $this->faker->randomElement([
                "male",
                "female",
                "others"
            ]),
            "address_info" => $this->faker->address
        ];
    }
}

Call Model Factory

Open DatabaseSeeder.php from /database/seeders folder. Load model and factory.

<?php

namespace Database\Seeders;

use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;

class DatabaseSeeder extends Seeder
{
    /**
     * Seed the application's database.
     *
     * @return void
     */
    public function run()
    {
         \App\Models\Student::factory(100)->create();
    }
}

Concept

\App\Models\Student::factory(100)->create();

It will generate 100 fake rows of student using StudentFactory.php file and save into students table.

Run Data Seeder

Back to project terminal and run this command to run factory to seed fake data.

$ php artisan db:seed

It will generate and save fake data into students table.

Add Routes

Open web.php file from /routes folder. Add these routes into it.

//...

use App\Http\Controllers\StudentController;

// Route Model binding
Route::get("student/{student}", [StudentController::class, "index"]);
// Route Model binding
Route::get("student-by-email/{student:email}", [StudentController::class, "infoByEmail"]);

Create Controller

Open project into terminal and run this command into it.

$ php artisan make:controller StudentController

It will create StudentController.php file inside /app/Http/Controllers folder. Open controller file and write this code into it.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Student;

class StudentController extends Controller
{
    public function index(Student $student) // Model
    {
        // Student data will be returned by student id getting from URL
        return $student; // returns complete object
    }

    public function infoByEmail(Student $student) // Model
    {
        // Student data will be returned by student's email passing from URL
        return $student; // returns complete object
    }
}

Since the $student variable is type-hinted as the App\Models\Student Eloquent model and the variable name matches the {student} URI segment, Laravel will automatically inject the model instance that has an ID matching the corresponding value from the request URI.

If matching model instance is not found in the database, a 404 HTTP response will automatically be generated.

To get single value from object write $student->name etc.

Application Testing

Run this command into project terminal to start development server,

php artisan serve

Example Routes:

  • URL #1 – http://127.0.0.1:8000/student/2 [ Student by ID ]
  • URL #2 – http://127.0.0.1:8000/student-by-email/sanjay@gmail.com [ Student by Email address ]

We hope this article helped you to learn about Laravel 9 Concept of Route Model Binding in a very detailed way.

Online Web Tutor invites you to try Skillshike! Learn CakePHP, Laravel, CodeIgniter, Node Js, MySQL, Authentication, RESTful Web Services, etc into a depth level. Master the Coding Skills to Become an Expert in PHP Web Development. So, Search your favourite course and enroll now.

If you liked this article, then please subscribe to our YouTube Channel for PHP & it’s framework, WordPress, Node Js video tutorials. You can also find us on Twitter and Facebook.