laravel 9 stored procedure multiple results

Laravel 9 Stored Procedure

Execute Stored Procedure Using Laravel 9

In this post, we will give you information about Execute Stored Procedure Using Laravel 9. Here we will give you detail about Execute Stored Procedure Using Laravel 9 And how to use it also give you a demo for it if it is necessary.

create MySQL stored procedure using laravel9 migration and we will call stored procedure using laravel eloquent. you can easily use it with laravel 6, laravel 7 and laravel 8 versions.

in this example, we will create a stored procedure call “posts_by_userid” that will return posts of given user id. so let’s see bellow simple example:

<?php
  
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
  
class CreatePostProcedure extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        $procedure = "DROP PROCEDURE IF EXISTS `posts_by_userid`;
            CREATE PROCEDURE `posts_by_userid` (IN idx int)
            BEGIN
            SELECT * FROM posts WHERE u_id = idx;
            END;";
  
        \DB::unprepared($procedure);
    }
  
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
         
    }
}

Call Stored Procedure:

Route::get('call-post-procedure', function () {
  
    $postId = 1;
    $getPost = DB::select(
       'CALL posts_by_userid('.$postId.')'
    );
  
    dd($getPost);
      
});

OUTPUT

Array

(

    [0] => stdClass Object

        (

            [id] => 15

            [title] => demo title

            [body] => demo body

            [created_at] => 2022-01-01 06:00:03

            [updated_at] => 2022-01-01 06:00:03

            [u_id] => 111

        )

    [1] => stdClass Object

        (

            [id] => 60

            [title] => demo title

            [body] => demo body

            [created_at] => 2022-01-01 06:14:05

            [updated_at] => 2022-01-01 06:14:05

            [u_id] => 111

        )

)

The first parameter uses the call keyword to execute the Stored Procedure and the second parameter takes data in an array format.
That’s it. Hope this article helps you guys to understand “How to Execute Stored Procedure Using Laravel 9”.

Conclusion for Execute Stored Procedure Using Laravel 9

Hope this code and post will help you implement Execute Stored Procedure Using Laravel 9. if you need any help or any feedback give it in the comment section or you have a good idea about this post you can give it in the comment section. Your comment will help us to help you more and improve us.

For More Info See :: laravel And github

Leave a Comment

Your email address will not be published. Required fields are marked *

  +  46  =  51

We're accepting well-written guest posts and this is a great opportunity to collaborate : Contact US