Using Laravel with Ajax to retrieve complete data from a joined table

When attempting to retrieve the name from the 'users' table, the entire user object is being returned in the network tab. This leaks private information such as phone numbers which are stored in the users table.

Here is the Admin Model:

class Admin extends Model
{
    protected $appends = ['name'];
    public function user()
    {
        return $this->belongsTo('App\User');
    }
    public function getNameAttribute()
    {
        return $this->user?$this->user->name:'';
    }
}

The Admin Controller looks like this:

    public function ajaxLoadAdmins (Request $request)
    {
        $query = Admin::select('admins.slug', 'admins.about')->paginate(10);
        return $admins;
    }

However, when calling this function using ajax/axios, it returns the full user object along with the name and all columns of the users table.

I also attempted to simplify the code by not using accessors/mutators, but even with the following code the user object is still present when viewing in the network tab or logging it in the console...

  public function ajaxLoadAdmins (Request $request)
    {
        $query = Admin::select('admins.slug', 'admins.about', 'users.name')->leftjoin('users','admins.user_id','=','users.id')->paginate(10);
        return $admins;
    }

Answer №1

When working with Laravel, utilizing includes can lead to clunky code, unnecessary extra columns, and potential duplicate models in one-to-many relationships. Instead, consider using the "with" method, which eagerly loads your relationship and transforms it in the response.

Admin::with('user')->paginate(10);

By implementing this approach, your admin model will have a clear structure, and the username will effortlessly be included.

{
    "slug": "admin",
    "about": "interesting",
    "user": {
        "name": "John doe"
    }
}

If you wish to hide certain transformed properties on your model, you can do so by updating your User.php model with the following:

class User {
    protected $hidden = ['phone'];
}

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

The checkboxes seem to be malfunctioning following an ajax request

I've been attempting to utilize ajax to load data, but for some reason the checkboxes aren't functioning. Below is the HTML I'm trying to load via ajax: <div class="mt-checkbox-list" > <?php foreach($product_offerings as $row){ $c ...

Creating a dynamic table using JQuery to display data from a JSON object with a flexible number of fields

Dear all, I must apologize for any messy coding errors as this is my first attempt at something like this and I am learning on the go. I am currently working on using JQuery's $.each() method to iterate through a JSON object retrieved via an Ajax cal ...

What is the best way to toggle a sticky footer menu visibility using div elements with JavaScript instead of relying on pixel measurements?

Just wanted to mention that I'm pretty new to this, so if I use the wrong terms, I apologize in advance. I am trying to replicate Morning Brew's sticky footer opt-in form (check it out here). However, the code I have now only tracks pixels. Is t ...

To ensure the smooth functioning of a React application running on a Docker container in Ubuntu 16.04, it is

I'm currently in the process of setting up a docker container for running a react app that sends a fetch request to another docker container containing a node server. The deployment is on Ubuntu 16.04, however, after building and deploying the contain ...

When using Node.js with Express and ssh2, my data structures remain intact without any resets when loading web pages

To display jobs sent by users to a cluster, the code below is used (simplified): var split = require('split'); var Client = require('ssh2').Client; var conn = new Client(); var globalRes; var table = [["Head_1","Head_2"]]; module.exp ...

Guide to adding a new font to your Ember project

I am currently in the process of developing a website utilizing the MEEN Stack framework (Mongo, Ember, Express, Node). One challenge I am encountering is importing the Lato font family into my project to serve as the main font for the entire site. Despite ...

Using vue-select: In VueJs, how to pass an option slot from a grandparent component

Utilizing a custom dropdown component called 'vue-select', there is an option to customize the options view using slots as detailed in this documentation -> https://vue-select.org/guide/slots.html I am aiming to achieve a similar customizatio ...

Issue with Vue styles not loading in production when using Rails/Webpacker

I recently upgraded my Rails app to use webpacker 4.x and encountered a strange issue. While everything works fine in development, the styles of Vue single file components are not rendered in production. Surprisingly, the JavaScript works perfectly, and ev ...

PHP function that utilizes the header("X-sendfile") to return an image may display null during the initial iteration, but will successfully return the binary file on the subsequent iteration

My current project involves a gallery app with thumbnails that fetch the original images via an AJAX call to showfile.php. The first return works fine, but subsequent calls result in incorrect values and script breakage (initially returns "null," then bina ...

Is it possible to pass parameters using getters in Nuxt?

When attempting to pass the ID using $route.params.id in my getters method, it's not functioning as expected. Within my component, I have an object called blogs; I would like to store this.$route.params.id in blogId and then utilize it in my getters ...

Implementing automatic table row updates triggered by events in Rails with the use of AJAX

Currently, I am working on a Rails application with the following brief: Users are able to edit data in an HTML table (using JavaScript and AJAX calls). I would like for other users to see the updated information in real time when a cell is edited and sa ...

Sending complex data types like IEnumerable models to a controller in ASP.NET MVC

I need to make changes to a view where a set of images related to a specific album can be edited by updating their descriptions and setting them as the cover photo. EditImageViewModel.cs public class EditImageViewModel { public int ImageId{get;set;} ...

What is the best way to send various parameters to a component using [routerLink] or router.navigate?

My app-routing.module.ts is configured as shown below: const routes: Routes = [ { path: "branches/:branch", component: BranchesComponent }, // ... ]; In addition, in my app.component.html, I have the following code: <li> ...

Utilizing D3 for translation by incorporating data from an array within d3.js

I need assistance with drawing rectangles in an SVG where the translation data is stored in an array. Below is the code: var vis=d3.select("#usvg"); var rectData=[10,21,32,43,54,65,76,87,98,109]; vis.selectAll("rect").data(rectData).enter().append("rect ...

Combining component attributes with a mixin in Vue 2 using TypeScript

In my Vue + TypeScript project, we are utilizing Vue class components. Recently, I moved one of the component's methods to a separate mixin that relies on the component's properties. To address TypeScript errors regarding missing properties in th ...

The website encountered an error in loading with the error message "ENOTFOUND" in Cypress

All my cypress tests were running smoothly until one day they all failed to visit the target site. The error message that I received was: cy.visit() failed trying to load: https://mywebsite.com/accounts/login/ We attempted to make an http request to this ...

Having trouble retrieving the last 50 photo posts in large sizes through the Tumblr API

I have almost achieved my goal, but it seems like I am overlooking a key element. Below is the snippet of my code: $.ajax({ url: "http://api.tumblr.com/v2/blog{my-blog}/posts?limit=50", dataType: 'jsonp', data: { api_key: "{my k ...

The request to http://localhost:5000/error resulted in a 404 (Not Found) error message. I encountered difficulties connecting

When attempting to retrieve information about a product from Amazon using their productId with Express.js and ScraperAPI, an error is encountered: Error message: "{name: "RequestError", message: "Error: Invalid URI "${baseUrl}&url=https://www.amazon.com/d ...

Error message: The line chart in angular-chartjs is encountering an issue with the function t.merge not

I am currently working on implementing a line chart example from the following source: . However, I am encountering an error and would appreciate any guidance or pointers to resolve it. Here is the error displayed in the console. Below is the code snippe ...

Grid prefixes are not being added by Autoprefixer for Internet Explorer

I'm currently working with vue-cli version 3.x. After creating a vue.config.js file: const prefixer = require("autoprefixer"); const plugin = prefixer({ grid: true }); module.exports = { configureWebpack: config => { // Locate the scss rule ...