Alexander Solonik
Alexander Solonik

Reputation: 10260

unable to convert JSON object to associative array in laravel method

I have the following function in my controller:

public function index() {
        $tags = DB::table('Tags')->get();
        $tagsArray = array();
        foreach($tags as $tag) {
            $tagsArray[$tag->id] = $tag->tag; 
        }

        $tagsArray = json_decode(json_encode($tagsArray) , true);
        return $tagsArray;
}

Now i need to pass $tagsArray as an array to my view but even though i am following the below step:

    $tagsArray = json_decode(json_encode($tagsArray) , TRUE);

I don't get an associative array , instead the data i get is as follows:

{"1":"javascript","2":"browser-bugs"}

What am i doing wrong ??

Upvotes: 1

Views: 699

Answers (3)

Morteza Sepehri Niya
Morteza Sepehri Niya

Reputation: 414

public function index() {
    $tags = DB::table('Tags')->get();
    $tagsArray = array();
    foreach($tags as $tag) {
        $tagsArray[$tag->id] = $tag->tag; 
    }
    $tagsArray = json_decode(json_encode($tagsArray) , true);
    return $tagsArray;
}

Upvotes: 0

Jerodev
Jerodev

Reputation: 33216

Returning an array directly from the controller will always result in a json object. Laravel automatically converts a php array to json for outputting: https://laravel.com/docs/5.3/responses#creating-responses

You have to add this value to a view, preferably by using the view helper. Like so:

return view('home')->with(['tags' => $tagsArray]);

Upvotes: 3

Alexey Mezenin
Alexey Mezenin

Reputation: 163978

You can change all your code to this:

public function index() {
    $tags = DB::table('Tags')->pluck('tag', 'id')->toArray();
    return view('some.view, compact('tags'));
}

This will return an array with [1 => 'Javascript', 2 => 'browser-bugs'] structure.

Upvotes: 2

Related Questions