Debug School

rakesh kumar
rakesh kumar

Posted on • Updated on

How to store and renders the data in json form using laravel

How to store data in jsonform

how to display json data in html from server data

how to convert $request->influencer_email appears to be a JSON-encoded string in associative array using json_decode
Difference between pluck and toArray()
Difference between toArray() and tojson
Difference between pluck,toArray(),json_encode() and json_decode()
Way to take for loop from laravel collection like pluck
How to display json data in key value pair format
How to retrive two field from table and store in json format in another table
How to display json data in blade file
How to display json data in nested td inside table in blade file
Display json data on popupmodal
Decode json response after get data using guzzle client

Database Migration
Create a migration to add the necessary columns in your table:

php artisan make:migration add_columns_to_example_table --table=example_table
Enter fullscreen mode Exit fullscreen mode

Edit the generated migration file:

// database/migrations/YYYY_MM_DD_add_columns_to_example_table.php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class AddColumnsToExampleTable extends Migration
{
    public function up()
    {
        Schema::table('example_table', function (Blueprint $table) {
            $table->json('social_media_data')->nullable();
            $table->string('name');
            $table->integer('id');
        });
    }

    public function down()
    {
        Schema::table('example_table', function (Blueprint $table) {
            $table->dropColumn('social_media_data');
            $table->dropColumn('name');
            $table->dropColumn('id');
        });
    }
}
Enter fullscreen mode Exit fullscreen mode

Run the migration:

php artisan migrate
Enter fullscreen mode Exit fullscreen mode

Step 2: Controller
In your controller, you can now use Eloquent to create a new record with the desired data:

use App\Models\Example;

class YourController extends Controller
{
    public function storeData()
    {
        $data = [
            'facebook' => 50,
            'twitter' => 30,
            'utube' => 80,
            'name' => 'ram',
            'id' => 2,
        ];

        $socialMediaData = [
            'facebook' => $data['facebook'],
            'twitter' => $data['twitter'],
            'utube' => $data['utube'],
        ];

        Example::create([
            'social_media_data' => json_encode($socialMediaData),
            'name' => $data['name'],
            'id' => $data['id'],
        ]);

        return response()->json(['success' => true, 'message' => 'Data stored successfully']);
    }

    // ... other methods
}
Enter fullscreen mode Exit fullscreen mode

============or=====================

  $users_id=$request->admin_id;
        $user_email=$request->admin_email;
        $user_name=$request->user_name;
        $myimage_trip = DB::connection('payments')
        ->table('addprofiles')->where('user_id',$users_id)->first();

        $country_id = $myimage_trip->country_id ?? '';
        $state_id=$myimage_trip->state_id ?? '';
        $city_id=$myimage_trip->city_id ?? '';
        $slug=$myimage_trip->slug ?? '';
        $mobile= $myimage_trip->mobile ?? '';

        $socialMediaData = [
            'facebook' => $input['facebook'] ?? null,
            'twitter' => $input['twitter'] ?? null,
            'youtube' => $input['youtube'] ?? null,
            'wordpress' => $input['wordpress'] ?? null,
            'tumblr' => $input['tumblr'] ?? null,
            'instagram' => $input['instagram'] ?? null,
            'quora' => $input['quora'] ?? null,
            'pinterest' => $input['pinterest'] ?? null,
            'reddit' => $input['reddit'] ?? null,
            'koo' => $input['koo'] ?? null,
            'scoopit' => $input['scoopit'] ?? null,
            'slashdot' => $input['slashdot'] ?? null,
            'telegram' => $input['telegram'] ?? null,
            'fb_grp' => $input['fb_grp'] ?? null,
            'linkedin_grp' => $input['linkedin_grp'] ?? null,
            'linkedin' => $input['linkedin'] ?? null,
            'roposo' => $input['roposo'] ?? null,
            'chingari' => $input['chingari'] ?? null,
            'mitron' => $input['mitron'] ?? null,            
        ];

        DB::connection('payments')->table('social_url')->updateOrInsert(
            ['user_id' => $users_id],
            [
                'social_site' => json_encode($socialMediaData),
                'user_email' => $user_email,
                'user_name' => $user_name,
                'country_id' => $country_id,
                'state_id' => $state_id,
                'city_id' => $city_id,
                'slug' => $slug,
                'mobile' =>  $mobile,
            ]
        );
