2
votes

I created an artisan custom command and in the handle() method i need to get a few info about users.

When i run:

handle() {
   $users = User::all();
   foreach($users as $user) {
      $this->line($user->name);
   }
}

it works, but i need something like:

handle() {
   $users = User::all();
   foreach($users as $user) {
      $this->line($user->summoner->summoner_id);
   }
}

And i get Trying to get property of non-object.

If i run the same code above in a controller it works just fine.

Does anyone have an idea?

User model:

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    use Notifiable;

    protected $fillable = [
        'name', 'email', 'password',
    ];

    protected $hidden = [
        'password', 'remember_token',
    ];

    public function summoner() {
        return $this->hasOne('App\Summoner');
    }

Summoner model:

    <?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Summoner extends Model
{
    protected $table = 'summoners';
    public $timestamps = true;

    public function user() {
        return $this->belongsTo('App\User');
    }
}
1
Show your models and relationships. - aynber
Ok, edited above - Felipe Martins
Try to dump $users in logs. See what exactly you got in variable. Also this can occur if any user doesn't have phone number - Vaibhavraj Roham
It sounds like all summoners have a user, but not all users have a summoner. Verify that before you try to print it (if !empty($user->summoner)) - aynber
You edited phone number to something else. (summoner->summoner_id). Try logging the object - Vaibhavraj Roham

1 Answers

0
votes

As @aynber metnioned above, if DB field user.summoner_id can be set to NULL, then there are users without related Summoner.

So you can use whereHas method of the QueryBuilder, which will check relationship summoner existence:

$users = User::whereHas('summoner')->get();
foreach($users as $user) {
  $this->line($user->summoner->summoner_id);
}

Or you can check existens of the relationship summoner for every selected user, but this approach may select redundant data from DB (if you need all users with non-NULL summoner_id field):

$users = User::all();
foreach($users as $user) {
    if(empty($user->summoner)){
        continue;
    }
    $this->line($user->summoner->summoner_id);  
}

You can find more information about whereHas method here: