Model Variable returns null and not the model class

Asked

Viewed 73 times

1

I have the model below and when I do a search that has data, it works right, but when it does not have it returns null, it was not to return the class of the empty model, without filling in the data?

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class AreaInteresse extends Model
{
    use HasFactory;

    protected $table = 'ZPVOBJETIVOINTERESSE';

    protected $fillable = [
        'cpf',
        'nivel',
        'area',
    ];
}

I’m doing the research like this:

$areasInteresse = AreaInteresse::where('cpf', '=', Auth::user()->cpf)->orderBy('id', 'asc')->get();
  • Could you tell me what you’re going to use this data for? Why couldn’t the return be null? By default when no data returns null even, it is correct!

1 answer

1


The return is correct.

Is returned null for the function Where() does not return the class itself, but rather an instance of Querybuilder.

A way around this would be using local Scope recommend giving a read.

Addendum: I will leave this addendum and change as the comment reply.

If you are having trouble returning null, because it is harming when it passes the variable to view you can use the following code in your view:

@if($areasInteresse->isEmpty())
    {{--Código que vai usar $areasInteresse aqui--}}
@endif

This causes you not to enter this part of the code if the output is null.

  • 1

    thank you very much that was the problem!

Browser other questions tagged

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