How can Angular be used to fetch the name associated with a user_id in Laravel?

There seems to be a problem with fetching the name attribute along with the title and body attributes. The name appears empty on page refresh but shows up automatically upon submission.

Interestingly, is unable to retrieve the name successfully.

Please note: This issue is occurring while using .

Here is an example scenario:

Server side implementation:

PostController

public function getPosts() {

  $posts = Post::with('user')->get();
  $response = new Response(json_encode($posts));
  $response->headers->set('Content-Type', 'application/json');
  return $response;
}

public function storePost(Request $request) {
  $data = request()->validate([
    'title' => 'required|max:120',
    'body' => 'required|max:1000'
  ]);

  $data['user_id'] = auth()->user()->id;
  $data['name'] = auth()->user()->name;

  $post = Post::create($data);

  $response = new Response(json_encode($data));
  $response->headers->set('Content-Type', 'application/json');

  return $response;
}

Main.js

$scope.myposts = {};

$scope.addPost = function() {

  $http.post('/auth/post', {
    title: $scope.post.title,
    body: $scope.post.body

  }).then(function(data, status, headers, config) {
    console.log(data);
    $scope.myposts.push(data.data);

  });

  $scope.post.title = '';
  $scope.post.body = '';

};

$scope.deletePost = function(post) {
  var index = $scope.myposts.indexOf(post);

  if (index != -1) {
    $scope.myposts.splice(index, 1);
  }

  $http.delete('auth/post/' + post.id);
};

$scope.getPosts = function() {

  $http.get('/auth/posts').then(function(data) {
    $scope.myposts = data.data;
  }).then(function(data, status, header, config) {});
};

HTML:

<div id="mypost" class="col-md-8 panel-default" ng-repeat="post in myposts">
  <div id="eli-style-heading" class="panel-heading">
    <% post.title %>
  </div>
  <div class="panel-body panel">
    <figure>
      <p>
        <% post.body %>
      </p>
      by:
      <p>
        <% post.user.name %>
      </p>

    </figure>
    <span><button ng-click="deletePost(post)">x</button></span>
  </div>
</div>

When adding content without refreshing asynchronously,

Upon page refresh,

Above logs may differ based on the post.

Answer №1

Your page reload function is functioning correctly because

$posts = Post::with('user')->get();

produces the following JSON response:

{
    "title": "title",
    "body": "body",
    "user":  {
        "name": "name"
    }
}

In your AngularJS code, you are displaying the user's name with:

<% post.user.name %>

To display this information after adding a new post, you need to restructure the JSON object before pushing it to the array in your controller:

$scope.addPost = function() {

  $http.post('/auth/post', {
    title: $scope.post.title,
    body: $scope.post.body

  }).then(function(data, status, headers, config) {
    console.log(data);

    data.data['user'] = {
        name: data.data.name
    }

    $scope.myposts.push(data.data);

  });

  $scope.post.title = '';
  $scope.post.body = '';

};

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

When using a file uploader to set an image on v-model in Vue JS, it sometimes results in

I am currently using Vue JS 2 to develop an image uploader functionality. The input in question has a change function that triggers a function and sets the selected file to the v-model property. After logging the data, I noticed that only an empty object ...

Ways to convert a PHP array into a JavaScript array

