Laravel liefert verschiedene Methoden zur Umwandlung eloquenter Modelle in JSON, wobei Tojson () einer der einfachsten Ansätze ist. Diese Methode bietet Flexibilität darin, wie Ihre Modelle für API -Antworten serialisiert werden.
<!-- 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);
Erforschen wir ein praktisches Beispiel eines API -Antwortsystems mit tojson ():
<!-- Syntax highlighted by torchlight.dev --><?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 } }
Laravels Tojson () -Methode bietet eine effiziente Möglichkeit, Modelle in JSON zu konvertieren und gleichzeitig die Flexibilität zu bieten, die Ausgabe durch Modellattribute und -beziehungen anzupassen.
Das obige ist der detaillierte Inhalt vonKonvertieren von Laravel -Modellen in JSON für API -Antworten in JSON konvertieren. Für weitere Informationen folgen Sie bitte anderen verwandten Artikeln auf der PHP chinesischen Website!