Display individuals based on their location using "location_user" in Laravel 8

I am encountering an issue when it comes to displaying users based on locations.

The problem lies in the fact that it only shows the user and not the users associated with the locations.

What I desire is for the user to see only the users located in the places linked in the 'location_user' table.

I acknowledge that the issue stems from 'location_user', 'location_user.user_id', '=', 'users.id'

However, I prefer a solution that is more intelligent and does not involve adding a column named location_id to the user list

This is because I require support for multiple locations

This pertains to the data in UsersController.php

$data = User::leftjoin('location_user', 'location_user.user_id', '=', 'users.id')
->where('location_user.user_id', auth()->user()->id)
->leftjoin('locations', 'locations.id', '=', 'location_user.location_id')
->where('locations.status', '1')
->select('users.*',)
->orderBy('status', 'DESC')->get();

Tables

users: https://i.sstatic.net/h3dID.jpg

location_user: https://i.sstatic.net/6KGZN.jpg

locations: https://i.sstatic.net/UDbDJ.jpg

Can someone assist me with this challenge?

Thank you.

Answer №1

According to the structure of your table, there exists a many-to-many relationship between User and Location through the intermediary table named location_user.

If the relationships are defined on both models as follows:

//User Model
public function locations()
{
    return $this->belongsToMany(Location::class);
}
//Location Model
public function users()
{
    return $this->belongsToMany(User::class);
}

You can then create a query to retrieve all users associated with the locations of the currently logged-in user.

$locationIds = auth()->user()->locations->pluck('id');

