Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

iamamirsalehi's avatar

Mysql database views in Laravel

Hi guys.

I need to create a view in my database (Mysql) but i'm thinking about how can i access and control it in my Laravel application. What can i do for it? How can i create a migration and model for it?

0 likes
4 replies
automica's avatar
automica
Best Answer
Level 54

@isamirsalehi This post:

https://www.itsolutionstuff.com/post/how-to-use-mysql-view-in-laravelexample.html

looks like it'll do what you're after.

This is the migration from the example:

<?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 <<<SQL
            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;
    }
   
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    private function dropView(): string
    {
        return <<<SQL
            DROP VIEW IF EXISTS `view_user_data`;
            SQL;
    }
}
1 like
iamamirsalehi's avatar

Thank you for replying. In createView and dropView you used << SQL: syntax but mine doesn't work. What should i do? Should i install a package for it?

Please or to participate in this conversation.