Enter fullscreen mode Exit fullscreen mode

Image description

In this example, we create a new record in the example_table with the 'social_media_data' column containing the JSON representation of 'facebook', 'twitter', and 'utube'. The 'name' and 'id' fields are stored in separate columns.

data stores in format

{"facebook": 50, "twitter": 30, "utube": 80} 
Enter fullscreen mode Exit fullscreen mode

how to display json data in html from server data

jQuery in HTML
Create an HTML file and include jQuery to make AJAX requests:

<!-- public/index.html -->

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>JSON Data Example</title>
    <script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
</head>
<body>

    <button id="storeDataBtn">Store Data</button>
    <button id="getDataBtn">Get Data</button>

    <div id="output"></div>

    <script>
        // jQuery code to store and retrieve JSON data
        $(document).ready(function() {
            $('#storeDataBtn').click(function() {
                $.ajax({
                    url: '/store-data',
                    type: 'GET',
                    dataType: 'json',
                    success: function(response) {
                        alert(response.message);
                    },
                    error: function(error) {
                        console.error('Error:', error);
                    }
                });
            });

            $('#getDataBtn').click(function() {
                $.ajax({
                    url: '/get-data',
                    type: 'GET',
                    dataType: 'json',
                    success: function(response) {
                        if (response.success) {
                            renderData(response.data);
                        } else {
                            alert(response.message);
                        }
                    },
                    error: function(error) {
                        console.error('Error:', error);
                    }
                });
            });

            function renderData(data) {
                // Assuming 'data' is an object like {"facebook": 50, "twitter": 30, "utube": 80}
                var outputHtml = '<h3>Data:</h3><ul>';
                for (var key in data) {
                    outputHtml += '<li>' + key + ': ' + data[key] + '</li>';
                }
                outputHtml += '</ul>';

                $('#output').html(outputHtml);
            }
        });
    </script>

</body>
</html>
Enter fullscreen mode Exit fullscreen mode

how to convert $request->influencer_email appears to be a JSON-encoded string in associative array using json_decode

 public function sharemysuggestion(Request $request)

           {
            Log::info($request);
            $input = $request->all();
            Log::info(' sharemysuggestion via AJAX:', $request->all());
        Log::info("sharemytask data me kya aa rha hai" . $request->influencer_email);
         $id=$request->share_id;
         $status=$request->suggest_option; 
         $influencer_email= $request->influencer_email;
      $shareingdata= DB::connection('payments')->table("sharedatas")->where('id',$id)->first();
      $publisher_name=$shareingdata->user_name;

         $influencer_email_array = json_decode($influencer_email, true);  
         log::info($influencer_email_array);       
         $influencer_name= DB::table("addprofiles")->whereIn('user_email',$influencer_email_array)->distinct()->pluck('user_name');
         log::info("after param influencer_name");
         log::info($influencer_name);

                        if($status=="Approve")
                        {
            Log::info("unique me kya aa rha hai" . $status);    
            $sharemytask= DB::connection('payments')->table("sharedatas")->where('id',$id)->update(array('publisher_status' =>$status));
                       return response()->json([
                           'message' => "task disapprove successfully", 
                           'success' => "task disapprove successfully", 
                           'publisher' => $publisher_name, 
                           'influencer' => $influencer_name,
                       ]);
                   }
        else
        {
            $write_up=$request->suggest_write_up; 
            Log::info("unique me kya aa rha hai" . $write_up);
            Log::info("unique me kya aa rha hai" . $status);
            $sharemytask= DB::connection('payments')->table("sharedatas")->where('id',$id)->update(array('publisher_status' =>$status,'suggestion' => $write_up));
                       return response()->json([
                           'message' => "task disapprove successfully", 
                           'success' => "task disapprove successfully", 
                           'publisher' => $publisher_name, 
                           'influencer' => $influencer_name,
                       ]);
                   }
        }
Enter fullscreen mode Exit fullscreen mode

Difference between pluck and toArray()

$influencer_adminids = $pay_users->pluck('influencer_admin_id')->toArray();
Enter fullscreen mode Exit fullscreen mode