I have a 3D array in php when using var_dump($arr) it looks like this array(2) { [0]=> array(4) { [0]=> array(2) { [0]=> string(7) "36.3636" [1]=> int(8) } [1]=> array(2) { [0]=> string(7) "27.2727" [1]=> int(5) } [2]=> a ...

The repetition of regex patterns and the presence of ng-invalid

Here's the pattern I'm using: <input name="ip" ng-pattern="/^http:\/\/[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+:[0-9]{4,5}/" class="form-control full-width text-right" type="text" ng-model="resource.ip"/> The {4,5} part spec ...

Getting the value of a sibling select element when a button is clicked

Trying to retrieve the selected option value on button click has become a challenge due to multiple groups of buttons and select elements. The key seems to be using siblings somehow, but the exact method remains elusive... <div class="form-group" ng-re ...

AngularJS controller exceeding allowed complexity (SonarLint alert)

While utilizing SonarLint in Eclipse, I encountered an issue while working on an AngularJS application. Specifically, I was cleaning up a controller to improve readability when SonarLint flagged the following problem: The function has a complexity of 11 ...

AngularJS - Triggering functions on image load event

I have been on a quest to find the best way to handle the onload event for images in Angular using jqLite. I came across this question, but I am looking for a solution that involves directives. Therefore, the approach below is not satisfactory to me: .c ...

Troubleshooting: Unable to Sort Column in ngx-DataTable Angular 4

As a newcomer to Angular, I have been encountering some challenges while using ngx-DataTable. I am currently utilizing a simple ngx-DataTable for basic operations. The issue I am facing is that the sorting functionality is not working on a specific column, ...

Continuously converting methods recursively until the array is fully processed

My current code has a method that is not very efficient and does not scale well. The object y is an array consisting of key/value pairs, each containing two properties: 1. A unique string property called name. This value is identified by the childre ...

Using jQuery to duplicate elements by copying and pasting

I am facing a scenario where I need to dynamically create and manipulate a div element in my web application. The process involves appending the newly created div to another container upon clicking a button, followed by triggering a series of functions on ...

Effortlessly find data in an HTML table and showcase the results instantly without

I am looking for a way to implement search functionality in my table without refreshing the page. The fields above the table are used for searching and I want the results to be displayed within the same table. Here is an example of the code: <?php $for ...

Contrasting the lib and es directories

I am seeking clarity on my understanding. I am currently working with a npm package called reactstrap, which is located in the node_modules folder. Within this package, there are 4 folders: dist es lib src I understand that the src folder contains the s ...

Filtering JSON data by nesting checkboxes in an AngularJS application

Trying to create a nested filter search in Angular with JSON data. Seeking assistance from the community since I am new to this and encountering difficulties. ...

Issue in Next.js 13: Byte index exceeds limits when running 'npm run dev' command

When attempting to install Next.js 13.4.12, I utilized the command npx <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="385b4a5d594c5d15565d404c1559484878090b160c1609">[email protected]</a>. The installation process ...

jquery button returned to its default state

Jquery Form Field Generator |S.No|Name|Button1|Button2| When the first button is clicked, the S.No label and name label should become editable like a textbox. It works perfectly, but if I click the second button, the field becomes editable as expected, ...

Encountered SyntaxError: An unexpected token has been found while integrating leaflet with flask

Despite adding all necessary scripts and configuring my API_KEY in config.js, I keep getting an error message saying "Uncaught SyntaxError: Unexpected token." I have double-checked my API key multiple times, and it seems to be correct. Here is a snippet f ...

Notification of failed fetch in backbone

We are experiencing a problem with our backbone application. Our goal is to show a notification to the user when a fetch fails (due to timeout or general error). Instead of displaying an error message on a new page, we want to overlay a dialog on top of th ...

Iterate over the array and show the elements only when a click event occurs

I am trying to create a loop through an array (array) and display the elements one by one only after clicking a button (bt). However, when I run this code, it only shows the last element of the array (i.e. honda). Can someone please help me fix this issu ...

The radar chart created with amchart.js disappears when placed within bootstrap columns

I'm encountering an issue while trying to display radar charts using amchart.js in bootstrap columns. The "amStockGraph" charts render perfectly, however, the radar charts appear blank with no errors in the console. Any advice on this matter would be ...

What could be the reason behind Strapi v4 only displaying the initial 25 articles? Discussing Next.js and React

I've encountered a peculiar bug while working with Strapi v4. The technology stack being used is React and Next.js I've set up a dynamic pagination system with the format /page/[slug]. It's functioning almost perfectly, except for one majo ...

What is the best way to search for a CSS selector that includes an attribute beginning with the symbol '@'?

Whenever I want to target an element with a click event, I usually use the following jQuery selector: $('div[@click="login()"]') <div @click="login()"> Login </div> However, when I tried this approach, it resulted ...