Php model to json

PHP JSON

Summary: in this tutorial, you will learn how to convert data in PHP to JSON data and vice versa using the PHP JSON extension.

JSON stands for JavaScript Object Notation. JSON is designed as a lightweight data-interchange format.

JSON is built on two structures:

  • A collection of name/value pairs called JSON objects. JSON objects are equivalent to associative arrays in PHP.
  • An ordered list of values called arrays. They’re equivalent to indexed arrays in PHP.

The JSON format is human-readable and easy for computers to parse. Even though JSON syntax derives from JavaScript, it’s designed to be language-independent.

PHP JSON extension

PHP natively supports JSON via the JSON extension. The JSON extension provides you with some handy functions that convert data from PHP to JSON format and vice versa.

Since the JSON extension comes with PHP installation by default, you don’t need to do any extra configuration to make it works.

Converting PHP variables to JSON using json_encode() function

To get a JSON representation of a variable, you use the json_encode() function:

json_encode ( mixed $value , int $flags = 0 , int $depth = 512 ) : string|falseCode language: PHP (php)

The following example uses the json_encode() function to convert an indexed array in PHP to JSON format:

 $names = ['Alice', 'Bob', 'John']; $json_data = json_encode($names); // return JSON to the browsers header('Content-type:application/json'); echo $json_data;Code language: PHP (php)
  • First, define an array of strings that consists of three elements.
  • Second, convert the array to JSON using the json_encode() function.
  • Third, return the JSON data to the browsers by setting the content type of the document to appplication/json using the header() function.
[ "Alice", "Bob", "John" ]Code language: JSON / JSON with Comments (json)

The following example uses the json_encode() function to convert an associative array in PHP to an object in JSON:

 $person = [ 'name' => 'Alice', 'age' => 20 ]; header('Content-type:application/json'); echo json_encode($person);Code language: PHP (php)
< name: "Alice", age: 20 >Code language: PHP (php)

In practice, you would select data from a database and use the json_encode() function to convert it to the JSON data.

Converting JSON data to PHP variables

To convert JSON data to a variable in PHP, you use the json_decode() function:

json_decode ( string $json , bool|null $associative = null , int $depth = 512 , int $flags = 0 ) : mixedCode language: PHP (php)

The following example shows how to use json_decode() function to convert JSON data to a variable in PHP:

 $json_data = ''; $person = json_decode($json_data); var_dump($person);Code language: PHP (php)
object(stdClass)#1 (2) ["name"] => string(5) "Alice" ["age"] => int(20) > Code language: PHP (php)

In this example, the json_decode() function converts an object in JSON to an object in PHP. The object is an instance of the stdClass class. To convert JSON data to an object of a specific class, you need to manually map the JSON key/value pairs to object properties. Or you can use a third-party package.

Serializing PHP objects

To serialize an object to JSON data, you need to implement the JsonSerializable interface. The JsonSerializable interface has the jsonSerialize() method that specifies the JSON representation of the object.

For example, the following shows how to implement the JsonSerializable interface and use the json_encode() function to serialize the object:

 class Person implements JsonSerializable < private $name; private $age; public function __construct(string $name, int $age) < $this->name = $name; $this->age = $age; > public function jsonSerialize() < return [ 'name' => $this->name, 'age' => $this->age ]; > > // serialize object to json $alice = new Person('Alice', 20); echo json_encode($alice);Code language: PHP (php)
"name":"Alice","age":20>Code language: PHP (php)
  • First, define a Person class that implements the JsonSerializable interface.
  • Second, return an array that consists of name and age properties from the jsonSerialize() method. The json_encode() function will use the return value of this method to create JSON data.
  • Third, create a new Person object and serialize it to JSON data using the json_encode() function.

Summary

  • JSON is a lightweight data-interchange format.
  • Use the json_encode() function to convert PHP variables to JSON.
  • Use the json_decode() function to convert JSON data to PHP variables.
  • Implement the JsonSerializable interface to specify the JSON representation of an object.

Источник

Php model to json in laravel code example

