8

There is no standard procedure mentioned in documentation that how to call a stored procedure in MYSQL in laravel with Eloquent syntax.

I mean is there any way to call stored procedure in mysql with help of eloquent syntax like

$result = StoredProcedures::my_custom_procedure(param1, param2);
return view('welcome')->with('result',$result);

Is there any way to call and fetch results from stored procedures with pure eloquent syntax(purely eloquent way).

Thanks. Small examples are highly encouraged .

Hassan Raza
  • 376
  • 1
  • 5
  • 15
  • 1
    Possible duplicate of [How to execute Stored Procedure from Laravel](https://stackoverflow.com/questions/34497063/how-to-execute-stored-procedure-from-laravel) – Sandeesh Jun 04 '17 at 13:36
  • Eloquent doesn't provide any functionality to call stored procedures. You need to use raw queries to achieve this. The above question has the answer on how to do it. – Sandeesh Jun 04 '17 at 13:48

3 Answers3

6

As everyone has mentioned, you can't call a stored procedure in Laravel with Eloquent syntax. You can transfer the result of your query to a collection which will give you all of the collection functionality.

$queryResult = DB::select('call my_custom_procedure(?, ?)', [1,2]);

$result = collect($queryResult);

return view('welcome')->with('result',$result);
whoacowboy
  • 6,982
  • 6
  • 44
  • 78
3

You cannot call stored procedure with eloquent. However you can use query builder approach in the following style.

first import the following namespaces on top of the controller file or in the file where you want to call the Stored Procedure.

use Illuminate\Support\Facades\DB;
use Doctrine\DBAL\Driver\PDOConnection;

then you can call the stored procedure like below,

$queryResult = $db->prepare('call searchAttendance(?,?,?,?,?)'); 
$queryResult->bindParam(1, $start_date); 
$queryResult->bindParam(2, $end_date); 
$queryResult->bindParam(3, $nurseRoles,PDOConnection::PARAM_STR); 
$queryResult->bindParam(4, $leaveTypesDayOffIds,PDOConnection::PARAM_STR); 
$queryResult->bindParam(5, $leaveTypesVactionIds,PDOConnection::PARAM_STR); 
$queryResult->execute(); 
$results = $queryResult->fetchAll(PDOConnection::FETCH_ASSOC); 
$queryResult->closeCursor(); 
return $results;

reference: Click here

Mohamed Akram
  • 2,244
  • 15
  • 23
  • Maybe you cn help me. Look at this : https://stackoverflow.com/questions/51838922/how-can-i-convert-many-statement-mysql-to-laravel-eloquent – moses toh Aug 15 '18 at 02:36
  • the DB facade alrealy uses PDO underneath, how is this different from: `$queryResult = DB::select('call my_custom_procedure(?, ?)', [1,2]);` – Danys Chalifour Feb 24 '21 at 05:25
1

No there is no Facade for that a simple solution is to use a raw SQL query

$result = DB::select('my_custom_procedure(?, ?)', [1,2]);
  • Maybe you cn help me. Look at this : https://stackoverflow.com/questions/51838922/how-can-i-convert-many-statement-mysql-to-laravel-eloquent – moses toh Aug 15 '18 at 02:36