Skip to content
Advertisement

How to use a custom model’s method as property in Laravel 9?

In Laravel 9 I use Blade and Spatie´s Permisisons for authorisation. In addition I redirect admins to other Controllers / Layouts / Views than I redirect normal users to.

With that approach I use the users table for both, admins and users. But users have a second table called clients with special normal user´s attributes. The Client model has a function to get the user attributes.

public function login()
{
    return $this->belongsTo('AppModelsUser', 'login');
}

With that I am able to display the client’s email address using {{$client->login->email}}.

But I want to use {{$client->email}} instead and I don’t want to store the email address in clients and users table.

Now I created a custom method

public function email()
{
    $this->login()->first()->email;
}

and I can use it with {{$client->email()}} but what do I need to do, to be able to access it with {{$client->email}}?

Advertisement

Answer

You’re very close actually. Notice how you’re using:

{{ $client->login->email }}

That same syntax can be used inside the model, but replace $client with $this:

public function email() {
  return $this->login->email;
}

Now, you can call:

{{ $client->email() }}

but $client->email (without the ()) will not work, as this is a Method, not a property.

For that, use an Accessor:

public function getEmailAttribute() {
  return $this->login->email;
}

The code get{Whatever}Attribute() will convert the method whatever() to a property whatever, and now you can call:

{{ $client->email }}

Full documentation can be found here:

https://laravel.com/docs/9.x/eloquent-mutators


Edit:

Since your model already has a login column, use a different name for your relationship:

public function loginUser() {
  return $this->belongsTo(User::class, 'login');
}

And now call:

// In your view:
{{ $client->loginUser->email }}
{{ $client->loginUser()->first()->email }}
// ... etc.

// In your `Client.php` model:
$this->loginUser->email;
$this->loginUser()->first()->email;
/// ... etc.

Or refactor your clients table to use a more sensical column name, such as user_id, login_id, etc. Whatever gets you the end result you need 🙂

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement