Laravel route model binding provides a convenient way to automatically inject the model instances directly into application routes.
For example, instead of injecting a user’s ID, you can inject the entire User
model instance that matches the given ID.
Inside this article we will see the concept of Route model binding in laravel 8 step by step.
Let’s get started.
Laravel Installation
We will create laravel project using composer. So, please make sure your system should have composer installed. If not, may be this article will help you to Install composer in system.
Here is the command to create a laravel project-
composer create-project --prefer-dist laravel/laravel blog
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
To create a table in database, we will use migration command of laravel artisan to create schema. Open project into terminal and run this artisan command.
$ php artisan make:migration CreateProductsTable
It will create a migration file with name 2021_03_18_182916_create_products_table.php according to my timestamp values at location /database/migrations.
Open migration file 2021_03_18_182916_create_products_table.php and write this code into it.
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateProductsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('products', function (Blueprint $table) { $table->id(); $table->string("name", 70); $table->string("slug", 100); $table->text("description"); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('products'); } }
Migrate Migration
To run migration file and create table.
$ php artisan migrate
This command will create database table.
Create Model
To create model, run this artisan command.
$ php artisan make:model Product
It will create a file with name Product.php at location /app/Models.
Open Product.php and write this code.
<?php namespace App\Models; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; class Product extends Model { use HasFactory; public $timestamps = false; }
Create Factory File – Data Seed
To seed dummy data into table, we need a factory file. To create factory file we will use artisan command. Back to terminal and run this artisan command.
$ php artisan make:factory ProductFactory --model=Product
It will create a file with name ProductFactory.php at location /database/factories.
Open ProductFactory.php and write this code into it.
<?php namespace Database\Factories; use App\Models\Product; use Illuminate\Database\Eloquent\Factories\Factory; use Illuminate\Support\Str; class ProductFactory extends Factory { /** * The name of the factory's corresponding model. * * @var string */ protected $model = Product::class; /** * Define the model's default state. * * @return array */ public function definition() { return [ 'name' => $this->faker->name, 'slug' => Str::slug($this->faker->name), 'description' => $this->faker->text, ]; } }
Run Factory File
To run this factory which results, it creates dummy data into database table. We will run this factory file by Tinker Shell panel
$ php artisan tinker
It will open a shell interface, by the help of which we will interact with database.
>>> App\Models\Product::factory()->count(100)->create()
Above commands will create 100 dummy rows for Product table.
Create Routes
Open web.php from /routes folder.
// At header use App\Http\Controllers\ProductController; // Route Model binding Route::get("product/{product}", [ProductController::class, "index"]); // Route Model binding Route::get("product-by-slug/{product:slug}", [ProductController::class, "infoBySlug"]);
Create Controller
To create controller, run this artisan command.
$ php artisan make:controller ProductController
It will create a file with name ProductController.php at /app/Http/Controllers folder.
Open ProductController.php and write this code into it.
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Models\Product; class ProductController extends Controller { public function index(Product $product) // Model { // Product data will be returned by product id getting from URL return $product; // returns complete object } public function infoBySlug(Product $product) // Model { // Product data will be returned by product slug passing from URL return $product; // returns complete object } }
Since the $product
variable is type-hinted as the App\Models\Product
Eloquent model and the variable name matches the {product}
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 $product->name etc.
Application Testing
Run this command into project terminal to start development server,
php artisan serve
URL #1 – http://127.0.0.1:8000/product/2
#Output { "id": 2, "name": "Arianna Klocko", "slug": "cordie-larson", "description": "Sample product data" }
URL #2 – http://127.0.0.1:8000/product-by-slug/cordie-larson
#Output { "id": 2, "name": "Arianna Klocko", "slug": "cordie-larson", "description": "Sample product data" }
We hope this article helped you to learn about Concept of Route Model Binding in Laravel 8 in a very detailed way.
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.