首页 > 后端开发 > php教程 > 将Laravel模型转换为JSON的API响应

将Laravel模型转换为JSON的API响应

Johnathan Smith
发布: 2025-03-06 01:17:13
原创
244 人浏览过

Laravel

Converting Laravel Models to JSON for API Responses

提供了几种将雄辩模型转换为JSON的方法,而Tojson()是最直接的方法之一。此方法在模型如何为API响应中序列化提供了灵活性。
<!-- 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);
登录后复制
>

让我们探索使用tojson()的API响应系统的实践示例
<!-- 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的tojson()方法提供了一种将模型转换为JSON的有效方法,同时提供了通过模型属性和关系自定义输出的灵活性。

>

以上是将Laravel模型转换为JSON的API响应的详细内容。更多信息请关注PHP中文网其他相关文章!

本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板