Skip to content
Advertisement

Laravel only one friend_id per user

I’m only starting with laravel and was wondering if anyone could help, I’ve created a friend_id and user_id from the database and have made a form in the view that adds the user_id to the friend_id (not sure what the terminology is for anything yet XD) everything working fine but each time I press the add friend button the friend user duplicates, so my question is how do I add a user without the user duplicating data?

FriendsController

JavaScript
JavaScript

This is what my boss suggested and it works to only add one friend id in the database at all

JavaScript

Advertisement

Answer

you can do this easily with a firstOrCreate :

JavaScript

But the logic is quite a bit wrong,

as I guess, your friends() relation on the User Model refer to a pivot table between 2 users (sort of)

You should just do this :

Pivot table :

id | user_id | friend_id

User Model :

JavaScript

then in your controller :

JavaScript
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement