Press "Enter" to skip to content

Call to a function in model that does not exists ? – Laravel

We keep stumbling upon exceptions while our programming. We invent lots of tricks to handle those or lets just say silent those.

We use something like

  • try – catch blocks
  • @ silent operator
  • In php 7, ?? is new option
  • If checks as much as possible,
  • array_key_exists if it is array
  • isset to check if anything is set.
  • And other tricks lying around.

But somehow it seems tedious to repeat one after another.

In laravel, we do have one cool exception handler. But it is still not enough.

Have an example:

Let’s say, we have a member that belongs to group (a typical eloquent relationship).

In group class, we have

In member class, we have

Somewhere, we will be accessing our member like:

But what if group has been deleted or there is no group associated to the member.

So, if we call group on this member, it will be null because relation is not found. And we cannot call any methods on null. We would then perform those security checks mentioned above when error happens in few cases.

Now, we have a lot of work around.

We can use,

In Blade, you can access,

We can use @ symbol,

We can also use ternary operator like:

One way or other, idea gets repeated and with mistakes too.

Well, there is a quick way around to get away from this mess. There is function called withDefault in model.

What it does, it will return an empty group.

Now, you have a group model,  so you no longer need exception checks anymore. You can simply just call the function you were supposed to call.

Of course, name of group is null, but it will generate empty string as blade wont render null.

Furthermore,  you can even pass and argument,

Well, now you have a default name.

Everything is awesome.

One Comment

Leave a Reply

Your email address will not be published.