How to Send Laravel Models to JSON API Response in Laravel 11?

How to Send Laravel Models to JSON API Response in Laravel 11

In Laravel, when we create REST API we need to send the model object to the API response. However, in the modern Laravel approach, we can send the model data in JSON format using the toJson method.

Hire Laravel Developers

Let’s understand how it is possible in Laravel 11.

Pre-requisites

  • Laravel 11 project setup
  • User and Article table with model. In the Article model, we have the ‘title’, ‘content’, and ‘author’ fields in a database. If you don’t have an Article model then follow the below steps.
Laravel Development Service CTA

To create a model with migration run the command:

php artisan make:model Article -m

database/migrations/xxxx_xx_xx_xxxxxx_create_articles_table.php

Run migration command: 

php artisan migrate

How to Send Laravel Models to JSON API Response in Laravel 11?

In Laravel there are so many methods to convert JSON response but toJson() is 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);

In our example, we can send JSON responses like:

<?php

namespace App\Http\Controllers;
use App\Models\Article;

class ArticalController extends Controller
{
    public function show($id)
    {
        $article = Article::findOrFail($id);
        return $article->toJson();
    }
    public function index()
    {
        $articles = Article::with('author')->get();
        return response()->json($articles);
    }
}

Conclusion:

This way you can send Laravel Models to JSON API Response in Laravel 11.

Got a question about Laravel APIs? Let us know in the comments below!

Relevant Read – Laravel: Creating a Standardized JSON Response for API

Contact Us

Happy Coding!

Previous Article

How to Create Dummy Data for Testing using Factory in Laravel 11?

Next Article

Top Website Downdetector Tools for 2025: Free and Paid

Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *

Get Connect With Us

Subscribe to our email newsletter to get the latest posts delivered right to your email.
Pure inspiration, zero spam ✨