PHP code example of hendabastian / laracrud-apigen
1. Go to this page and download the library: Download hendabastian/laracrud-apigen library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
// app/Repositories/Contracts/OrderRepositoryInterface.php
namespace App\Repositories\Contracts;
use Illuminate\Database\Eloquent\Collection;
interface OrderRepositoryInterface extends BaseRepositoryInterface
{
public function list(): mixed;
public function findByStatus(string $status): Collection;
public function cancelExpiredOrders(): int;
}
// app/Repositories/OrderRepository.php
namespace App\Repositories;
use App\Models\Order;
use App\Repositories\Contracts\OrderRepositoryInterface;
use Illuminate\Database\Eloquent\Collection;
class OrderRepository extends BaseRepository implements OrderRepositoryInterface
{
public function __construct(Order $model)
{
parent::__construct($model);
}
public function findByStatus(string $status): Collection
{
return $this->model->where('status', $status)->get();
}
public function cancelExpiredOrders(): int
{
return $this->model
->where('status', 'pending')
->where('expires_at', '<', now())
->update(['status' => 'cancelled']);
}
}
// app/Repositories/UserRepository.php
namespace App\Repositories;
use App\Models\User;
use App\Repositories\Contracts\UserRepositoryInterface;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Hash;
class UserRepository extends BaseRepository implements UserRepositoryInterface
{
public function __construct(User $model)
{
parent::__construct($model);
}
public function create(array $data): Model
{
if (isset($data['password'])) {
$data['password'] = Hash::make($data['password']);
}
return parent::create($data);
}
public function update(int $id, array $data): Model
{
if (isset($data['password'])) {
$data['password'] = Hash::make($data['password']);
}
return parent::update($id, $data);
}
}
// app/Http/Controllers/Api/OrderController.php
// Add this method to the generated controller:
public function cancel(Order $order): JsonResponse
{
if ($order->status === 'shipped') {
return response()->json(['message' => 'Cannot cancel a shipped order.'], 422);
}
$this->repository->update($order->id, ['status' => 'cancelled']);
return response()->json(['message' => 'Order cancelled successfully.']);
}