Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute SQL functions with Laravel 5

I have SQL functions stored on my database.

However, I can not call them.

$nb = DB::select('SELECT nb_seances_archivees()');

The result is :

array:1 [▼
   0 => {#186 ▼
      +"nb_seances_archivees": 0
   }
]

But the desired result is just 0.

Thank's for help !

like image 946
Royce Avatar asked Jan 29 '23 00:01

Royce


1 Answers

By default DB::select return an array of objects, you can use collections to get the first result:

 $nb = collect(DB::select('SELECT nb_seances_archivees() AS nb'))->first()->nb;

Or directly access the first object in the array:

 $nb = DB::select('SELECT nb_seances_archivees() AS nb')[0]->nb;

If you want to pass parameters then you should do:

 DB::select('SELECT nb_seances_archivees(?) AS nb', [$parameter]);
like image 100
YouneL Avatar answered Jan 31 '23 18:01

YouneL