0

I have a query that works before using laravel eloquent method

$products = Product::where('category', 'ILIKE', '%'.$conditionTxt.'%')
                            ->orderBy('created_at', 'desc')
                            ->get();

But after using query builder approach

$products = DB::table('products')
                      ->where('category', 'ILIKE', '%'.$conditionTxt.'%')
                      ->orderBy('created_at', 'desc')
                      ->get();

It returns this error:

Undefined property: stdClass::$inventory

Here is my model and portion of the view where it points the error.

Model

public function inventory(){
    return $this->hasMany('App\InventoryRecord\InventoryRecord');
}

View:

<td>
    <?php 
    for($i = 0; $i < count($val->inventory); $i++){
        if( $val->inventory[$i]->total_qty <= 50 )  { ?>
            <span style="color:#C00"><?php echo $val->inventory[$i]->total_qty.' -'; ?></span>
        <?php  }else{ ?>
            <span style="color:#25A602"><?php echo $val->inventory[$i]->total_qty.' -'; ?></span>
        <?php
        }
    }
    ?>
</td>
1
  • Can somebody help me with this please? :( Commented Dec 24, 2016 at 2:54

2 Answers 2

1

When you use query builder approach it returns an Illuminate\Support\Collection containing the results where each result is an instance of the PHP StdClass object (not a model object). You may access each column's value by accessing the column as a property of the object.

But you can't access the Model relations because you have PHP StdClass object.

I would suggest you, stick to Laravel eloquent.

Sign up to request clarification or add additional context in comments.

Comments

1

You are mixing up two different pieces of functionality. Laravel provides a data access layer, which is the Query Builder. Laravel also provides an ORM called Eloquent, which is built on top of the Query Builder.

When you use Eloquent to query the database, you will get instances of your Eloquent Models back.

When you use the Query Builder to query the database, you will get instances of stdClass back.

The query builder doesn't, and shouldn't, know anything about your Eloquent models. If you need Eloquent functionality (like accessing your inventory relationship), then you need to use Eloquent to query the database.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.