Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel: Get current object inside model class

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?

like image 479
iamjonesy Avatar asked Sep 05 '25 23:09

iamjonesy


2 Answers

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;
}
like image 149
Phill Sparks Avatar answered Sep 08 '25 13:09

Phill Sparks


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)

like image 43
Collin Henderson Avatar answered Sep 08 '25 14:09

Collin Henderson