0

i want my code to keep working if the table return null

i tried using if(empty) bla bla bla, but is not seem to be the problem

the problem is laravel don't let me call function on null

@php($article = article::find($id)->get())

error : "Call to a member function get() on null"

4
  • Your problem is that article::find($id) returns null, yes? Commented Jun 28, 2019 at 18:02
  • yes, i want to prevent that error Commented Jun 28, 2019 at 18:04
  • 2
    remove the ->get(), it does not make sense there, find() will retrive one model or null. Commented Jun 28, 2019 at 18:17
  • You don't need get() on find() as other users say..but if it returns null you can assign any value to your $article using nullcoalesce operator ??. $article = article::find($id) ?? [] if article db returns null $article will be assign to empty array() Commented Jun 28, 2019 at 18:29

2 Answers 2

1

If aritcle::find($id) returns null, it should solve the problem:

@if($article = article::find($id) != null)
    // If the aricle::find($id) returns anything but null, this block will be reached.
@endif

I think that is better to you to send the data to the view from the controller, instead of using blade directives to fetch data.

something like this:

//Within some controller:
public function show($id)
{
    $article = article::find($id);
    return view('your-view')->with($article);
}

Then you can check if $article is null using blade:

@if(empty($article))
    // The article is empty
@endif
Sign up to request clarification or add additional context in comments.

2 Comments

how to get, a get method from controller?
i add an example
0

Using ->get() after find() is unnecessary. find() automatically returns the model that matches the primary key provided. You will get errors if you attempt to access $article after find() fails, but it will stop you from getting the error you posted.

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.