A list of small functions that help allot

· · 10 months ago

Getters and Setters

Examples of getting a value and set it to another value.

A user has a location_id set to 5
In the locations database table location_id 5 has a location_name set to California.

If we try to show this in our blade file it will return 5 (as expected).


But we would rather it return the location_name

In our User model we can use a getter function like this.

public function getLocationIdAttribute($value)
        $userLocation = Location::where('id', $value)->first();
        return $userLocation->location_name;

This will find the location using the users location_id and then return location_name So now $user->location->id will return California

Another example:
Here we want to make the created_at date a little more readable.

public function getCreatedAtAttribute($value) {
        return Carbon::parse($value)->diffForHumans();

With help from Carbon this will return the date formated like so 3 days ago


Examples of getting a value from the database and changing it to another value.

public function setCompanyIdAttribute($value)
        $company = Company::where('company_acronym', $value)->first();
        $this->attributes['company_id'] = $company->id;