If you just need to get json data from somewhere, create usual class which gets data from somewhere and returns JSON: Register this class in file, run and use your class: Hence, you can do like in this example from the documentation to return JSON data directly from your route: For more information, see http://four.laravel.com/docs/eloquent#converting-to-arrays-or-json Solution: You need to extend Model only if you’re using Eloquent.

Returning an Eloquent model as JSON in Laravel 4

The actual data sent is the same, however.

#1 Sends Content-Type:application/json to the browser

#2 Sends Content-Type:text/html

#1 is more correct but it depends on your Javascript, see: What is the correct JSON content type?

However, it is much simpler to just return the model. It is automagically returned as JSON and the Content-Type is set correctly:

Response::json($someArray) is a generic way to return JSON data.

return $model->toJson() is specific to returning a model as JSON. This would be my preferred approach when working with an Eloquent model.

In #1 you first convert your Eloquent to an array, and then you convert it to JSON, which seems a bit redundant.

With that in mind, I’d go with #2 if you’re returning the JSON to the caller.

Also note that, in L4, whenever an Eloquent model is cast to a string it will be automatically converted to JSON. Hence, you can do like in this example from the documentation to return JSON data directly from your route:

For more information, see http://four.laravel.com/docs/eloquent#converting-to-arrays-or-json

Php — Returning an Eloquent model as JSON in Laravel, With that in mind, I’d go with #2 if you’re returning the JSON to the caller. Also note that, in L4, whenever an Eloquent model is cast to a string it will be automatically converted to JSON. Hence, you can do like in this example from

Json Laravel Model

You need to extend Model only if you’re using Eloquent.

If you just need to get json data from somewhere, create usual class which gets data from somewhere and returns JSON:

Register this class in composer.json file, run composer dumpauto and use your class:

$model = new MyModel(); $data = $model->getJsonData(); 

Php — Json Laravel Model, You need to extend Model only if you’re using Eloquent. If you just need to get json data from somewhere, create usual class which gets data from somewhere and returns JSON: class MyModel < public function

Model binding for JSON api using Laravel

There is no such binding in Laravel. Laravel binding is about Models/DB access as @PKeidel said. All you need is controller method without any models.

public function add(Request $request) < return $request->A + $request->B; > 

UPD: What about new constructor for CalculatorModel class?

public function __construct(array $properties = []) < foreach ($properties as $key =>$value) < $this-> = $value; > > public function add(Request $request) < $m = new CalculatorModel($request->all()); return Calculator::Add($m); > 

In any case Laravel does not offer out of the box solution for this.

Try this to wrap your API, which can then be used by Eloquent as if it were a database model:

All what models are about is saving/reading something from the database. So if this is not what you want, forget about it. Because in Laravel models are bound to database tables 😉

If you just want so receive some values as json, do a calculation and return a value you are thinking to complicated.

Route::post('add', function() < $data = request()->json(); return $data->get('A') + $data->get('B'); >); 
Route::post('add', function(\Illuminate\Http\Request $r) < return $r->A + $r->B; >); 

After that just make sure to send your data with json header. Like so:

fetch('/add', < method:"post", headers: , body: '' >) .then((d) => d.text()) .then((html) => < output.innerHTML = html; >) 

See it in action here: https://laravelplayground.com/#/snippets/006b4871-5d92-4a2d-b8af-8a21423024e6

Request function json decode in Laravel 8 Code Example, All Languages >> PHP >> request function json decode in Laravel 8 “request function json decode in Laravel 8” Code Answer laravel json response decode php by Noob Learner

Php sort json by value

sort json in php

score > $b->score ? -1 : 1; //Compare the scores >); print_r($data); ?>

Php sort json by value Code Example, laravel group by with where clause. Laravel group collection and sort by the biggest value. laravel group concat values showing duplicate. laravel group route controller. laravel group routes. laravel groupby and latest. Laravel groupby date of created_at. laravel grouping where. laravel guest blade.

Источник

Читайте также:  Задачи по рекурсии python
Оцените статью