1

h-e-l-l-o everyone

I received this response

enter image description here

now I want to use foreach in my View file to show all of the users

this is my Controller Functions:

public function ShowUserList()
{
    return response()->json(User::all(), 200);
}

public function ShowUser()
{
    $users = $this->ShowUserList();
    return view('show_users', compact('users'));        
}

and when I render it in view I received the response that I uploaded on top

1
  • May I ask, if you want to use it in foreach loop, why you're trying to send json data? Commented Oct 8, 2018 at 9:26

3 Answers 3

1

at the ShowUserList() method, you're not just getting json data also also you're trying to send a response..

public function ShowUserList()
{
    return response()->json(User::all(), 200);
}

so you need to change it like;

public function ShowUserList()
{
    return User->all()->toJson();
}
Sign up to request clarification or add additional context in comments.

1 Comment

thanks, Bro I need ShowUserList Method as API base code, so is "return User->all()->toJson();" API base?
1
if I understood your question , try like below code ...

//in your controller class..

public function ShowUserList()
{
    return response()->json([
                           'status_code'=>200,
                           'data'=>User::all(),
                           'error' => false
                         ]);
}

// in your view file..

var response = JSON.parse(response)
if(!response.error){
    for(var i=0; i<response.data.length; ++i){
         console.log(response.data[i].name+' '+response.data[i].email)
    }
}

3 Comments

thanks, Bro can you please edit your view code and change it to blade?
for example you code is js and I need to use it html with blade and use @foreach
how do you fetch data in your view file using javascript?
1

if i'm right you need to parse json in view.

public function ShowUserList()
{
    return response()->json(User::all(), 200);
}

public function ShowUser()
{
    $users = json_decode( $this->ShowUserList(), true );
    return view('show_users', compact('users'));        
}

so based on this in your view you can do this:

// now this is just an json object not array..

  {{ $user['id'] }}
  {{ $user['name'] }}

hope i helped you..

1 Comment

I got error bro,Cannot use object of type Symfony\Component\HttpFoundation\ResponseHeaderBag as array (View: /Users/lolek/Desktop/lolek/resources/views/ShowUser.blade.php)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.