将 Laravel 模型转换为 JSON 用于 API 响应
Laravel 提供了几种将 Eloquent 模型转换为 JSON 的方法,toJson()
是最简单的方法之一。此方法在如何为 API 响应序列化模型方面提供了灵活性。
/ Basic usage of toJson()
$user = User::find(1);
return $user->toJson();
// With JSON formatting options
return $user->toJson(JSON_PRETTY_PRINT);
下面是使用 toJson()
的 API 响应系统的实例:
<?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 的 toJson()
方法提供了一种将模型转换为JSON的有效方法,同时提供了通过模型属性和关系定制输出的灵活性。