Lwin Maung Maung

My Notes and Blogs

Home Laravel Linux
<-

Laravel Personalized Relationships

Published on  Feb 29th, 2024Updated:  May 23rd, 2024
2 mins Read

Laravel has a set of tools for database connectivity, database query or Eloquent ORM. We use nested relationships, especially the database queries specific to logged-in users.

Laravel Relationships - avoid nested Relationships

What is the user?

    The user may be a student or a business with access to the system. In this case, we will refer to who will get the data from our system.

Why does the user need to be focused on our system?

   The user is necessary for the system information retrieval process. The user will get his bills, courses and even profile information. If we search using the data, the leaks will happen.
    For example, the user A has invoice #1, #2 and #3, and the user B has invoice #4,#5 and #6, etc. When we look for the invoice, we look at the relationship between the user and the invoice. If we focus on the invoice instead of the user, another invoice related to other users will leak to the logged-in user.

Example Scenario:
    The user has to find the billing invoices. If you allow the user to read the Inovice, you need to list the Inovice using the user<->invoice relationship, like $user->invoices. If we get the data using $invoice->where(user_id,1)->get();, you will get some data leaked from other users.

When will the data leak?

    The data will leak when the invoice details are coming up. If you find the invoice using $user->invoice, the data will get empty if the invoice does not belong to the user. If you find the invoices with the $invoice->where()->get(); query, the query will bring everything when you make some mistakes.

How can I avoid nested relationships?

    The best way to avoid nested relationships is to add a foreign key for the resource owner. This solution will prevent both nested data and leaks for better productivity.
 

© lwinmaungmaung MMXXIII. All Rights Reserved.