Home > OS >  Using first() on Eloquent Relationships
Using first() on Eloquent Relationships

Time:12-11

Good day. I saw this snippet in a code I am maintaining. I am trying to wrap my head around what it means (like if I even have to explain it to someone). Who can help simplify? The code is shown below.

public function pullFrom(string $appType)
    {
        switch ($appType) {
            case 'personal':
            case 'plugin':
                return $this->belongsTo(PersonalUser::class, 'local_id')->first();
            default:
                throw new \Exception('Invalid user type provided', Response::HTTP_INTERNAL_SERVER_ERROR);
        }
    }

Is it same as saying $user->pullFrom($app_type)->first();

CodePudding user response:

I think you should remove the ->first() from the belongsTo relationship by default belongsTo returns only 1 element of the class it has relation with, as well as remove it from the call you do:

public function pullFrom(string $appType)
    {
        switch ($appType) {
            case 'personal':
            case 'plugin':
                return $this->belongsTo(PersonalUser::class, 'local_id');
            default:
                throw new \Exception('Invalid user type provided', Response::HTTP_INTERNAL_SERVER_ERROR);
        }
    }
  • Related