0
votes

I'm on Shared Server.

Laravel v8.15.0 (PHP v7.3.23)

unable to set it up properly.

Sanctum & Passport both tried but that crashes with 500 Internal Server Error. So removed them.

https://townies.pk/api/v1/getCart is working. Another GET route for fetching Images is also working.

But https://townies.pk/api/register POST or https://townies.pk/api/v1/register POST not working. 500 Internal Server Error.

And https://townies.pk/api/login POST or https://townies.pk/api/v1/login POST not working. 500 Internal Server Error.

api.php

<?php

use App\Models\User;
use App\Http\Controllers\AuthController;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\ValidationException;
use Illuminate\Support\Facades\DB;

/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/

/*Route::middleware('auth:api')->get('/user', function (Request $request) {
    return $request->user();
});*/

Route::get('/v1/getCart', function(Request $request){
    return response()->json([
        'success'=> true, 
        'msg'=> "yes",
        'cartItems' => ['Beef Salaami Large: Rs. 780/-', 'Chicken Supreme Small: Rs. 290/-', 'Super Supreme Medium: Rs. 530/-' ]
    ])
    ->header('Content-Type', 'application/json');
});

Route::post('/v1/register', [AuthController::class, 'register'])->name('register');
Route::post('/v1/login', [AuthController::class, 'login'])->name('login');

AuthController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class AuthController extends Controller
{
    public function register(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'name' => 'required',
            'email' => 'required|email',
            'password' => 'required'
        ]);

        if($validator->fails())
        {
            Log::error('Something is really going wrong.');
            return response()->json(['status_code' => 400, 'message' => 'Bad Request']);
        }

        $user = new User();
        $user->name = $request->name;
        $user->email = $request->email;
        $user->password = algo($request->password);
        $user->save();

        return response()->json([
            'status_code' => 201,
            'message' => 'User Registration Successful.'
        ]);
    }

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

        if($validator->fails())
        {
            return response()->json(['status_code' => 400, 'message' => 'Bad Request']);
        }

        $credentials = request(['email', 'password']);

        if(!Auth::attempt($credentials))
        {
                return response()->json([
                    'status_code' => 401,
                    'message' => 'Unauthorised'
                ]);
        }

        $user = User::where('email', $request->email)->first();

        $tokenResult = $user->createToken('authToken')->plaitTextToken;

        return response()->json([
            'status_code' => 200,
            'token' => $tokenResult
        ]);
    }

    public function logout(Request $request)
    {
        $request->user()->currentAccessToken()->delete();
        return response()->json([
            'status_code' => 200,
            'message' => 'LogOut Successful'
        ]);
    }
}

My Database Schema

Database Schema

1
You'll want the contents of that 500 to debug this further. Also my gut says this is not a bug in Laravel since you also posted in the tracker there, but a misconfiguration on your end.Connor Tumbleson
yes, i know it's a misconfig on my end. but can't figure it out for 2 days now. i can only do GET requests. but no POST requests.Ronnie Depp

1 Answers

1
votes

Next time, please share the exception message from your logs. It is much easier and faster to debug errors when we have a clear picture on the error message itself.

I tried with Laravel Sanctum and /register works fine after adding the missing imports to AuthController and HasApiTokens trait to User model, as outlined below.

/login was still failing until fixing a typo on this line:

$tokenResult = $user->createToken('authToken')->plaitTextToken;

plaitTextToken is misspelled. Should be: plainTextToken.

These are the imports missing on AuthController:

use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Validator;

Also, be sure to:

  • Add the Laravel\Sanctum\HasApiTokens trait to the User model
  • Add the middleware needed for Sanctum into ./app/Http/Kernel.php under the api middleware group
  • Publish and run Laravel Sanctum migrations

All these are outlined on Laravel Sanctum installation guide, please be sure to follow the installation guide very closely:

https://laravel.com/docs/8.x/sanctum#installation

After applying the changes above I tried with PHPStorm HTTP Client using these requests:

POST http://my-app.test/api/v1/register
Accept: application/json
Content-Type: application/json

{"name": "bar", "email": "[email protected]", "password": "password"}

###

POST http://my-app.test/api/v1/login
Accept: application/json
Content-Type: application/json

{"email": "[email protected]", "password": "password"}

###

With these corresponding responses:

POST http://my-app.test/api/v1/register

HTTP/1.1 200 OK
Server: nginx/1.18.0 (Ubuntu)
Content-Type: application/json
Transfer-Encoding: chunked
Connection: keep-alive
Vary: Accept-Encoding
Cache-Control: no-cache, private
Date: Sun, 29 Nov 2020 01:26:22 GMT
X-RateLimit-Limit: 60
X-RateLimit-Remaining: 59
Access-Control-Allow-Origin: *

{
  "status_code": 200,
  "message": "User Registration Successful."
}

Response code: 200 (OK); Time: 80ms; Content length: 61 bytes

And

POST http://my-app.test/api/v1/login

HTTP/1.1 200 OK
Server: nginx/1.18.0 (Ubuntu)
Content-Type: application/json
Transfer-Encoding: chunked
Connection: keep-alive
Vary: Accept-Encoding
Cache-Control: no-cache, private
Date: Sun, 29 Nov 2020 01:27:17 GMT
X-RateLimit-Limit: 60
X-RateLimit-Remaining: 58
Access-Control-Allow-Origin: *

{
    "status_code": 200,
    "token": "1|5ImkzdVQgNhQyotxlZzs5Hr2YDkTPKfpfovthx1o"
}

Response code: 200 (OK); Time: 86ms; Content length: 72 bytes