Home > Software design >  laravel I'm trying to get substract value in view
laravel I'm trying to get substract value in view

Time:05-05

hello im trying to get substract value in controller to pass in view using two different table.

im getting error

ErrorException
Object of class Illuminate\Database\Eloquent\Collection could not be converted to number

my table

table_a and table_b

table_a columns selected "price"     //discount $100 is percent in table_a
table_b columns selected "discount"  //discount $5 is percent in table_b 

my controller

   public function index()   
   {
 
        $table_a = TABLE_A::get(['price']);
        $table_b = TABLE_B::get(['discount']);
 

 $substract = $table_a - $table_b ; 

       return view('Home', compact('substract' ));
    
   }

view

<b> final value </b>
<h1> {{ $substract}}</h1> //value need to get $95

CodePudding user response:

You must understand some basic Laravel to see that you are doing a wrong thing.

  1. Model::get() returns a Collection (that may or not have items)
  2. A collection acts like an extended array (i.e it's an instance of Illuminate\Database\Eloquent\Collection), it has many methods to help you handle data such as contains,find, map, filter, etc.
  3. Each item in the collection is an Model, not an number directly.
  4. You cannot sum/subtract an array directly.
  5. Also you cannot sum/subtract Model obejcts directly.

That said, you have a few conception problems:

  1. To make the subtraction, you need to choose a row and a column first, eg: Table_A::first()->price - Table_B::first()->discount
  2. The code in 1. will not work as you expect unless you have a single row in your tables.

CodePudding user response:

Your use case is odd, but this should work to fix your code.

public function index()   
   {
 
        $table_a = TABLE_A::first();
        $table_b = TABLE_B::first();
 

 $substract = $table_a->price - $table_b->discount ; 

       return view('Home', compact('substract' ));
    
   }

If you want instead to sum all values in every table you can do

public function index()   
   {
 
        $table_a = TABLE_A::sum('price');
        $table_b = TABLE_B::sum('discount');
 

 $substract = $table_a - $table_b ; 

       return view('Home', compact('substract' ));
    
   }
  • Related