Published on September 05 Aug 25

Standardize Your Laravel Responses with YSM Responsable

1 month ago 66

Perfect β€” based on the detailed README you provided, here's a comprehensive and engaging blog post to promote YSM/Responsable, ideal for platforms like dev.to, Medium, Hashnode, or your personal Laravel blog.


βœ… Standardize Your Laravel Responses with YSM/Responsable

If you've ever found yourself repeating the same response()->json() or redirect()->with() boilerplate over and over again, you're not alone.

Whether you're building a RESTful API or a web application, response formatting often gets messy, inconsistent, and scattered across your codebase.

That’s exactly why I built YSM/Responsable β€” a tiny but powerful Laravel package to standardize JSON and web redirect responses, and bring back the joy of clean, predictable code.


🎁 What Does YSM/Responsable Do?

It gives you:

  • βœ… success() and error() macros for both JSON responses and web redirects

  • βœ… apiSuccess() and apiError() helpers for clean API controller syntax

  • βœ… responsable() and responsable_forget() helpers to manage session-based flash data

  • βœ… Built-in support for Laravel pagination (including CursorPaginator)

  • βœ… Works in Laravel 6+ and PHP 7.2+


πŸš€ Installation

composer require ysm/responsable

That’s it. No need to publish anything β€” it auto-registers itself in Laravel.


πŸ§ͺ JSON API Responses (Success & Error)

Let’s say you're building a basic posts API:

βœ… Success Response with Collection

public function index()
{
    $posts = Post::limit(5)->get();

    return Response::success('Posts fetched successfully', PostResource::collection($posts));
}

βœ… Paginated Success Response

public function paginated()
{
    $posts = Post::paginate(10);

    return Response::success('Posts fetched successfully', PostResource::collection($posts), 200, $posts);
}

You’ll get structured JSON responses like:

{
  "status": true,
  "message": "Posts fetched successfully",
  "code": 200,
  "data": [...],
  "meta": {
    "total": 100,
    "per_page": 10,
    "current_page": 1,
    "last_page": 10
  }
}

❌ Error Response

public function show(Request $request)
{
    if (!$request->has('id')) {
        return Response::error('Post ID is required');
    }

    // ...
}

Output:

{
  "status": false,
  "message": "Post ID is required",
  "code": 422,
  "errors": []
}

🧼 Cleaner Syntax with apiSuccess() / apiError()

You can also use the global helpers:

return apiSuccess('Post created', ['id' => $post->id]);
return apiError('Something went wrong');

🌐 Web Redirect Responses

YSM/Responsable also improves redirect responses by attaching structured session data for flash messaging.

βœ… Success Redirect

return redirect()->route('posts.index')->success('Post created successfully', 201, ['id' => $post->id]);

❌ Error Redirect

return redirect()->back()->error('Failed to update post', 422, ['title' => 'Invalid']);

🎯 Access Session Data with responsable()

In your controller or Blade view:

$response = responsable();

$response->get('type');    // 'success' or 'error'
$response->get('message'); // The message
$response->get('data');    // Any attached data
$response->get('errors');  // Any attached errors

πŸ” Example in a Blade View

@php $r = responsable(); @endphp

@if ($r['type'])
    <div class="alert alert-{{ $r['type'] }}">
        <strong>{{ $r['message'] }}</strong>
        @if ($r['errors'])
            <ul>
                @foreach ($r['errors'] as $field => $msg)
                    <li>{{ $field }}: {{ $msg }}</li>
                @endforeach
            </ul>
        @endif
    </div>
@endif

🧹 Clear Session Flash with responsable_forget()

Want to manually clear the stored session flash?

responsable_forget();

Useful if you want full control over the lifetime of flash messages.


🧠 IDE Support (Optional)

To enable auto-complete for the macros and helpers:

composer require --dev barryvdh/laravel-ide-helper
php artisan ide-helper:generate

Now you'll get full suggestions for response()->success(), redirect()->error(), etc.


πŸ“š Macro Signatures (Cheat Sheet)

// JSON success
Response::success(string $message = '', array|object $data = [], int $code = 200, ?Paginator $paginator = null);

// JSON error
Response::error(string $message = '', int $code = 422, array $errors = []);

// Web redirect success
redirect()->success(string $message = '', int $code = 200, array|object $data = [], bool $persist = false);

// Web redirect error
redirect()->error(string $message = '', int $code = 422, array $errors = [], bool $persist = false);

⚑ When to Use YSM/Responsable?

Use this package when you:

  • Want consistent JSON responses across your API

  • Need structured flash data for web redirects

  • Hate rewriting the same response format again and again

  • Need a testable, predictable way to manage success/error states


πŸ”— Get Started

πŸ“¦ GitHub: https://github.com/DevYSM/responsable
πŸ”– License: MIT
πŸ“… Laravel 6+ | PHP 7.2+


❀️ Final Thoughts

This package was born out of frustration with Laravel’s scattered response conventions β€” one pattern for JSON, another for web redirects, and yet another for session data.

With YSM/ResponsableYou can unify your response layer and keep your codebase clean, DRY, and consistent.

Give it a ⭐ if it helps, and PRs are always welcome!

#JavaScript #jQuery #laravel #php #elasticsearch #mongodb #api #mysql #wordpress #html #css #bootstrap #php8 #ui-development #tailwindcss #postgresql #redis #docker #openai #codewithyassen #ysm #response #ysm-responsable