Nil the babe
Nil the babe

Reputation: 35

How to read response api json in laravel view

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

Upvotes: 1

Views: 2950

Answers (3)

Salman Zafar
Salman Zafar

Reputation: 4035

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..

Upvotes: 1

Akbar Soft
Akbar Soft

Reputation: 1066

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)
    }
}

Upvotes: 1

Teoman Tıngır
Teoman Tıngır

Reputation: 2866

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();
}

Upvotes: 1

Related Questions