Create a Laravel project.
php artisan make:model Event --mcr
Create a folder named as Interfaces under app.
Create EventRepositoryInterface.php inside the folder
EventRepositoryInterface.php:
<?php
namespace App\Interfaces;
interface EventRepositoryInterface
{
public function getAllEvents();
public function getEventById($eventId);
public function deleteEvent($eventId);
public function createEvent(array $eventDetails);
public function updateEvent($eventId, array $newDetails);
}
As it's an Interface it only supports public methods, create required methods.
Create a folder named as Repositories under app.
Create EventRepository.php inside the folder
EventRepository.php:
<?php
namespace App\Repositories;
use App\Interfaces\EventRepositoryInterface;
use App\Models\Event;
class EventRepository implements EventRepositoryInterface
{
public function getAllEvents()
{
return Event::all();
}
public function getEventById($eventId)
{
return Event::findOrFail($eventId);
}
public function deleteEvent($eventId)
{
Event::destroy($eventId);
}
public function createEvent(array $eventDetails)
{
return Event::create($eventDetails);
}
public function updateEvent($eventId, array $newDetails)
{
return Event::whereId($eventId)->update($newDetails);
}
}
Using the Repository in the controller
<?php
namespace App\Http\Controllers;
use App\Interfaces\EventRepositoryInterface;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
class EventController extends Controller
{
private EventRepositoryInterface $eventRepository;
public function __construct(EventRepositoryInterface $eventRepository)
{
$this->eventRepository = $eventRepository;
}
public function index(): JsonResponse
{
return response()->json([
'data' => $this->eventRepository->getAllEvents()
]);
}
public function store(Request $request): JsonResponse
{
$res = $this->eventRepository->createEvent($eventDetails);
return response()->json([
'data' => $res
]);
}
}
Lastly the Repository service provider needs to be created, booted and the repository file needs to be mapped for that
php artisan make:provider RepositoryServiceProvider
Inside the RepositoryServiceProvider's boot function mapp the interface with the repo:
$this->app->bind(EventRepositoryInterface::class,EventRepository::class);
Also add the the new Service Provider to the providers array in config/app.php so that Laravel boots it when the app boots
'providers' => [
// ...other declared providers
App\Providers\RepositoryServiceProvider::class,
];
Top comments (0)