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

adesugbaa's avatar

Laravel app for web and api

What is the best practice for designing a single application that contains an API that will be used by mobile devices, and also has a web application?

Do I design single controllers with logic that checks if user wants JSON? or dedicated controllers for web and api - if yes, how to I prevent duplication of logic. I assume there will be similarities - they will typically handle data in the same way, but one will return json, while other redirects or sends data to to given view. Can the common code be moved to a separate layer eg services?

Any help including open source code will be appreciated.

Thanks.

0 likes
6 replies
bobbybouwmann's avatar

I would split them both up! So everything related to your web application can be found in the following files

  • routes/web.php
  • app/Http/Controllers

Everything related to your api should be available in

  • routes/api.php
  • app/Http/Controllers/Api

Note that the routes setup come by default in Laravel. You can easily create your own routes with a different namespace in the RouteServiceProvider to keep them separated.

It's best practice to create service classes and/or repositories that can be reused in both controllers.

Let me know if you have more questions or need more examples ;)

adesugbaa's avatar

Thanks for the response.

I would love an example of a service class/repository, and how it gets used by the controllers.

jlrdw's avatar

Are you actually needing an API or just mobile friendly for the application.

bobbybouwmann's avatar
Level 88

You will probably get something like this

// app/Repositories/PostsRepository.php

class PostsRepository
{
    public function list(): Collection
    {
        return Post::all();
    }
}

// app/Http/Controllers/PostsController.php

class PostsController extends Controller
{
    public function index(PostsRepository $postsRepository)
    {
        $posts = $postsRepository->list();

        return view('posts.index', compact('posts'));
    }
}

// app/Http/Controllers/Api/PostsController.php

class PostsController extends Controller
{
    public function index(PostsRepository $postsRepository)
    {
        $posts = $postsRepository->list();

        return response()->json(compact('posts'));
    }
}

I would personally use something like the new API resources from Laravel for your API responses, check this out: https://laracasts.com/series/whats-new-in-laravel-5-5/episodes/20

Note: This is a really basic example but you probably get the gist of it :)

jekinney's avatar

Resources too. Helps maintain your allowed data via ajax (think fractal)

Please or to participate in this conversation.