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
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 ]
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community