Error doing Join with Laravel Query Builder

Asked

Viewed 245 times

5

I’m doing the following Join:

public function getStockDanger()
{
    $data = DB::table('product')
        ->join('stock', 'product.id', '=', 'stock.product_id')
        ->where('stock.stock', '<=', 0)
        ->get();

    return view(
        'product.index',
        [
            'data' => $data,
            'data_category' => $this->category->all(),
            'nav' => $this->nav
        ]
    );
}

View:

    @if($data->count() > 0)
        <div class="row">
            <div class="col-md-12">
                <table class="table table-striped table-responsive">
                    <thead>
                    <tr>
                        <th class="id text-center">#</th>
                        <th class="text-center">Produto</th>
                        <th class="text-center">Quantidade</th>
                        <th class="text-center">Preço</th>
                        <th class="text-center">Ações</th>
                    </tr>
                    </thead>
                    <tbody>
                    @foreach($data as $product)
                        <tr>
                            <td class="id text-center">{{$product->id}}</td>
                            <td class="text-center"><a class="color-red"
                                                       href="/products/{{$product->id}}">{{$product->name}}</a></td>
                            <td class="text-center @if($product->stock->stock <= 0) credit_danger @else credit_ok @endif">{{$product->stock->stock}}</td>
                            <td class="text-center credit_ok">R$ {{$product->sale_price}}</td>
                            <td class="text-center">
                                <a title="Editar" style="margin-right: 5px; color: #3498db; font-size: 18px;"
                                   href="/products/edit/{{$product->id}}"><i class="fa fa-pencil"
                                                                             aria-hidden="true"></i></a>
                                <a title="Excluir" style="color: #e74c3c; font-size: 18px;"
                                   href="/products/delete/{{$product->id}}"><i class="fa fa-trash-o"
                                                                               aria-hidden="true"></i></a>
                            </td>
                        </tr>
                    @endforeach
                    </tbody>
                </table>
                @include('pagination.default')
            </div>
        </div>
    @else
        <div class="alert alert-empty">
            <strong>Nenhum cadastro!</strong> Tabela vazia
        </div>
    @endif
</div>

But I’m getting the following error

Fatalerrorexception in ac3f490a3eb54420e99fe37a225e6f129d87f36d.php line 36:

Call to a Member Function Count() on a non-object

What could I have done wrong?

  • 1

    It’s hard to find without the view. post line 36 of the view product.index.

  • Another thing: Always report the version of Laravel.

  • Error in View line 36?

  • I posted the view. Laravel 5.2

  • The problem seems to be that it is not being recognized as an object, but as I do to come a collection of objects?

  • @Virgilionovic your answer is not wrong. Larvel 5.2 still returns a array.

  • @Wallacemaxters let me confirm, there was so much change that I remember not returning class collection I’ll be right back!

Show 2 more comments

3 answers

3


The Query Builder of Laravel 5.2 does not return a class Collection but, um array simple, look at the informative text in English:

Like raw queries, the get method Returns an array of Results Where each result is an instance of the PHP Stdclass Object. You may access each column’s value by accessing the column as a Property of the Object:

So:

change this line

@if($data->count() > 0)

for that

@if(count($data) > 0)

In version Laravel 5.3 returns a class Collection:

The get method Returns an Illuminate\Support\Collection containing the Results Where each result is an instance of the PHP Stdclass Object. You may access each column’s value by accessing the column as a Property of the Object:

  • This is another problem, in this view I need to manipulate objects, because I use information from two different tables, I use belongsTo be able to pull the attributes that are in another table, know if it is possible to make a Join returning a Collection of objects in Laravel 5.2?

  • @Felipepaetzold if you configured the Model, you can use directly by the entity class, understood, the same brings the relationships, you have the classes configured?

  • I set up the access methods, but I need a portion of the records that meet a certain condition, not all records, so I need to do Join.

  • When you use Join with Fluent Builder it does not make the game of equal relation the Eloquent, each line represents a field of the table and relations, as we do with a PDO or Mysqli, each line dams the junction of that Join, I saw that you put $product->stock->stock It doesn’t work but, as you did the relationship he must be in $produto->nome_do_campo. before sending to screen give a var_dump($data) in the Controller check what returns this is the final solution if you will understand quickly!

  • 1

    Actually it returns me a Collection, but Join creates a stock attribute on the object, so I could not use the same view, because product->stock->stock does not exist there, it is product->stock... but still thank you.

1

You could do it using Eloquent that way:

Controller

public function getStockDanger()
{
    $data = Product::get();

    return view(
        'product.index',
        [
            'data' => $data,
            'data_category' => $this->category->all(),
            'nav' => $this->nav
        ]
    );
}

In the Model Product you should have a method of relationship:

class Product extends Model{
    public function stock(){
        $this->hasMany('App\Stock', 'product.id', 'product_id')->where('stock', '<=', 0);
    }
}

From there on View...

@if($data->stock->count() > 0)
    @foreach($data->stock as $product)

        # Aqui pode deitar o pêlo.

    @endforeach
@endif

0

In versions prior to Laravel 5.3, no query results from Fluent returns Collection, and yes a array.

As Virgil says, use count($data) instead of $data->count().

Just giving more details, When you use DB::table(), you are using the Fluent. He will return array, unlike Eloquent, that returns a Illuminate\Database\Eloquent\Collection.

If you want to avoid problems or even keep a standardization in your code, you can use count($data) so much for Eloquent as for Fluent, since the Collection of Laravel implements the interface Countable (when you use it, it is possible to define a behavior for when it is called count in the class instance).

Read more on:

Browser other questions tagged

You are not signed in. Login or sign up in order to post.