PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0
Showing posts with label laravel-response. Show all posts
Showing posts with label laravel-response. Show all posts

Wednesday, January 19, 2022

[FIXED] How to change response in Laravel?

 January 19, 2022     laravel, laravel-5, laravel-5.4, laravel-response     No comments   

Issue

I have RESTful service that is available by endpoints.

For example, I request api/main and get JSON data from server.

For response I use:

return response()->json(["categories" => $categories]);

How to control format of response passing parameter in URL?

As sample I need this: api/main?format=json|html that it will work for each response in controllers.


Solution

You can use for this Response macros. For example in AppServiceProvider inside boot method you can add:

\Response::macro('custom', function($view, $data) {
    if (\Request::input('format') == 'json') {
            return response()->json($data);
    }
    return view($view, $data);
});

and in your controller you can use now:

$data = [
   'key' => 'value',
];

return response()->custom('your.view', $data);

If you run now for example GET /categories you will get normal HTML page, but if you run GET /categories?format=json you will get Json response. However depending on your needs you might need to customize it much more to handle for example also redirects.



Answered By - Marcin Nabiałek
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Monday, January 3, 2022

[FIXED] How to set custom response for selected Request class in Laravel 5.5

 January 03, 2022     laravel, laravel-5, laravel-5.5, laravel-request, laravel-response     No comments   

Issue

I'm trying to use Laravel validation to generate custom error message, however I'm unable to find the function I should be overriding.

Route: POST:/entries/ uses EntryController@store which uses EntryStoreRequest to perform validation.

EntryStoreRequest

namespace App\Api\V1\Requests;

class EntryStoreRequest extends ApiRequest
{
    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'message' => [
                'string',
                'required',
                'max:65535',
            ],
            'code' => [
                'string',
                'max:255',
                'nullable'
            ],
            'file' => [
                'string',
                'max:255',
                'nullable'
            ],
            'line' => [
                'string',
                'max:255',
                'nullable'
            ],
            'stack' => [
                'string',
                'max:65535',
                'nullable'
            ]
        ];
    }
}

ApiRequest

namespace App\Api\V1\Requests;

use Illuminate\Foundation\Http\FormRequest;

abstract class ApiRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }
}

The errors are currently returned as:

{
    "message": "The given data was invalid.",
    "errors": {
        "message": [
            "The message field is required."
        ]
    }
}

I want to format them as:

{
    "data": [],
    "meta: {
        "message": "The given data was invalid.",
        "errors": {
            "message": [
                "The message field is required."
            ]
        }
}

How can I achieve this within the ApiRequest class?


Solution

If you want to customize validation response only for selected Request class, you need to add failedValidation() message to this class:

protected function failedValidation(\Illuminate\Contracts\Validation\Validator $validator)
{
    $response = new JsonResponse(['data' => [], 
             'meta' => [
                'message' => 'The given data is invalid', 
                'errors' => $validator->errors()
             ]], 422);

    throw new \Illuminate\Validation\ValidationException($validator, $response);
}

This way you don't need to change anything in Handler and have this custom response only for this single class.

And if you want to change format globally for all responses you should add to app\Exceptions\Handler.php file the following method:

protected function invalidJson($request, ValidationException $exception)
{
    return response()->json([
             'data' => [], 
             'meta' => [
                'message' => 'The given data is invalid', 
                'errors' => $exception->errors()
             ]
             ], $exception->status);
}

You can read about this also in Upgrade guide in Exception Format section



Answered By - Marcin Nabiałek
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Older Posts Home
View mobile version

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
All Comments
Atom
All Comments

Copyright © PHPFixing