$users = User::query()
    ->whereHas('locations', fn($query) => $query->whereIn('id', $locationIds)
    /** If you want results to include the currently logged in user
      * remove the below where condition **/
    ->where('id', '<>', auth()->id())
    ->get();

Alternatively, you can use conventional anonymous closure functions instead of arrow function syntax like this:

$locationIds = auth()->user()->locations->pluck('id');

$users = User::query()
    ->whereHas('locations', function($query) use($locationIds){
        $query->whereIn('id', $locationIds);
    })
    /** If you want results to include the currently logged in user
      * remove the below where condition **/
    ->where('id', '<>', auth()->id())
    ->get();

Answer №2

Initially, there is no need to link the "location_user" table because each user is connected to only one location. This implies a ManyToOne relationship, which can be established by adding the following code to your models:

class User extends Model
{
    // Add this line
    public function location()
    {
        return $this->belongsTo(Location::class);
    }
}

class Location extends Model
{
    // Add this line
    public function users()
    {
        return $this->hasMany(User::class);
    }
}

Once that is done, you can retrieve all members within a user's location using their id like so:

$user = User::find(1); // Find user with id 1
$location = $user->location; // Get location associated with user id 1 

$members  = $location->users; // Retrieve all members linked to the location of user id 1 

In case of a ManyToMany relationship, you can still apply the same approach by making the following modifications:

  /*
public function location()
        {
            return $this->belongsTo(Location::class);
        }
*/

Change it to:

  public function locations()
        {
            return $this->belongsToMany(Location::class,'location_user');
        }

and:

  /*
public function users()
        {
            return $this->hasMany(User::class);
        }
*/

Change it to:

  public function users()
        {
            return $this->belongsToMany(User::class,'location_user');
        }

You can then combine the members using collection methods: Collections Or utilize whereHas and orHas for more complex queries.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Refresh the Morris chart using jQuery after a .NET MVC post request

In my .NET Controller action, I have written code to fetch specific time zone and group data based on that time zone. The code looks like this: [HttpPost] [ActionName("FetchTimeZone")] public ActionResult FetchTimeZone(string timeZone) ...

Excluding form items that are disabled from a request in ReactJS

In my code, I am dealing with a Form section that contains multiple Collapse.Panel sub-sections. Interestingly, the Form.Item elements within collapsed panels are not included in the form values upon submission. However, I have noticed that certain InputNu ...

Resetting clears the date default value

When the page is loaded, the date input field is automatically set to the current date. However, if the form is reset, instead of restoring the default date, the date field is cleared, as shown in the images below: Page load Form reset // app.component. ...

Issue with Firebase Storage: Invalid character detected in the string format 'base64'

I am currently developing a project using react-native and I am facing an issue with uploading an image to Firebase using Firebase Storage. To select the image from the phone, I am utilizing react-native-image-picker, which provides me with the base64 enco ...

What is the best way to access and modify a nested object within a complex object containing an array of objects?

I've got the course structure all sorted out, but I'm struggling to understand how to retrieve a lesson object by its ID and also update a lesson object with new property values. If anyone could provide some guidance on the right approach, it wo ...

Guide on integrating donut charts using ChartJS in CodeIgniter 3 to showcase database information

Struggling to integrate a doughnut chart into my CI3 application with ChartJS for the first time, but facing some challenges. My Attempts -PHP public function get( $data ) { if ( $this->input->is_ajax_request() ) { $this->load->l ...

Issue with displaying checkboxes in the dataTable table

I am currently working with dataTables and encountering difficulties displaying checkboxes on my tables. Below is the code that I have: <table id="employeeList" class="table table-sm table-bordered table-hover" cellspacing="0" width="200%"> &l ...

Creating a dynamic HTML table using Vue 3

My table is not showing the data I'm fetching from my API. Even though I can see the data in my console.log, it's not populating the table. Could there be an issue with how I'm calling the data to display in the table? <template> < ...

Error: The function react__WEBPACK_IMPORTED_MODULE_6___default.a.useState is not defined as a function

Hey there! I have been working on some ReactJS code using material-ui, but it seems like I made a mistake with the placement of function handleClickOpen() and function handleClose(). Unfortunately, now my code doesn't compile. Can you help me fix it? ...

Unable to access the internal function of an Angular controller

My goal is to invoke the inner function of an Angular controller. index.html <script type="text/javascript> $(document).ready(function() { $('#example').multiselect({ onChange: function(option, checked, ...

The JsonLint tool has detected an Invalid Json Error

I am currently dealing with a web service that is returning the following JSON data: [ { "id": "9469", "title": "A person grabbed by police because of carrying a Ghanaian passport while being Nigerian!", "introtext": "A person ...

Issues with the functionality of the asynchronous socket.io JavaScript callback are being experienced

I am facing an issue with my JavaScript code that involves querying data from a database using Node.js and Socket.io. Currently, I have implemented setTimeout() functions to make it work, but I want to switch to using callbacks for better reliability. Howe ...

Using JSON for serialization in ActiveRecord instead of YAML

I'm working with a model that has a serialized column: class Survey < ActiveRecord::Base serialize :data, Hash Is it possible to change the serialization format from YAML to JSON? ...

Major processing glitch detected in JSON and PHP data handling

I am facing an issue with my PHP page that requests data from another page using JSON. Currently, I have an AJAX call set up like this: $.ajax({ type: "POST", url: "getdata.php", cache:false, data:"lis ...

Click automatically upon loading the page

I'm looking for help to automatically click a button after the page loads. I currently have to manually click the "Buy the basket" button, but I am not familiar with coding at all. I need a fully ready code that can automate this process for me. Can s ...

What could be causing the issue with my custom AlloyEditor UI extension?

After following the instructions in this guide to integrate alloyeditor as a WYSIWYG editor into Contentful, I successfully added the extension to my contentful staging space. However, despite copying the html page from the github repository and includin ...

"Trouble with jQuery not being triggered when there is a string in

New to the world of MVC and diving into jQuery for the first time, I am faced with a challenge. My goal is to populate text boxes in a partial view using jQuery that is placed within the parent view. Here are the relevant sections of the parent view: @ ...

Is it possible to create a "text carousel" using HTML, CSS, and JavaScript?

Currently, I am in the process of building a 'text carousel' on my own, without seeking assistance. The progress so far can be viewed here (please stretch it out, as it is not responsive yet). Specifically, I am aiming to replicate the text carou ...

Shift the sleek navigation arrows to the interior of the slides

Is there a way to relocate the navigation arrows on the slider images? I have tried various methods found online with no success. Currently using ASP.NET, but doubt it matters. Employing the latest version of SLICK. Here is the HTML code snippet: <%@ ...

Can you explain the compatibility between comet and PHP?

As I utilize Comet iframe, I simply send script tags from the backend PHP file to the frontend where JavaScript displays them. I would appreciate it if someone could provide a concise explanation of how the comet server fits into the equation and how comm ...