Output:

[101, 102, 103]
Enter fullscreen mode Exit fullscreen mode

Here, pluck('influencer_admin_id') extracts the 'influencer_admin_id' values from the collection, and toArray() converts the resulting collection to a plain PHP array.

$influencer_adminids = $pay_users->pluck('influencer_admin_id');
Enter fullscreen mode Exit fullscreen mode

Output (if you directly print or use the collection):

Illuminate\Support\Collection Object (
    [items:protected] => Array (
        [0] => 101
        [1] => 102
        [2] => 103
    )
)
Enter fullscreen mode Exit fullscreen mode

Here, pluck('influencer_admin_id') returns a Laravel collection with the 'influencer_admin_id' values.

In summary, the difference is in the data type of the output:

With ->toArray(), you get a plain PHP array.
Without ->toArray(), you get a Laravel collection.
Enter fullscreen mode Exit fullscreen mode

Difference between pluck,toArray(),json_encode() and json_decode()

Let's compare the outputs of $influencer_adminids = $pay_users->pluck('influencer_admin_id')->toArray() and $influencer_adminids = $pay_users->pluck('influencer_admin_id') in combination with json_encode and json_decode. We'll use the same example as before:

$pay_users = collect([
    ['id' => 1, 'influencer_admin_id' => 101],
    ['id' => 2, 'influencer_admin_id' => 102],
    ['id' => 3, 'influencer_admin_id' => 103],
]);
$influencer_adminids = $pay_users->pluck('influencer_admin_id')->toArray();
Enter fullscreen mode Exit fullscreen mode

Output:

[101, 102, 103]
Enter fullscreen mode Exit fullscreen mode

Now, let's use json_encode on the resulting array:

$json_encoded = json_encode($influencer_adminids);
Enter fullscreen mode Exit fullscreen mode

Output of $json_encoded:

[101,102,103]
Enter fullscreen mode Exit fullscreen mode

Now, if you want to decode it back into an array:

$decoded_array = json_decode($json_encoded, true);
Enter fullscreen mode Exit fullscreen mode

Output of $decoded_array:

[101, 102, 103]
$influencer_adminids = $pay_users->pluck('influencer_admin_id');
Enter fullscreen mode Exit fullscreen mode

Output (if you directly print or use the collection):

Illuminate\Support\Collection Object (
    [items:protected] => Array (
        [0] => 101
        [1] => 102
        [2] => 103
    )
)
Enter fullscreen mode Exit fullscreen mode

Now, if you want to convert the collection to an array and then use json_encode:

$json_encoded = json_encode($influencer_adminids->toArray());
Enter fullscreen mode Exit fullscreen mode

Output of $json_encoded:

[101,102,103]
Enter fullscreen mode Exit fullscreen mode

To decode it back into an array:

$decoded_array = json_decode($json_encoded, true);
Enter fullscreen mode Exit fullscreen mode

Output of $decoded_array:

[101, 102, 103]
Enter fullscreen mode Exit fullscreen mode

In summary, both approaches will result in the same JSON representation when using json_encode. The difference lies in the data type before encoding (toArray() converts the collection to a plain PHP array). When decoding with json_decode, you get an array in both cases. Using json_encode and json_decode can be useful when you need to serialize and deserialize data for storage or transportation purposes.

Way to take for loop from laravel collection like pluck

If $influencer_adminids is a Laravel collection resulting from $pay_users->pluck('influencer_admin_id'), you can use a foreach loop to iterate over its elements. Here's an example:

$pay_users = collect([
    ['id' => 1, 'influencer_admin_id' => 101],
    ['id' => 2, 'influencer_admin_id' => 102],
    ['id' => 3, 'influencer_admin_id' => 103],
]);
Enter fullscreen mode Exit fullscreen mode
$influencer_adminids = $pay_users->pluck('influencer_admin_id');
Enter fullscreen mode Exit fullscreen mode
foreach ($influencer_adminids as $adminId) {
    // Your logic for each $adminId goes here
    echo $adminId . PHP_EOL;
}
Enter fullscreen mode Exit fullscreen mode

