Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Deleu's avatar

The 'overwhelmth' of Laravel - A REST goal

I started writing this topic in the hopes of finding a guidance, but now it seems like I wrote too much and, at the same time, I don't want to give up posting. So here goes my problems with Laravel RESTful.

1- Authentication

I chose JWT-Auth over OAuth2-Laravel because OAuth and those 13 tables seems too complex for me right now. Following Elson Tan's tutorial, I managed to achieve a basic authentication token with refresh at each request. How do I go from here to validating roles in routes? Although it works, I don't think the following is appropriate:

        Route::get('test', function() {
            $payload = JWTAuth::parseToken()->getPayload();

            if(!in_array('admin', $payload->get('role'))){
                throw new \Symfony\Component\HttpKernel\Exception\HttpException(401);
            }

            return response()->json(['foo' => 'bar']);
        });

I almost chose Sentry over JWT, but it's deprecated and the Sentinel Framework doesn't seem a good fit for API. I know, I read the Sentinel::stateless() authentication, but still I wasn't convinced of it's practicality without Session usage.

2- Error Handling

Laravel seems to take care of a lot of things for you. That's good. But what about things we don't want? Redirect seems to be one of them. I don't want any redirect since I'm working on a REST API, all answers must be JSON. There's a great deal of information at Sven's response, but no correct answer at simdep's question and a more complex and more overwhelming way to handle by ellipsesynergie.

3 - Nested Routes/Controllers

sebdesign's answer is by far the most helpful information I could find. It gives a nice structure and clean controllers. But he mentions custom Requests. Ine1030 seems to teach you how to overwrite Laravel's default request and matthewdaniel gives you an insight of structuring your request folder. What about matching it all with Authorization and Authentication mentioned in section 1? Form Request and Controller Validation episode gives an insight about it, but it's a MVC web application, not an API.

4 - Wrapping all up

Let's think about a Ticket and a User model. Customer A opens a ticket 1. endpoint: /customer/{customer}/ticket/{ticket}

An attendant needs to give attention to a ticket. endpoint: /employer/{employer}/ticket/{ticket}

This is the best routing option I could come up with after smashing my head against nested controllers. Now I just have to check the token, validate the role, handle unauthorized access, handle form validation and return json.

Let's not talk about Database Seed, Unit Test and API Versioning right now

References:

0 likes
0 replies

Please or to participate in this conversation.