3

I'm wondering if it's possible to access the current object when accessing a method of that object. for example the method fullname() below is used to get the full name of the user.

class User extends Eloquent 
{

    public function itineraries() {
        return $this->has_many('Itinerary', 'user_id');
    }

    public function reviews() {
        return $this->has_many('Placereview', 'user_id');
    }

    public function count_guides($user_id){
        return Itinerary::where_user_id($user_id)->count();
    }

    public static function fullname() {
        return $this->first_name . ' ' . $this->last_name; // using $this as an example
    }
}

A user has a first_name field and a last_name field. Is there anyway I can do

$user = User::where('username', '=', $username)->first();

echo $user->fullname();

Without having to pass in the user object?

Phill Sparks
  • 20,000
  • 3
  • 33
  • 46
iamjonesy
  • 24,732
  • 40
  • 139
  • 206
  • 1
    Can you just chain them? `$fullName = User::where('username', '=', $username)->first()->fullname();` ? – Collin Henderson May 12 '13 at 15:43
  • I could. But I'd like to do that in my model. Plus there are other things I want to do using that method such as calculating age from DOB etc. – iamjonesy May 12 '13 at 15:46
  • Oh, I think I see what you're after. You're looking for something like User::fullname($someusername) type thing right? – Collin Henderson May 12 '13 at 15:49
  • What I'm really after is a method where I don't have to do any more DB calls as the user object already exists. So a way in which i can access the current object's properties in a method of that object – iamjonesy May 12 '13 at 16:07

2 Answers2

8

You're almost there, you just need to remove the static from your code. Static methods operate on a class, not an object; so $this does not exist in static methods

public function fullname() {
    return $this->first_name . ' ' . $this->last_name;
}
Phill Sparks
  • 20,000
  • 3
  • 33
  • 46
  • I like to use `implode(' ', [$this->first_name, $this->last_name]);` That way if either is ever blank there are no extra spaces – Brett Santore Feb 23 '18 at 19:59
  • Neither `first_name` nor 'last_name' is a property of the class `User`. Still you can access them as they are database columns. 1) Unlike usual PHP classes, this is specific to Laravel, right ? 2) Where in Laravel doc is it said ? – Istiaque Ahmed Jul 09 '18 at 07:40
  • Found it: https://laravel.com/docs/5.5/eloquent-mutators , take a look at `getFullNameAttribute()` function. still supported in Laravel 8. – moghwan Jan 12 '21 at 16:14
3

In your user model, your static function can look something like this

public static function fullname($username) {
    $user = self::where_username($username)->first();

    return $user->first_name.' '.$user->last_name;
}

You can then call this anywhere in your views/controllers etc with User::fullname($someonesUsername)

Collin Henderson
  • 1,154
  • 10
  • 22