You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
This is a proposed method to fix some limitations with eloquent models which some dynamic variables cannot be used with models relationships and attribute retrievals.
Given the below specifications:
calculate distance between each models and the authenticated user
assign each distance result to each models attribute as distance
// HasArgAttribute.phptrait HasArgAttribute
{
protected$args = [];
// function to populate the models args with valuesfunctionsetArgs(array$args) {
$this->args = $args;
return$this;
}
// function to make `args` available for model query builderfunctionscopeWithArgs($q, $args, callable$call = null) {
// when model retrievedstatic::retrieved(function ($model) use($args, closure $call) {
// set the model args$model->setArgs($args);
$call && $call($model);
});
}
}
we could use HasArgAttribute to pass coordinates to the user model.
// User.phpuseHasArgAttribute;
functiongetDistanceAttribute() {
// we should expect args to be populated with some value(s).if (!$this->args) {
returnnull;
}
return$this->getDistance($this->args[0], $this->args[1]);
}
Retrieving users with calculated distance from auth user using HasArgAttribute
// User.phpfunctionposts() {
// allows us to use dynamic relationship key// currently not possible without model args featurereturn$this->hasMany(Post::class, $this->args['some_dynamic_value']);
}
Please could this be a useful feature in the laravel framework? @themsaid and everyone else.
reacted with thumbs up emoji reacted with thumbs down emoji reacted with laugh emoji reacted with hooray emoji reacted with confused emoji reacted with heart emoji reacted with rocket emoji reacted with eyes emoji
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
This is a proposed method to fix some limitations with eloquent models which some dynamic variables cannot be used with models relationships and attribute retrievals.
Given the below specifications:
distance
Using normal way
User.php
Retrieving users with calculated distance from auth user
we could improve above approach by using laravel getAttribute feature.
with this approach no way to pass the authenticated user coordinates to the
getDistanceAttribute
User.php
That is when model argument feature can come in.
we could use
HasArgAttribute
to pass coordinates to the user model.Retrieving users with calculated distance from auth user using
HasArgAttribute
same feature could be used with relationships
Please could this be a useful feature in the laravel framework? @themsaid and everyone else.
Beta Was this translation helpful? Give feedback.
All reactions