How to Use MySQL View in Laravel 9?

In this blog post, you can explore the concept of MySQL views and explain how to effectively integrate them into Laravel applications.

SQL Create View Query

CREATE VIEW view_data AS

SELECT 

    users.id, 

    users.name, 

    users.email,

    (SELECT count(*) FROM posts

                WHERE posts.user_id = users.id

            ) AS total_posts,

    (SELECT count(*) FROM comments

                WHERE comments.user_id = users.id

            ) AS total_comments

FROM users

SQL Drop View Query

DROP VIEW IF EXISTS `view_data`;

 Let’s create migration with views.

php artisan make:migration create_view

Update Migration File:

<?php

  

use Illuminate\Database\Migrations\Migration;

use Illuminate\Database\Schema\Blueprint;

use Illuminate\Support\Facades\Schema;

  

class CreateView extends Migration

{

    /**

     * Run the migrations.

     *

     * @return void

     */

    public function up()

    {

        \DB::statement($this->createView());

    }

   

    /**

     * Reverse the migrations.

     *

     * @return void

     */

    public function down()

    {

        \DB::statement($this->dropView());

    }

   

    /**

     * Reverse the migrations.

     *

     * @return void

     */

    private function createView(): string

    {

        return <<

            CREATE VIEW view_data AS

                SELECT 

                    users.id, 

                    users.name, 

                    users.email,

                    (SELECT count(*) FROM posts

                                WHERE posts.user_id = users.id

                            ) AS total_posts,

                    (SELECT count(*) FROM comments

                                WHERE comments.user_id = users.id

                            ) AS total_comments

                FROM users

            SQL;

    }

   

    /**

     * Reverse the migrations.

     *

     * @return void

     */

    private function dropView(): string

    {

        return <<

            DROP VIEW IF EXISTS `view_data`;

            SQL;

    }

}

now we will create model as below:

app/ViewData.php

<?php

  

namespace App;

  

use Illuminate\Database\Eloquent\Model;

 

class ViewUserData extends Model

{

    public $table = "view_data";

}

Now we can use it as below on the controller file:

<?php

  

namespace App\Http\Controllers;

  

use Illuminate\Http\Request;

use App\ViewData;

  

class UserController extends Controller

{

    /**

     * Display a listing of the resource.

     *

     * @return \Illuminate\Http\Response

     */

    public function index()

    {

        $users = ViewData::select("*")

                        ->get()

                        ->toArray();

          

        dd($users);

    }

}

you can see output:-

array:20 [▼

  0 => array:5 [▼

    "id" => 1

    "name" => "Roshan Kumar Jha"

    "email" => "roshan.cotocus@gmail.com"

    

  ]

Related Posts

Modern Cloud DataOps Platforms for Reliable Data Pipelines

Introduction Modern organizations depend heavily on data. Every department, from finance and sales to healthcare, manufacturing, marketing, and customer support, needs reliable data to make better decisions….

Read More

Advanced DataOps Monitoring Tools for Enterprises: A Comprehensive Implementation Guide

Introduction Enterprise data environments are becoming more complex as organizations depend on cloud platforms, data lakes, data warehouses, real-time pipelines, analytics tools, and automated workflows. When one…

Read More

The Ultimate Share Market for Beginners Guide to Smart Returns

Entering the world of equity investing can feel like stepping into a foreign country where everyone speaks a different language. The flashing tickers, fast-moving financial news charts,…

Read More

Evaluating SEO Reporting Software: Must-Have Features for Modern Enterprise

Introduction Modern marketing teams, digital agencies, and e-commerce brands juggle multiple disjointed tools to manage their online footprint. Hopping between single-purpose tools for keyword tracking, asset storage,…

Read More

Platform Engineering and GitOps: Enterprise Guide to Modern Delivery

Introduction DevOps has evolved from a niche engineering practice into a boardroom priority that directly impacts customer experience, revenue, and competitiveness. Yet many enterprises still struggle to…

Read More

Platform Engineering vs DevOps: The New Cloud Architecture Shift.

Introduction Modern software engineering moves at breakneck speeds. Organizations must deploy features rapidly while maintaining total system availability. Transitioning away from legacy architectures toward modern cloud infrastructure…

Read More
Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x