Laravel Tutorials

Converting Laravel Models to JSON for API Responses

Published
Converting Laravel Models to JSON for API Responses image

Laravel provides several methods for transforming Eloquent models into JSON, with toJson() being one of the most straightforward approaches. This method offers flexibility in how your models are serialized for API responses.

// Basic usage of toJson()
$user = User::find(1);
return $user->toJson();
// With JSON formatting options
return $user->toJson(JSON_PRETTY_PRINT);

Let's explore a practical example of an API response system using toJson():

<?php
 
namespace App\Models;
 
use Illuminate\Database\Eloquent\Model;
 
class Article extends Model
{
protected $appends = ['reading_time'];
 
protected $hidden = ['internal_notes'];
 
public function author()
{
return $this->belongsTo(User::class);
}
 
public function comments()
{
return $this->hasMany(Comment::class);
}
 
public function getReadingTimeAttribute()
{
return ceil(str_word_count($this->content) / 200);
}
 
public function toArray()
{
return [
'id' => $this->id,
'title' => $this->title,
'content' => $this->content,
'author' => $this->author->name,
'reading_time' => $this->reading_time,
'comments_count' => $this->comments()->count(),
'created_at' => $this->created_at->toDateTimeString(),
'updated_at' => $this->updated_at->toDateTimeString(),
];
}
}
 
// In your controller
class ArticleController extends Controller
{
public function show($id)
{
$article = Article::with(['author', 'comments.user'])->findOrFail($id);
 
return $article->toJson();
}
 
public function index()
{
$articles = Article::with('author')->get();
 
return response()->json($articles); // Implicit conversion
}
}

Laravel's toJson() method provides an efficient way to convert models to JSON, while offering the flexibility to customize the output through model attributes and relationships.

Harris Raftopoulos photo

Senior Software Engineer • Staff & Educator @ Laravel News • Co-organizer @ Laravel Greece Meetup

Sponsored

acquaintsoft logo
Acquaint Softtech

Hire Laravel developers with AI expertise at $20/hr. Get started in 48 hours.

Visit Acquaint Softtech

The latest

View all →
The Laracon Archive image

The Laracon Archive

Read article
Group Adjacent Collection Items in Laravel with chunkBy() image

Group Adjacent Collection Items in Laravel with chunkBy()

Read article
Laravel queue:work Now Prints Why the Worker Stopped image

Laravel queue:work Now Prints Why the Worker Stopped

Read article
Sidecar Brings Statamic's Control Panel to Your Existing Markdown Sites image

Sidecar Brings Statamic's Control Panel to Your Existing Markdown Sites

Read article
Collections chunkBy() and Storage Path Hardening in Laravel 13.30 image

Collections chunkBy() and Storage Path Hardening in Laravel 13.30

Read article
Forte: Parse and Rewrite Laravel Blade Templates image

Forte: Parse and Rewrite Laravel Blade Templates

Read article