Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel - Return multiple values within one method

Tags:

php

laravel

Heres where I'm currently stuck at. I am doing multiple methods where I am doing the different queries to the same table:

public function totalOfA()
{
    return $a = Stocks::where('user_id','=', $this->employee->id)
        ->where('category','=','a')
        ->pluck('qty')
        ->sum();
}

public function totalOfB()
{
    return $a = Stocks::where('user_id','=', $this->employee->id)
        ->where('category','=','a')
        ->pluck('qty')
        ->sum();
}

I'm trying to look for a way to sum that all up to just one function

public function totalStocks()
{
    $stocks = Stocks::where('user_id','=', $this->employee->id)
        ->get();

    $a = $stocks::where('category', '=', 'a')
        ->pluck('qty')
        ->sum();

    $b = $stocks::where('category', '=', 'b')
        ->pluck('qty')
        ->sum();

    return $a and $b
}

So I can just call it from view as totalstocks()->a or totalstocks()->b something like that.

like image 890
Oliver Vincent Ledesma Avatar asked Sep 20 '25 09:09

Oliver Vincent Ledesma


2 Answers

try this:

function totalStocks() {
   $a = 1;
   $b = 2;

   return  [$a, $b];
}

list($valueA, $valueB) = totalStocks();
echo $valueA; //1
echo $valueB; //2
like image 196
Link.de Avatar answered Sep 22 '25 23:09

Link.de


You cant call like that.you can create an aray or you can pass seperately to view

public function totalStocks()
{
    $stocks = Stocks::where('user_id','=', $this->employee->id)
        ->get();

    $a = $stocks::where('category', '=', 'a')
        ->pluck('qty')
        ->sum();

    $b = $stocks::where('category', '=', 'b')
        ->pluck('qty')
        ->sum();

    return view('home',['stocks'=> $stocks,'a'=>$a,'b'=>$b]);

}

Now you can access $a ,$b in your view

 public function totalStocks()
    {

        $data['stocks'] = Stocks::where('user_id','=', $this->employee->id)
            ->get();

       $data['a'] = $stocks::where('category', '=', 'a')
            ->pluck('qty')
            ->sum();

       $data['b'] = $stocks::where('category', '=', 'b')
            ->pluck('qty')
            ->sum();

        return view('home',['data'=>$data]);

    }

so you can accessin view like {{$data['a']}}

like image 43
Vision Coderz Avatar answered Sep 22 '25 21:09

Vision Coderz