Support the ongoing development of Laravel.io →
posted 7 years ago
Architecture
Last updated 1 year ago.
0

assuming your "Thing" class is a model:

you don't need setThis and getThat methods on your model.

you can always get attributes defined on your table

$thing->id;
$thing->name;

you can set attributes as long as they are defined on the $fillable array on the model

$this->name = "new name";

There's also something called "mutators" in the model, where you can get an attribute value with a change,

public function getNameAttribute($value)
{
    return ucwords($value);
}

usage:

$thing->name; // returns ucwords value

The mutated attribute does not need to be a table column. say you have a user table with "first" and "last" name columns, you can create method getNameAttribute(),

public function getNameAttribute()
{
    return $this->first_name . $this->last_name;
}

To set values with a change use "accessors", say you have a field on the table "admission_date" here you convert it to UTC and store.

public function setAdmissionDateAttribute($value)
{
    $this->attributes['admission_date'] = Carbon::create($value, 'Asia/Jakarta')->setTimezone('UTC');
}

usage

$thing->admission_date; //sets the model value converted to UTC

https://www.laravel.com/docs/5.3/eloquent-mutators#

Last updated 7 years ago.
0

Hi,

sorry you misunderstood the question I think. It's not connected to a database table. I just want Thing->Attribute syntax eg $thing->score=50 which runs a setter function, in this case for a session value

i found out you could use setAttribute and getAttribute though, so this works by using Eloquent but not having it relate to a database table.



use Eloquent;

Class ThingSession extends Eloquent {

	public $name = "ThingSession";

	public function __construct() {
	}

	public function reset() {
		session()->forget($this->name);
	}

	public function forget($args) {
		foreach((array)$args as $field) {
			session()->forget($this->name.'.'.$field);
		};
	}

	public function getAttribute($name) {
		return session($this->name.'.'.$name);
	}

        // set eg ThingSession.score in session
	public function setAttribute($name, $value) {
		session([$this->name. '.'.$name => $value]);
	}

}

Then i call eg...

$thing = new ThingSession();
// sets score = 50 in ThingSession session array
$thing->score = 50;

// Laravel DebugBar will show eg

ThingSession array:1 [ "score" => 50 ]
Last updated 7 years ago.
0

Sign in to participate in this thread!

Eventy

Your banner here too?

jmp909 jmp909 Joined 29 Jan 2015

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2024 Laravel.io - All rights reserved.