DaFois
DaFois

Reputation: 2223

Calling db in a function

I'm trying to use a function that I wrote inside my routes.php file:

the function is this:

function userScore($uid) {

    $db = $app->get('db');

    //calcolo punteggio totale 
    $query_punti = $db->table('prodotti_sounding')
    ->where('id_utente', $uid)
    ->select('punti')
    ->get();

    $totale_punti = 0;
    foreach($query_punti as $item) {
       $totale_punti += $item->punti;
    }
}

it returns this error:

Slim Application Error The application could not run because of the following error:

Type: Error Message: Call to a member function get() on null

where am I wrong?

EDIT

my relevant code in routes.php after the first answer is:

use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Message\ResponseInterface;
use Illuminate\Database\Connection;
use Slim\Http\UploadedFile;
use Illuminate\Support\Facades\DB as DB;

$container = $app->getContainer();

$app->post('/sendbarcode', function ($request, $response){
            /* parametri barcode */
            /** @var Container $this */
            /** @var Connection $db */

            $barcode = $request->getParsedBodyParam('barcode');
            $id_utente = $request->getParsedBodyParam('id_utente');

            $db = $this->get('db');

            // prepare data for json
            $array['itacheck'] = 0;

            if(checkbarcode($barcode) == 1 ) {
                $array['it_check'] = 1;
                $array['punti'] = 25;
                $array['totalepunti'] = userScore($id_utente);
            }

            $array['barcode'] = $rows;

            if(count($rows) > 0){
                return $response->withJson($array, 200, JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_LINE_TERMINATORS);
            } 
        });

function userScore($uid) {

    //calcolo punteggio totale in base alle segnalazioni pregresse
    $query_punti = DB::table('prodotti_sounding')
    ->where('id_utente', $uid)
    ->select('punti')
    ->get();

    // check total points
    $totale_punti = 0;
    foreach($query_punti as $item) {
       $totale_punti += $item->punti;
    }
}

Upvotes: 0

Views: 36

Answers (1)

Davit Zeynalyan
Davit Zeynalyan

Reputation: 8618

Error becomes $db = $app->get('db');, because you not defained $app variable. Instaed of you can use this

//calcolo punteggio totale 
$query_punti = DB::table('prodotti_sounding')
    ->where('id_utente', $uid)
    ->select('punti')
    ->get();

DB full class name is \Illuminate\Support\Facades\DB
Edit
That case add $app attribute in function argument

function userScore($uid, $app) {    
    $db = $app->get('db');

Upvotes: 1

Related Questions