Currently I have a relation between a location and a state. So a location belongs to one state and a state can have many locations.
I have set up the relation correctly:
class Location extends Model
{
public function state(): BelongsTo
{
return $this->belongsTo(State::class);
}
}
Of course the location model has a foreignId column named state_id and all tables and columns follow the name conventions.
When I now want to create a relation I have two options. Option one is to use the "official" way with associate:
$state = State::where(['short'=>'AUT'])->first();
$location = new Location();
$location->name = 'Vienna';
$location->state()->associate($state);
$location->save();
There is also the more basic way (which is not recommended but still working):
$state = State::where(['short'=>'AUT'])->first();
$location = new Location();
$location->name = 'Vienna';
$location->state_id = $state->id;
$location->save();
Wouldn't it be much easier to make this more straightforward and let Laravel automatically detect if an association is needed?
It would be much easier if I could do this:
$state = State::where(['short'=>'AUT'])->first();
$location = new Location();
$location->name = 'Vienna';
$location->state = $state;
$location->save();
but this method is not working and will result in an error saying that column state does not exist.
What do you think: Is this something which would be useful? Should I create a feature request?