In this example, the foreach loop iterates over each element in the $influencer_adminids collection, and the variable $adminId represents the current element in each iteration. You can replace the echo statement with the logic you want to apply for each influencer admin ID.

If you want to use the index along with the value in the loop, you can use the foreach loop with the key and value syntax:

foreach ($influencer_adminids as $index => $adminId) {
    // Your logic for each $adminId and its $index goes here
    echo "Index: $index, Admin ID: $adminId" . PHP_EOL;
}
Enter fullscreen mode Exit fullscreen mode

This way, $index will represent the array key (index), and $adminId will represent the value in each iteration. Adjust your loop logic based on what you need to do with each influencer admin ID.

Difference between toArray() and tojson

In the context of Laravel collections, the toArray and toJSON methods serve different purposes.

Let's consider your example:

$influencer_email_array = $pay_users->pluck('influencer_email')->toArray();
$influencer_email_json = $pay_users->pluck('influencer_email')->toJSON();
Enter fullscreen mode Exit fullscreen mode

toArray() Method:

Purpose: The toArray method is used to convert a collection into a plain PHP array.
Example:

$influencer_email_array = $pay_users->pluck('influencer_email')->toArray();
Enter fullscreen mode Exit fullscreen mode

Output:

['john@example.com', 'jane@example.com']
Enter fullscreen mode Exit fullscreen mode

toJSON() Method:

Purpose: The toJSON method is used to convert a collection into a JSON representation (a JSON-encoded string).
Example:

$influencer_email_json = $pay_users->pluck('influencer_email')->toJSON();
Enter fullscreen mode Exit fullscreen mode

Output:

["john@example.com","jane@example.com"]
Enter fullscreen mode Exit fullscreen mode

This string represents a JSON array containing the influencer email values extracted from the original $pay_users collection. Each email is a separate string element in the array.

If you want to use this JSON-encoded string later, you can decode it back to a PHP array using json_decode:

$influencer_email_array = json_decode($influencer_email);
Enter fullscreen mode Exit fullscreen mode

Summary:

toArray() produces a plain PHP array.
toJSON() produces a JSON-encoded string.
Enter fullscreen mode Exit fullscreen mode

In your example, if you use toArray, you get a PHP array, and if you use toJSON, you get a JSON-encoded string. Choose the method that best suits your needs based on whether you want a PHP array or a JSON string representation of your data.

How to display json data in key value pair format

<h1>{{ $user->name }}</h1>

<p>Email: {{ $user->email }}</p>

@if ($user->json_data)
    <h2>JSON Data:</h2>
    <ul>
        @foreach(json_decode($user->json_data, true) as $key => $value)
            <li>{{ $key }}: {{ $value }}</li>
        @endforeach
    </ul>
@endif
Enter fullscreen mode Exit fullscreen mode

How to retrive two field from table and store in json format in another table

you want to retrieve data from two fields of one table and store it in another table in the format similar to the example you provided, you can follow these steps. I'll use Eloquent to illustrate the process.

Let's assume you have two tables: source_table and destination_table.

Migration for Source Table:

php artisan make:migration create_source_table
In the migration file

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateSourceTable extends Migration
{
    public function up()
    {
        Schema::create('source_table', function (Blueprint $table) {
            $table->id();
            $table->string('field1');
            $table->integer('field2');
            $table->timestamps();
        });
    }

    public function down()
    {
        Schema::dropIfExists('source_table');
    }
}
Enter fullscreen mode Exit fullscreen mode

Run the migration:

php artisan migrate
Enter fullscreen mode Exit fullscreen mode

Model for Source Table:

use Illuminate\Database\Eloquent\Model;

class SourceModel extends Model
{
    protected $fillable = ['field1', 'field2'];
}
Enter fullscreen mode Exit fullscreen mode

Migration for Destination Table:

php artisan make:migration create_destination_table
In the migration file

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateDestinationTable extends Migration
{
    public function up()
    {
        Schema::create('destination_table', function (Blueprint $table) {
            $table->id();
            $table->json('combined_data');
            $table->timestamps();
        });
    }

    public function down()
    {
        Schema::dropIfExists('destination_table');
    }
}
Enter fullscreen mode Exit fullscreen mode

Run the migration:

