I was trying to convert an array to json and this is my code
<?php
namespace App\Http\Middleware;
use Carbon\Carbon;
use Closure;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Log;
class SystemActivityLogger
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse) $next
* @return Response|RedirectResponse
*/
public function handle(Request $request, Closure $next)
{
Log::channel('rabbitmq_elk')->info($this->prepareLogData($request));
return $next($request);
}
/**
* Prepare log data and log it
* @param Request $request
* @return string
*/
private function prepareLogData(Request $request): string
{
return json_encode([
'ip' => $request->ip(),
'url' => $request->url(),
'agent' => $request->userAgent(),
'date' => Carbon::now()->toDateTimeString(),
'params' => $request->query(),
]);ل
}
}
But then when I tested the output of this code, I realized that it returns a string. this is my code
dd(is_string(json_encode([
'ip' => $request->ip(),
'url' => $request->url(),
'agent' => $request->userAgent(),
'date' => Carbon::now()->toDateTimeString(),
'params' => $request->query(),
])));
return the true output
how can convert this array to json???
CodePudding user response:
JSON is a string format. The data is only JSON when it is in a string format.
To convert array to object
$object = json_decode(json_encode($array));
To convert array to collection
$collection = collect($array);
To convert array to json
$json = json_encode($array);
CodePudding user response:
dd(is_string(json_encode([
'ip' => $request->ip(),
'url' => $request->url(),
'agent' => $request->userAgent(),
'date' => Carbon::now()->toDateTimeString(),
'params' => $request->query(),
])));
Here used is_string
function and it's return always boolean
. So please remove is_string
function and check again with die and dump. Like bellow...
dd(json_encode([
'ip' => $request->ip(),
'url' => $request->url(),
'agent' => $request->userAgent(),
'date' => Carbon::now()->toDateTimeString(),
'params' => $request->query(),
]));