Data Recovery Problem in a Portable Application

Asked

Viewed 210 times

2

My table is as follows:

╔════════════════════════╗
║        USER            ║
╠═══════════╦════════════╣
║ Id        ║ Integer    ║
║ Name      ║ String     ║
║ Address   ║ String     ║
╚═══════════╩════════════╝

I have some data already recorded in the database, Exp:

╔═══════════╦═══════════╦═══════════════╗
║ Id        ║ Name      ║ Address       ║
╠═══════════╬═══════════╬═══════════════╣
║ 1         ║ Marcelo   ║ Rua A         ║
║ 2         ║ Ferdinand ║ Rua B         ║
║ 3         ║ Marcelo   ║ Rua A         ║
╚═══════════╩═══════════╩═══════════════╝

In my controller I have the following method:

public function getListUsers()
{
    $users = DB::table("users")->pluck('Name','Address');
    echo json_encode($LatLng);
    return;
    // return response()->json($users);
}

When I display the route that invokes the controller function, the following array is displayed:

{"Marcelo":"Rua A","Ferdinand":"Rua B"}

I even tried to execute the following:

    DB::enableQueryLog();
    $users= DB::table("users")
                ->pluck("name","address");
    print_r(
        DB::getQueryLog()
    );

In the log, the executed select is the following:

 select `user`, `address` from `user`

And if I run the same select in my database, bring me the correct data, which should be something like:

[{"name":"Marcelo","Address":"Rua A"},{"name":"Ferdinand","Address":"Rua B"},{"name":"Marcelo","Address":"Rua A"}]

1 answer

3


You are using the wrong function. After running the query in the database, the function pluck will transform your result as a array where the first field is the value and the second is the key.

$collection = collect([
    ['product_id' => 'prod-100', 'name' => 'Desk'],
    ['product_id' => 'prod-200', 'name' => 'Chair'],
]);

$plucked = $collection->pluck('name');

$plucked->all();

// ['Desk', 'Chair']

For what you want to do, use select() and get()

$users = DB::table("users")->select('Name','Address')->get();

return response()->json($users);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.