0

I have a problem here, I want to change the query string that I received to the json form as follows

{"id":"89"}

here I try to use json_encode but the one it produces is

""?id=89""

here is my code

    $coba = str_replace($request->url(), '',$request->fullUrl());
        if (empty($coba)) {
           $url = "{}";
        } else {
            $url = $coba;
        }

         $json_body = json_encode($url);

there I also want to change if there is no query string then the result is {}

2 Answers 2

1

This should do it for you for both conditions:

json_encode($request->query(), JSON_FORCE_OBJECT);

PHP Manual - JSON Functions - json_encode

Laravel 5.8 Docs - Requests - Retrieving Input - Retrieving Input From The Query String query

Sign up to request clarification or add additional context in comments.

1 Comment

well it works, but what if there is no query string condition then it generates {}
0
//get Parameters
$array = [
    'id' => 20,
    'name' => 'john',
];
//getting the current url from Request
$baseUrl = $request->url();

//we are encoding the array because 
//u said that the get parms in json format
//so that ...
$json = json_encode($array);

//now building the query based on the data
//from json by decoding it
$query = (http_build_query(json_decode($json)));

//at the end of the url you need '?' mark so...
$url = \Illuminate\Support\Str::finish($baseUrl,'?');
//now Merging it
$fullUrl = $url.$query;

dump($fullUrl);

For any issues kindly comment

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.