How would I share this between both API and web controllers for same resource? Or I would repeat it here and there? What is the best practices for such solution?
@sh1r3f If you have common code that you want to use in multiple places, then this is where you would re-factor by extracting it to a single place. So as you mentioned in your post, a service or something.
Extract the Eloquent queries to a service, and then use that service in both your web and API controllers. If you need to update the query, you then only need to do it in one location:
namespace App\Services;
use Illuminate\Pagination\LengthAwarePaginator;
class ArticleService
{
public function getPaginatedList(): LengthAwarePaginator
{
return Article::query()->paginate();
}
}
namespace App\Http\Controllers\Api;
class ArticleController extends Controller
{
protected $articleService;
public function __construct(ArticleService $articleService)
{
$this->articleService = $articleService;
}
public function index()
{
return ArticleResource::collection($this->articleService->getPaginatedList());
}
}
namespace App\Http\Controllers\Web;
class ArticleController extends Controller
{
protected $articleService;
public function __construct(ArticleService $articleService)
{
$this->articleService = $articleService;
}
public function index()
{
return view('articles.index')->with([
'articles' => $this->articleService->getPaginatedList(),
]);
}
}
So as you see, both controllers get the ArticleService injected and then the same method is called on that service, but the controller presents the result different depending on if it is an API controller or a web controller.