Skip to content

Laravel usage

In order to use JsonMapper with your Laravel application you only need JsonMapper's LaravelPackage.

Installation#

The installation of JsonMapper Laravel package can easily be done with Composer

$ composer require json-mapper/laravel-package

This package makes use of Laravels package auto-discovery mechanism.

* The example shown above assumes that composer is on your $PATH.

Configuration#

Copy the package config to your local config with the publish command:

php artisan vendor:publish --provider="JsonMapper\LaravelPackage\ServiceProvider"

The package config enables you to choose between the default JsonMapper or the best-fit JsonMapper. You can check the Setup page for more info of the different types.

Example#

<?php
 
namespace App\Service;
 
use Illuminate\Support\Collection;
use JsonMapper\LaravelPackage\JsonMapperInterface;
 
class ApiClient
{
public function __construct(
private JsonMapperInterface $mapper
) {
}
 
public function fetchJokes(): Collection
{
$data = file_get_contents('https://jsonplaceholder.typicode.com/todos');
 
return $this->mapper->mapToCollectionFromString($data, new Todo());
}
}
 
class Todo
{
public int $userId;
public int $id;
public string $title;
public bool $completed;
}