2

When I try to determine if an object is empty it's telling me:

Trying to get property of non-object

I'm doing it like this:

 $lastTicket = Auth::user()->ticket->last()->ticketid;
    if($lastTicket->isEmpty())
    {
        $lastTicket = 0;
    }

Obviously Auth::user()->ticket->last(); isn't a record yet. How should I do this? I'm working with Laravel.

Jamie
  • 10,302
  • 32
  • 103
  • 186
  • Based on what you have above, `ticketid` is a property not an object. Therefore you can't use object notation or call a method such as `->isEmpty();` on `$lastTicket`. – War10ck Nov 11 '15 at 18:12

3 Answers3

2

You need to check that collection not empty before get the property:

    if(Auth::user()->ticket->last()->isEmpty())
    {
       $lastTicket = 0;
    }
    else
    {
        $lastTicket = Auth::user()->ticket->last()->lastId;
    }

In short way:

$lastTicket = !Auth::user()->ticket->last()->isEmpty() ? $lastTicket = Auth::user()->ticket->last()->lastId : 0;
ClockworkOrange
  • 587
  • 5
  • 10
  • Thanks for your reply, but when I do that it's telling me: Call to undefined method Illuminate\Database\Query\Builder::isEmpty() – Jamie Nov 12 '15 at 16:44
  • If last() relation is OneToOne this construction must work: $lastTicket = !empty(Auth::user()->ticket->last()) ? $lastTicket = Auth::user()->ticket->last()->lastId : 0; – ClockworkOrange Nov 12 '15 at 16:51
  • When I try: $lastTicket = Auth::user()->ticket->last()->ticketid; if($lastTicket->isEmpty()) { $lastTicket=1; } var_dump($lastTicket); – Jamie Nov 12 '15 at 18:09
  • It throws an exception: Call to a member function isEmpty() on a non-object – Jamie Nov 12 '15 at 18:10
  • I have found out that you only can use isEmpty() on a collection sow this won't work. – Jamie Nov 12 '15 at 18:29
1

First of all have a look here if can be a solution at your problem. And anyway if you're trying to load a relation you should look at the official documentation:

Dynamic Properties

Eloquent allows you to access your relations via dynamic properties. Eloquent will automatically load the relationship for you, and is even smart enough to know whether to call the get (for one-to-many relationships) or first (for one-to-one relationships) method. It will then be accessible via a dynamic property by the same name as the relation. For example, with the following model $phone:

class Phone extends Eloquent {

   public function user()
   {
       return $this->belongsTo('User');
   }

}

$phone = Phone::find(1);

Instead of echoing the user's email like this:

echo $phone->user()->first()->email;

It may be shortened to simply:

echo $phone->user->email;
Community
  • 1
  • 1
IlGala
  • 3,331
  • 4
  • 35
  • 49
0

The right answer was:

$lastTicket = !Auth::user()->ticket->last() ? Auth::user()->ticket->last()->ticketid+1 : 0;

because if it's empty it will return 0 as default.

Jamie
  • 10,302
  • 32
  • 103
  • 186