Laravel find () function giving error

2

When I launch a search with an id that exists in the database, it works normally.

  

Laravel 5.6

    public function findProduto($id)
{
    $produto = Produto::find($id)->with('imagemgame')->first();
    return $dados_check = $produto->count()>0 ? $produto : false ;
}

But when I launch a search with an id that does not exist in the database, instead of returning "false", it returns an error, seems to be giving something wrong in find or something like that.

Symfony \ Component \ Debug \ Exception \ FatalThrowableError (E_ERROR)
Call to a member function find() on null

Model- > Products

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use App\Models\ImageUploads;

class Produto extends Model
{
use SoftDeletes;

public $timestamps = true;

protected $table = 'produtos';

protected $fillable = [
    'titulo', 'status', 'console', 'edicao', 'genero', 'classificacao', 'custo', 'venda', 'promocao',
    'indatepromo', 'outdatepromo', 'quantidade', 'descricao', 'produtora', 'lancamento',
    'idioma', 'legenda', 'onplayers', 'offplayers', 'obs1', 'obs2', 'obs3', 'video',
];

protected $hidden = ['custo'];

protected $dates = ['deleted_at'];

/////////////////////////////////////////////////////////////////
/// RELACIONAMENTOS /////////////////////////////////////////////
public function imagemgame(){
    return $this->hasMany(ImageUpload::class, 'produtos_id', 'id')->orderBy('capa', '1');
}

}

    
asked by anonymous 25.08.2018 / 03:17

1 answer

4

Analyzing your code has some problems, eg when using find which is the return of information from the primary key of your table if the data does not is found is returned null and soon after you make a with that does not exist, this is the reason for the problem and the exception thrown, then inside the method at the time of return you put count , there is no such method because is not a list is a unique data, then also have to change the criticism and resolved propror a minimal example:

public function findProduto($id)
{
    $produto = Produto::with('imagemgame')->where('id', $id)->first();
    return is_null($produto) ? false: $produto;
}

Note: I made a where and put the name of the primary key , you should also put the same name, id which is a default, but of course the name can be another.

It can also be done like this:

public function findProduto($id)
{
    $produto = Produto::find($id);
    if ($produto)
    {
        $produto->load('imagemgame'); //carregamento a relação
        return $produto;
    }
    return false;
}

Eloquent: Relationships >

    
25.08.2018 / 04:07