How to use MySQL View in Laravel 8 ?

Admin   Laravel   461  2021-03-15 02:40:04

Now let's see example of how to use mysql view in laravel 8 application. In this tutorial, i will show you create mysql view in laravel 8 application. I’m going to show you about laravel migration create view. Here you will learn laravel migration make view. i explained simply step by step how to use mysql view in laravel. Let's see bellow example laravel using mysql views.

This tutorial will give you how to use mysql view in laravel 8. We will learn how to create mysql view in laravel 8.

In this example, we will create "view_user_data" view and i will get count posts and comments of that user. so we don't require to fire again and again same query on server. so let's simple example bellow:

Bellow my sql query for creating view and drop view:

SQL Create View Query

 

CREATE VIEW view_user_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_user_data`;

Now we need to use this query on our live database with laravel migration. so let's create migration with views.

Create Migration:

 

php artisan make:migration create_user_view

Update Migration File:

 

<?php

use Illuminate\Database\Migrations\Migration;

use Illuminate\Database\Schema\Blueprint;

use Illuminate\Support\Facades\Schema;

class CreateUserView 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