php artisan migrate
Enter fullscreen mode Exit fullscreen mode

Model for Destination Table:

use Illuminate\Database\Eloquent\Model;

class DestinationModel extends Model
{
    protected $fillable = ['combined_data'];
}
Enter fullscreen mode Exit fullscreen mode

Code to Retrieve and Store Data:
Now, you can write a script to retrieve data from source_table, combine the values of field1 and field2 into a JSON format, and store it in destination_table.

// Retrieve data from source_table
$sourceData = SourceModel::select('field1', 'field2')->get();

// Process and combine data
$combinedData = [];
foreach ($sourceData as $row) {
    $combinedData[] = [
        'field1' => $row->field1,
        'field2' => $row->field2,
    ];
}

// Encode the array into JSON format
$jsonCombinedData = json_encode($combinedData);

// Store the data in destination_table
DestinationModel::create([
    'combined_data' => $jsonCombinedData,
]);
Enter fullscreen mode Exit fullscreen mode

Note
Difference between below two codes
Difference between Appending to Array and Overwriting Array

$combinedData = [];
foreach ($sourceData as $row) {
    $combinedData[] = [
        'field1' => $row->field1,
        'field2' => $row->field2,
    ];
}
Enter fullscreen mode Exit fullscreen mode
$combinedData = [];
foreach ($sourceData as $row) {
    $combinedData = [
        'field1' => $row->field1,
        'field2' => $row->field2,
    ];
}
Enter fullscreen mode Exit fullscreen mode

Image description

Database Structure:
After running the script, the destination_table might look like this:

Image description

This table has the columns id (primary key), combined_data (JSON column), created_at (timestamp), and updated_at (timestamp). The combined_data column contains the JSON-encoded data retrieved from field1 and field2 of the source_table.

How to display json data in blade file

Database Structure:
After running the script, the destination_table might look like this:

Image description

you can use the following code. I'll assume you want to display the data in a table with columns for field1 and field2.

In your Blade file (e.g., your_view.blade.php), you can use the following code:

<html>
<head>
    <title>Display Data</title>
</head>
<body>

<table border="1">
    <thead>
        <tr>
            <th>Field 1</th>
            <th>Field 2</th>
        </tr>
    </thead>
    <tbody>
        @foreach($combinedData as $data)
            <tr>
                <td>{{ $data['field1'] }}</td>
                <td>{{ $data['field2'] }}</td>
            </tr>
        @endforeach
    </tbody>
</table>

</body>
</html>
Enter fullscreen mode Exit fullscreen mode

In your controller, you can pass the combined data to the view:

use App\Models\DestinationModel;

public function showData()
{
    $destinationData = DestinationModel::latest()->first();

    // Decode the JSON data
    $combinedData = json_decode($destinationData->combined_data, true);

    return view('your_view', compact('combinedData'));
}
Enter fullscreen mode Exit fullscreen mode

Let's assume the $destinationData->combined_data contains the following JSON-encoded data:

[{"field1":"value1","field2":10,"created_at":"2022-01-01 12:30:00"},
 {"field1":"value2","field2":20,"created_at":"2022-01-02 14:45:00"}]
Enter fullscreen mode Exit fullscreen mode

When you use

json_decode($destinationData->combined_data, true);
Enter fullscreen mode Exit fullscreen mode

it will decode the JSON string into a PHP array. Here's the example:

$combinedData = json_decode($destinationData->combined_data, true);
Enter fullscreen mode Exit fullscreen mode
// $combinedData will be an array like this:
/*
[
    [
        'field1' => 'value1',
        'field2' => 10,
        'created_at' => '2022-01-01 12:30:00'
    ],
    [
        'field1' => 'value2',
        'field2' => 20,
        'created_at' => '2022-01-02 14:45:00'
    ]
]
*/
Enter fullscreen mode Exit fullscreen mode

// Now, you can use this $combinedData in your Blade view to display the da

How to display json data in key value pair format

<h1>{{ $user->name }}</h1>

<p>Email: {{ $user->email }}</p>

@if ($user->json_data)
    <h2>JSON Data:</h2>
    <ul>
        @foreach(json_decode($user->json_data, true) as $key => $value)
            <li>{{ $key }}: {{ $value }}</li>
        @endforeach
    </ul>
