0

I'm new to Laravel and use Laravel 9 for my REST API. The client sends data in JSON format when I want to authenticate the application. But I cannot authenticate JSON format with my below code. Can anyone help me to find out the problem?

public function loginUser(Request $request)
{
    $validateUser = Validator::make($request->all(), [
        'email' => 'required|email',
        'password' => 'required'
    ]);

    if ($validateUser->fails()) {
        return response()->json([
            'status' => false,
            'message' => 'Validation errror',
            'errors' => $validateUser->errors()
        ], 401);
    }
}
2
  • Where do you have defined your routes? api.php or web.php ? Commented Sep 1, 2022 at 14:08
  • Can you please check for the errors that what error you'll get in response. if you could paste the error that you get here that would very much will some how show us the point where this error occurs. Thank you. Commented Sep 9, 2022 at 5:42

2 Answers 2

1

Note that your code needs some improvements.

Instead of doing manual validation, this way is better:

app/Exceptions/Handler.php

public function render($request, Throwable $e)
{
    if ($e instanceof \Illuminate\Validation\ValidationException) {
        return response()->json([
            'status' => false,
            'message' => 'Validation Error',
            'errors' => $e->errors()
        ], 422);
    }

    parent::render($request, $e);
}

Now, in your controller, just:

$validatedData = $request->validate([
            'email' => ['required', 'email'],
            'password' => ['required', (new \Illuminate\Validation\Rules\Password(8))]
]);

And, to solve the JSON Problem, create a new middleware with: php artisan make:middleware ForceXmlHttpRequest

app/Http/Middleware/ForceXmlHttpRequest
<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;

class ForceXmlHttpRequest
{
    public function handle(Request $request, Closure $next)
    {
        $request->headers->set('X-Requested-With', 'XMLHttpRequest');

        return $next($request);
     }
}

app/Http/Middleware/Kernel.php
protected $middlewareGroups = [
...
'api' => [
        'throttle:api',
        \Illuminate\Routing\Middleware\SubstituteBindings::class,
        \App\Http\Middleware\ForceXmlHttpRequest::class,
    ],
];
Sign up to request clarification or add additional context in comments.

Comments

0

if u using postman you go to headers and wright

Key : Accept Value : application/json

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.