How to Call Stored Procedure In Laravel 7
In this article we will learn how to call stored procedure in Laravel . As Laravel makes it very easier for working with database , so calling stored procedure in laravel is also super easy process . Let's dive in and see how to do this .
We will call stored procedure using both parameter and without parameter .
Step 1 - Create a Stored Procedure :
First create a stored procedure in your mysql Database like the following . In this example i have created a stored procedure for getting all the users from the users table as shown below .
Setup your routes for calling the controller .
Route::get('/procedure/{id}','CheckController@callProcedure');
Step 3 - Call Procedure in Laravel :
Calling Procedure without Parameter :
Use the following syntax for calling a procedure in Laravel .
$alluser = DB::select('call procedurename()');
CheckController.php :
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use DB;
class CheckController extends Controller
{
public function callProcedure()
{
// Calling Stored Procedure from MySQL
$alluser = DB::select('call getalluser()');
return $alluser;
}
}
Output :
Calling Procedure with Parameter :
Use the following syntax for calling a procedure with parameter in Laravel .
$specificuser = DB::select('call getspecificuser(?,?,?,?)',array("parameter1","parameter2","parameter3","parameter4"));
CheckController.php :
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use DB;
class CheckController extends Controller
{
public function callProcedure($id)
{
// Calling Stored Procedure from MySQL
$specificuser = DB::select('call getspecificuser(?)',array($id));
return $specificuser;
}
}
Output :
Thank you for reading this article 😊
For any query do not hesitate to comment 💬