@endif
Enter fullscreen mode Exit fullscreen mode

output

<h1>User's Name</h1>
<p>Email: user@example.com</p>

<h2>JSON Data:</h2>
<ul>
    <li>key1: value1</li>
    <li>key2: value2</li>
    <!-- ... more key-value pairs if present in the JSON data ... -->
</ul>
Enter fullscreen mode Exit fullscreen mode

other way

<table>
    <tr>
        <th>Name</th>
        <td>{{ $user->name }}</td>
    </tr>
    <tr>
        <th>Email</th>
        <td>{{ $user->email }}</td>
    </tr>
    @if ($user->json_data)
        <tr>
            <th colspan="2">JSON Data</th>
        </tr>
        @foreach(json_decode($user->json_data, true) as $key => $value)
            <tr>
                <td>{{ $key }}</td>
                <td>{{ $value }}</td>
            </tr>
        @endforeach
    @endif
</table>
Enter fullscreen mode Exit fullscreen mode

Output

Image description

How to display json data in nested td inside table in blade file

To display data from a Laravel database table in a table where one of the fields contains a JSON array and its elements are displayed in nested td elements with rowspan, you can use the following example. Assume you have a users table with fields id, name, email, and json_data. The json_data field contains a JSON array.

<!-- Assuming you have a $users variable from the controller with the user data -->
<table border="1">
    <thead>
        <tr>
            <th>ID</th>
            <th>Name</th>
            <th>Email</th>
            <th>JSON Data</th>
        </tr>
    </thead>
    <tbody>
        @foreach($users as $user)
            <tr>
                <td>{{ $user->id }}</td>
                <td>{{ $user->name }}</td>
                <td>{{ $user->email }}</td>
                <td rowspan="{{ count(json_decode($user->json_data, true)) }}">
                    @if ($user->json_data)
                        <ul>
                            @foreach(json_decode($user->json_data, true) as $key => $value)
                                <li>{{ $key }}: {{ $value }}</li>
                            @endforeach
                        </ul>
                    @endif
                </td>
            </tr>
        @endforeach
    </tbody>
</table>
Enter fullscreen mode Exit fullscreen mode

Image description

<table border="1">
    <thead>
        <tr>
            <th>ID</th>
            <th>Name</th>
            <th>Email</th>
            <th>JSON Data</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>1</td>
            <td>John Doe</td>
            <td>john@example.com</td>
            <td rowspan="2">
                <ul>
                    <li>key1: value1</li>
                    <li>key2: value2</li>
                </ul>
            </td>
        </tr>
        <tr>
            <td>2</td>
            <td>Jane Smith</td>
            <td>jane@example.com</td>
        </tr>
        <tr>
            <td>3</td>
            <td>Bob Johnson</td>
            <td>bob@example.com</td>
            <td rowspan="2">
                <ul>
                    <li>key5: value5</li>
                    <li>key6: value6</li>
                </ul>
            </td>
        </tr>
    </tbody>
</table>
Enter fullscreen mode Exit fullscreen mode

Image description

To display data from a Laravel database table in a table where one of the fields contains a JSON array and its elements are displayed in nested td elements with colspan, you can use the following example. Assume you have a users table with fields id, name, email, and json_data. The json_data field contains a JSON array.

<table border="1">
    <thead>
        <tr>
            <th>ID</th>
            <th>Name</th>
            <th>Email</th>
            <th colspan="2">JSON Data</th>
        </tr>
    </thead>
    <tbody>
        @foreach($users as $user)
            <tr>
                <td>{{ $user->id }}</td>
                <td>{{ $user->name }}</td>
                <td>{{ $user->email }}</td>
                <td colspan="2">
                    @if ($user->json_data)
                        <ul>
                            @foreach(json_decode($user->json_data, true) as $key => $value)
                                <li>{{ $key }}: {{ $value }}</li>
                            @endforeach
                        </ul>
                    @endif
                </td>
            </tr>
        @endforeach
    </tbody>
</table>
Enter fullscreen mode Exit fullscreen mode

Image description

