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

sevenTopo's avatar

Laravel Rest Api web and mobile

Hello every one ,i have an existing web application created with laravel wich all the controllers return views (blades) with data etc...

for now everything work fine but i'm plaining to use those services for a mobile app using the REST API .how can

i do that without recreating a copy of my controllers or routes ..(i want to use the same routes and controllers ).

do you have any idea guys.

0 likes
5 replies
Nakov's avatar
Nakov
Best Answer
Level 73

@seventopo in case you have your business logic in a separate layer, like services or repositories then you will again need to create different endpoints in the api.php file in this case, and they will be served by different controllers, as they will need to return a JSON representation of the data, and not a blade view.

But if you have everything in the controller, like the calls to your database and so on.. then the easiest thing is to check on the request:

$users = User::all();

if($request->wantsJson())
{
   return $users;
}

return view('users.index', ['users' => $users]);

This is just a simple example, but I would suggest you go with the first point, creating separate routes and separate controllers, but having your business logic in a separate layer as well.

goldtaste's avatar

+1 for @nakov 's reply.

Another solution - and it might be quite painful - is to rewrite your web front end (possibly using vue) to consume json too. It will be a lot of work, but will ensure that your mobile and web app are using the same backend.

1 like
goldtaste's avatar

PS That will also mean that you have to refactor your existing backend, but going forward backend changes will only need to be made in one place. As mentioned, it won't be fun to do in the first place.

1 like
sevenTopo's avatar

Thank you guys for your help.i choosed Nakov 's solution . returning two tipes of data and depending to my request if it need json response i'll return json if it's not by default returning a blade with my array(data) for exemple . thank you all.

Please or to participate in this conversation.