article

Friday, May 13, 2022

Laravel Join Two Tables

Laravel Join Two Tables

How to install laravel 9

https://tutorial101.blogspot.com/2022/02/how-to-install-laravel-9.html

Connecting our Database

open .env file root directory. 

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel
DB_USERNAME=root
DB_PASSWORD=
Create tables
php artisan make:migration create_categories_table
php artisan make:migration create_products_table
C:\xampp\htdocs\laravel9\blog>php artisan make:migration create_categories_table
C:\xampp\htdocs\laravel9\blog>php artisan make:migration create_products_table

Open new products and categories migrations
yourproject/database/migrations
blog\database\migrations\_create_products_table.php
edit code blog\database\migrations\_create_products_table.php
products_table.php
//products_table.php
<?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('products', function (Blueprint $table) {
            $table->id();
            $table->string('prodname');
            $table->integer('category_id');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('products');
    }
};
categories_table.php
//categories_table.php
<?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('categories', function (Blueprint $table) {
            $table->id();
            $table->string('catname');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('categories');
    }
};
Database Migration
php artisan migrate

C:\xampp\htdocs\laravel9\blog>php artisan migrate
Migration table created successfully.
check database table

CREATE TABLE `products` (
`id` bigint(20) UNSIGNED NOT NULL,
`prodname` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`category_id` int(11) NOT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

INSERT INTO `products` (`id`, `prodname`, `category_id`, `created_at`, `updated_at`) VALUES
(1, 'Milk', 1, '2022-05-13 07:43:06', '2022-05-13 07:43:06'),
(2, 'Coffee', 1, '2022-05-13 07:43:06', '2022-05-13 07:43:06'),
(3, 'Iphone 13', 2, '2022-05-13 07:43:58', '2022-05-13 07:43:58'),
(4, 'Samsung Galaxy', 2, '2022-05-13 07:43:58', '2022-05-13 07:43:58');

CREATE TABLE `categories` (
`id` bigint(20) UNSIGNED NOT NULL,
`catname` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

INSERT INTO `categories` (`id`, `catname`, `created_at`, `updated_at`) VALUES
(1, 'Drink', '2022-05-13 07:42:02', '2022-05-13 07:42:02'),
(2, 'Mobiles', '2022-05-13 07:42:02', '2022-05-13 07:42:02');
Creating Controller

php artisan make:controller ProductController --resource
C:\xampp\htdocs\laravel9\blog>php artisan make:controller ProductController --resource
change it with the following codes:
blog\app\Http\Controllers\ProductController.php
//blog\app\Http\Controllers\ProductController.php
<?php
namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Category;
use App\Models\Product;

class ProductController extends Controller
{
    public function index()
    {
        $products = Product::with('category')->get();
        $categories = Category::with('products')->get();
        
        return view('index', compact('products', 'categories'));
    }
}
Create Model

Model is used to get the data from the database.

php artisan make:model Product
php artisan make:model Category

C:\xampp\htdocs\laravel9\blog>php artisan make:model Product
C:\xampp\htdocs\laravel9\blog>php artisan make:model Category

blog\app\Models\Category.php and blog\app\Models\Product.php

blog\app\Models\Category.php
//blog\app\Models\Category.php
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use App\Models\Product;

class Category extends Model
{
    use HasFactory;
    protected $fillable = [
        'id',
        'catname',
    ];
 
    public function products()
    {
        return $this->hasMany(Product::class, 'category_id', 'id');
    }
}
blog\app\Models\Product.php
//blog\app\Models\Product.php
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use App\Models\Category;

class Product extends Model
{
    use HasFactory;
    protected $fillable = [
        'id',
        'prodname',
        'category_id',
    ];
 
    public function category()
    {
        return $this->belongsTo(Category::class);
    }
}
Create Views

Bootstrap 5 https://getbootstrap.com/docs/5.1/getting-started/download/
blog\resources\views\layout.blade.php
//blog\resources\views\layout.blade.php
<html>
<head>
    <title>Laravel 9 Join Two Tables</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
</head>
<body>
<div class="container">
    @yield('content')
</div>
</body>
</html>
blog\resources\views\index.blade.php
//blog\resources\views\index.blade.php
@extends('layout')

@section('content')
<div class="row" style="margin:20px;">
    <div class="col-12">
    <h2>Laravel Join Two Tables</h2>
    <table class="table table-bordered table-striped">
        <thead>
            <tr>
            <th scope="col">#</th>
            <th scope="col">Product name</th>
            <th scope="col">Category Name</th>
            </tr>
        </thead>
        <tbody>
            @foreach ($products as $product)
            <tr>
                <td>{{ $loop->iteration }}</td>
                <td>{{ $product->prodname }}</td>
                <td>{{ $product->category->catname }}</td>
            </tr>
            @endforeach
        </tbody>
        </table>
    </div>
</div>    
Creating Routes
blog\routes\web.php
//blog\routes\web.php
<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\ProductController; //add product Controller

Route::get('/', function () {
    return view('welcome');
});

Route::get('products', [ProductController::class, 'index']);
Run C:\xampp\htdocs\laravel\blog>php artisan serve

Starting Laravel development server: http://127.0.0.1:8000

Related Post