<table border="1">
    <thead>
        <tr>
            <th>ID</th>
            <th>Name</th>
            <th>Email</th>
            <th colspan="2">JSON Data</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>1</td>
            <td>John Doe</td>
            <td>john@example.com</td>
            <td colspan="2">
                <ul>
                    <li>key1: value1</li>
                    <li>key2: value2</li>
                </ul>
            </td>
        </tr>
        <tr>
            <td>2</td>
            <td>Jane Smith</td>
            <td>jane@example.com</td>
            <td colspan="2">
                <ul>
                    <li>key3: value3</li>
                    <li>key4: value4</li>
                </ul>
            </td>
        </tr>
        <tr>
            <td>3</td>
            <td>Bob Johnson</td>
            <td>bob@example.com</td>
            <td colspan="2">
                <ul>
                    <li>key5: value5</li>
                    <li>key6: value6</li>
                </ul>
            </td>
        </tr>
    </tbody>
</table>
Enter fullscreen mode Exit fullscreen mode

Image description

Display json array on popup modal

<!-- Include Bootstrap CSS and JS files if not already included -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>

<!-- Your table structure -->
<table border="1">
    <thead>
        <tr>
            <th>ID</th>
            <th>Name</th>
            <th>Email</th>
            <th>JSON Data</th>
        </tr>
    </thead>
    <tbody>
        @foreach($users as $user)
            <tr>
                <td>{{ $user->id }}</td>
                <td>{{ $user->name }}</td>
                <td>{{ $user->email }}</td>
                <td>
                    @if ($user->json_data)
                        <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#jsonDataModal_{{ $user->id }}">
                            View JSON Data
                        </button>
                        <!-- Modal -->
                        <div class="modal fade" id="jsonDataModal_{{ $user->id }}" tabindex="-1" role="dialog" aria-labelledby="jsonDataModalLabel_{{ $user->id }}" aria-hidden="true">
                            <div class="modal-dialog modal-lg" role="document">
                                <div class="modal-content">
                                    <div class="modal-header">
                                        <h5 class="modal-title" id="jsonDataModalLabel_{{ $user->id }}">JSON Data</h5>
                                        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                            <span aria-hidden="true">&times;</span>
                                        </button>
                                    </div>
                                    <div class="modal-body">
                                        <ul>
                                            @foreach(json_decode($user->json_data, true) as $key => $value)
                                                <li>{{ $key }}: {{ $value }}</li>
                                            @endforeach
                                        </ul>
                                    </div>
                                    <div class="modal-footer">
                                        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    @else
                        No JSON Data
                    @endif
                </td>
            </tr>
        @endforeach
    </tbody>
</table>
Enter fullscreen mode Exit fullscreen mode

Decode json response after get data using guzzle client

$json = json_decode($response->getBody()->getContents(), true);
Enter fullscreen mode Exit fullscreen mode
try {
    // Get the access token using the getKeywordAccessToken method
    $access_token = $this->getKeywordAccessToken();

    // Build the URL for the GET request
    $url = ''
        . Config::get('app.SD_KEYWORDS_MS_BASE_URL')
        . Config::get('app.SD_KEYWORDS_MS_EDIT')
        . '/' . $id;

    // Log information about the process
    Log::info('Got the access token from KeywordApiController::getKeywordAccessToken(). Now fetching keyword!');
    Log::info('Keyword Edit Url: ' . $url);

    // Create a new instance of the Guzzle HTTP client
    $guzzleClient = new Client();

    // Set up parameters for the GET request, including headers with the access token
    $params = [
        'headers' => [
            'Accept'         => 'application/json',
            'Authorization'  => 'Bearer ' . $access_token
        ]
    ];

    // Make a GET request to the specified URL using Guzzle
    $response = $guzzleClient->request('GET', $url, $params);

    // Log information about the response
    Log::info('Got the response from user');

    // Decode the JSON response content into an associative array
    $json = json_decode($response->getBody()->getContents(), true);

    // Return the decoded JSON data
    return $json;
} catch (\Exception $e) {
    // Handle any exceptions that may occur during the process
    // For example, log the error and return an appropriate response
    Log::error('Error fetching keyword: ' . $e->getMessage());
    return ['error' => 'Failed to fetch keyword.'];
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)