Home >Backend Development >PHP Tutorial >Converting Laravel Models to JSON for API Responses

Converting Laravel Models to JSON for API Responses

Johnathan Smith
Johnathan SmithOriginal
2025-03-06 01:17:13245browse

Converting Laravel Models to JSON for API Responses

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.

<!-- Syntax highlighted by torchlight.dev -->// 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():

<!-- Syntax highlighted by torchlight.dev --><?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Article extends Model
{
    protected $appends = [&#39;reading_time&#39;];

    protected $hidden = [&#39;internal_notes&#39;];

    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.

The above is the detailed content of Converting Laravel Models to JSON for API Responses. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn