From the course: Laravel Essential Training
Unlock the full course today
Join today to access over 25,100 courses taught by industry experts.
Query and save relationships - Laravel Tutorial
From the course: Laravel Essential Training
Query and save relationships
We have now defined our one to many relationship in user model, and the inverse relationship belongsTo in note model. Now it's time to make use of these relationships for querying models. Open NoteController. NoteController. In the index method, we use this 'where' clause to get all the notes of the authenticated user. Now, we can simply replace this with auth::user()->notes like so, and this can be removed. And here you will see an error, but this is actually not an error. It's just the editor that is showing it. IntelliSense is not able to understand this. You can ignore this. Notice how we are able to fetch the notes that belong to the authenticated user using the relationship. Let's go to the browser and see if this works. And yes, we are able to see the notes exactly as before. And now since Laravel version 8, we can also use the inverse relation and replace this with Note::whereBelongsTo authenticated user, Auth::user(), get the latest, and so on. Now see how similar this is to…