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

mishasneg's avatar

Share business logic between web app and api

Hey, I am building a web app with classic Laravel routers views controllers, and also building an API that mobile apps will consume. I am wondering what would be the best approach to share business logic between these two things?

One solution might me calling my own API from views, but it doesn't seem right.

0 likes
3 replies
PovilasKorop's avatar

If they are two separate projects, then create your own package that both would consume. If they are within the same Laravel project, then create some Service classes that both would consume.

artcore's avatar

I would use a job (Command Bus) which can be used in a controller and also console for instance

UsersController some auth middleware

index() dispatch_now(...new GetUsersJob())

================================

ApiUsersController some other auth middleware

index() dispatch_now(...new GetUsersJob())

================================

Artsisan console handle() dispatch_now(...new GetUsersJob())

https://laravel.com/docs/7.x/queues#creating-jobs

They can be queued to run later on a new thread dispatch() or right away dispatch_now

Very handy and flexible and no need for complex service layers although a repository may work too come to think of it ;)

Please or to participate in this conversation.