Close Menu
    DevStackTipsDevStackTips
    • Home
    • News & Updates
      1. Tech & Work
      2. View All

      Sunshine And March Vibes (2025 Wallpapers Edition)

      May 24, 2025

      The Case For Minimal WordPress Setups: A Contrarian View On Theme Frameworks

      May 24, 2025

      How To Fix Largest Contentful Paint Issues With Subpart Analysis

      May 24, 2025

      How To Prevent WordPress SQL Injection Attacks

      May 24, 2025

      Looking for an AI-powered website builder? Here’s your best option in 2025

      May 24, 2025

      SteamOS is officially not just for Steam Deck anymore — now ready for Lenovo Legion Go S and sort of ready for the ROG Ally

      May 23, 2025

      Microsoft’s latest AI model can accurately forecast the weather: “It doesn’t know the laws of physics, so it could make up something completely crazy”

      May 23, 2025

      OpenAI scientists wanted “a doomsday bunker” before AGI surpasses human intelligence and threatens humanity

      May 23, 2025
    • Development
      1. Algorithms & Data Structures
      2. Artificial Intelligence
      3. Back-End Development
      4. Databases
      5. Front-End Development
      6. Libraries & Frameworks
      7. Machine Learning
      8. Security
      9. Software Engineering
      10. Tools & IDEs
      11. Web Design
      12. Web Development
      13. Web Security
      14. Programming Languages
        • PHP
        • JavaScript
      Featured

      A timeline of JavaScript’s history

      May 23, 2025
      Recent

      A timeline of JavaScript’s history

      May 23, 2025

      Loading JSON Data into Snowflake From Local Directory

      May 23, 2025

      Streamline Conditional Logic with Laravel’s Fluent Conditionable Trait

      May 23, 2025
    • Operating Systems
      1. Windows
      2. Linux
      3. macOS
      Featured

      Open-Typer is a typing tutor application

      May 24, 2025
      Recent

      Open-Typer is a typing tutor application

      May 24, 2025

      RefreshOS is a distribution built on the robust foundation of Debian

      May 24, 2025

      Cosmicding is a client to manage your linkding bookmarks

      May 24, 2025
    • Learning Resources
      • Books
      • Cheatsheets
      • Tutorials & Guides
    Home»Development»Converting Laravel Models to JSON for API Responses

    Converting Laravel Models to JSON for API Responses

    December 30, 2024

    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.

    // 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 AppModels;
    
    use IlluminateDatabaseEloquentModel;
    
    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.


    The post Converting Laravel Models to JSON for API Responses appeared first on Laravel News.

    Join the Laravel Newsletter to get all the latest
    Laravel articles like this directly in your inbox.

    Source: Read More 

    Facebook Twitter Reddit Email Copy Link
    Previous Articleecholabsdev/prism
    Next Article Acquia Cloud Site Review – A Crucial Step for Success

    Related Posts

    Artificial Intelligence

    Markus Buehler receives 2025 Washington Award

    May 24, 2025
    Artificial Intelligence

    LWiAI Podcast #201 – GPT 4.5, Sonnet 3.7, Grok 3, Phi 4

    May 24, 2025
    Leave A Reply Cancel Reply

    Continue Reading

    Leading a Clinical Data Collaboration Revolution: A Success Story

    Development

    AzzaSec Reveals Advanced Windows Ransomware Builder, Threatens Cybersecurity

    Development

    Why is Testing Essential for Insurance Policy Administration Systems?

    Development
    Malicious npm Package Targets Atomic Wallet, Exodus Users by Swapping Crypto Addresses

    Malicious npm Package Targets Atomic Wallet, Exodus Users by Swapping Crypto Addresses

    Development

    Highlights

    News & Updates

    Borderlands 4 is offering a free weapon skin and Golden Keys to unlock loot before the game is even out

    May 5, 2025

    2K is offering a free weapon skin for the upcoming looter-shooter Borderlands 4, and free…

    New ScyllaDB Release Delivers Unprecedented Elasticity & Efficiency via “Tablets” Architecture

    December 7, 2024

    “That was really frustrating for us on the dev side.” Halo dev explains how one of the Xbox series’ biggest controversies came to be

    April 25, 2025

    The First Descendant: Known issues and bugs

    July 2, 2024
    © DevStackTips 2025. All rights reserved.
    • Contact
    • Privacy Policy

    Type above and press Enter to search. Press Esc to cancel.