Let's say i have three models User Post and Comment and linked like so:
class User extends Model
{
public function posts(): HasMany
{
return $this->hasMany(Post::class);
}
}
class Comment extends Model
{
public function post(): BelongsTo
{
return $this->belongsTo(Post::class);
}
}
class Post extends Model
{
/**
* Get the comments for the blog post.
*/
public function comments(): HasMany
{
return $this->hasMany(Comment::class);
}
}
and i wanted to associate a post to comment, i would do:
$comment->post()->associate($post);
but if i mistakenly pass a different model to the associate function:
$comment->post()->associate($user);
then it will still work, it will associate the post that has the same id of the passed user, which is wrong.
basically the associate function doesn't check the type of the model that was passed before associating, is there something that can be enabled so that laravel checks the type of the model before associating?
The
associatemethod does not check for types nor do a parameter type-hinting, and it's expects a Model instance, string, int or null as shown:Basically, you must take care of this by yourself, as this is not a user input, so it's easy to make sure that you are passing the right parameters.
Otherwise, you will need to do a redundant work -IMO- to handle this.
First, you will override the
belongsTomethod in your model that returns the newBelongsToclass (in the next step).Secondly, you will need to create a shadow version of the
BelongsToconcern, most likely you will inherit theIlluminate\Database\Eloquent\Relations\BelongsToand override theassociatemethod to type hint your parameter, give it a proper name, let's sayCommentsBelongsToor something.The final class would something like: