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

Certified AIOps Manager: Strategic Framework for Intelligent IT Operations

Introduction The Certified AIOps Manager program is a specialized training designed to help professionals lead the next wave of IT operations. This guide is for engineers and…

Read More

Advanced AIOps Architect Certification Roadmap for DevOps Engineers

Introduction The Certified AIOps Architect is a comprehensive professional program designed for engineers and architects who want to master the intersection of Artificial Intelligence and IT Operations….

Read More

Advanced Certified AIOps Professional Guide for Mastering AI Driven Operations Skills

Introduction Artificial Intelligence for IT Operations is the future of managing complex systems and large scale digital environments. The Certified AIOps Professional program is designed for those…

Read More

Certified AIOps Engineer Training to Boost Automation Monitoring and Career Growth

The Certified AIOps Engineer is a specialized professional program designed to integrate artificial intelligence into modern IT operations. As systems scale and generate massive amounts of telemetry…

Read More

Advanced Guide to AIOps Foundation Certification for Scalable IT Infrastructure

In an era where infrastructure and applications generate massive amounts of telemetry data, manual intervention is no longer a sustainable strategy for maintaining system uptime. The AIOps…

Read More

Advanced Certified Site Reliability Manager Learning Path for DevOps Teams

Introduction The Certified Site Reliability Manager program is an essential credential for those aiming to lead high-performance engineering teams in the modern era of cloud computing. As organizations transition…

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