How to convert JSON to array in Laravel?

In this tutorial explained of how to convert json to array in laravel. I explained simply about how to convert json into array in laravel. If you have a question about laravel convert json to array then i will give a easy example with a best solution.

There are many different method to convert JSON data into an array in laravel. In this example, i will give you various method to convert JSON data into a array. In the first example, we will use json_decode() and in the  so let’see example below.

1. Convert json to array in laravel using json_decode()
Example

$json_data = '[
            {"id": 1, "type" : "test", "range" : "1"},
            {"id": 2, "type" : "testing", "range" : "2"},
            {"id": 1, "type" : "testuser", "range" : "3"},
]';

$dataArrar = json_decode($json_data, true);

    dd($dataArrar);
Output:
Array
(
    [0] => Array
        (
            [id] => 1
            [type] => test
            [range] => 1
        )
    [1] => Array
        (
            [id] => 1
            [type] => testing
            [range] => 1
        )
    [2] => Array
        (
            [id] => 1
            [type] => testuser
            [range] => 1
        )
)
2. Example in a blade template

If you want to convert JSON to an array and use it in blade template, you can do it like this

Controller:

<?php
namespace App\Http\Controllers;

use Illuminate\Http\Request;

class TestController extends Controllers
{
    public function showJsonData() 
    {
        $json_string = '{"id" => 1, "type" => "usertest", "range" => 1}';
        $arrayValue = json_decode($json_string, true);
        
        return view('json_show', ['data' => $arrayValue]);
    }
}


?>

Blade Template  json_show.blade.php

<!DOCTYPE html>
<html>
<head>
    <title>Json To Array</title>
</head>
<body>
    <h1>Json to Array Conversion</h1>
    <ul>
    @foreach($data as $key => $value)
        <li>{{$key}}: {{$value}}</li>
        @endforeach
    </ul>
</body>

</html>

I hope this tutorial help you.

Leave a Reply

Your email address will not be published. Required fields are marked *