I am trying to check if a user has already liked a place so I need to check if there is already a record in the Place_User
table. However, as of now I have not created a model for the intermediate table. I wouldn't even know how to name the model. Would Place_User make sense for a model name?
I have the following 3 tables:
Table: Users
Columns: id, username, password
Table: Places
Columns: id, place_id
Table: Place_User
Columns: id, user_id, place_id
I also have the 2 following models:
class User extends \Eloquent implements Authenticatable
{
use AuthenticableTrait;
public function places(){
return $this->belongsToMany('App\Place');
}
}
And
class Place extends Model
{
public function user(){
return $this->belongsToMany('App\User');
}
}
You don't need an extra model for a many to many relationship. You can easily check if the user already liked the place like this:
User::find(1)->places->contains($placeId);
// or
User::find(1)->places()->where('place_id', $placeId)->exists();
You can add method for pivot table in User
model as, belongs to many should work for your case:
public function user_places()
{
return $this->belongsToMany('App\Place', 'place_user',
'user_id', 'place_id');
}
I recommend using plural names of table to better readability to laravel.
Yes, you should create models for pivot tables. Dangling tables with no associated models are not really my choice. Naming them can be a bit tough though, I would suggest UserPlaces
for the sake of simplicity.
Why you should create models? So that you could define 2 relationships in the UserPlace model
So in future, it's easy to navigate through relationships from the pivot table itself. Even though you won't be touching the pivot model/table directly most of the time.
Recents version of Laravel 5.8 provide doc on the subject: https://laravel.com/docs/5.8/eloquent-relationships#defining-custom-intermediate-table-models
But I don't think that pivot table should have a model.
Models represent your app Entities. Pivot tables are just there to store relations between entities.
If you just need to check existence of relation, there already are required tools :
$hasPlace = User::find(1)->places()->where(/* ... */)->exists();
If you really need Model for your pivot tables, it is possible, but I believe that in most cases you need to rethink your DB shema.