Creating Array of Data in Laravel Controller

Creating Array of Data in Laravel Controller
$document = new Document();
$document->title = $request['title'];
$document->description = $request['description'];

When i try to output the above code using echo $document; i get this result:

{"title":"asdfasdf","description":"asdfasdfsadf"}

What i want is to create my own array of data and output the same format. This is the code i am trying to experiment but it does not work:

    $data = array(
      "title" => "hello",
      "description" => "test test test"
    );

    echo $data;

Any Help would be appreciated. Thanks.

3

1 Answer

All collections also serve as iterators, allowing you to loop over them as if they were simple PHP arrays:

foreach ($document as $data) {
    echo $data->title;
    echo $data->description;
}

There is no difference while using a PHP framework. You may refer the official PHP Arrays Manual page to work with the language construct.

If you need to convert JSON to array, use:

$data->toArray();

OR

json_decode($data);

Here is your code:

$data = array(
  "title" => "hello",
  "description" => "test test test"
);

// may also declare

$data = ["title" => "hello", "description" => "test test test"];

Use:

var_dump($data);

OR

print_r($data);

// and the output will be

["title" => "hello", "description" => "test test test",]
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Sarah Jenkins
Author

Sarah Jenkins

Sarah Jenkins is a veteran tech journalist with over 12 years of experience covering artificial intelligence, mobile innovations, and digital ethics. Her insights have appeared in leading technology publications worldwide.