PHP code example of surazdott / laravel-repository
1. Go to this page and download the library: Download surazdott/laravel-repository 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/ */
surazdott / laravel-repository example snippets
namespace App\Repositories\Interfaces;
use Illuminate\Database\Eloquent\Model;
interface UserRepositoryInterface
{
/**
* Find database record by id.
*
* @param mixed $id
*/
public function findById(string $id): ?Model;
}
namespace App\Repositories;
use App\Models\User;
use App\Repositories\Interfaces\UserRepositoryInterface;
use Illuminate\Database\Eloquent\Model;
use SurazDott\Repositories\BaseRepository;
class UserRepository extends BaseRepository implements UserRepositoryInterface
{
/**
* Create new repository instance.
*/
public function __construct(
protected User $model
) {
}
/**
* Find database record by id.
*/
public function findById(string $id): ?Model
{
return $this->model->find($id);
}
}
namespace App\Services;
use App\Repositories\UserRepository;
use Illuminate\Support\Collection;
use Illuminate\Database\Eloquent\Model;
use SurazDott\Services\BaseService;
class UserService extends BaseService
{
/**
* Create new service instance.
*/
public function __construct(
protected UserRepository $repository
) {
}
/**
* Find database record by id.
*
* @param string $id
*/
public function findById($id): ?Model
{
return $this->repository->findById($id);
}
}
namespace App\Http\Controllers;
use App\Services\UserService;
use Illuminate\View\View;
use Illuminate\Http\Request;
class UserController extends Controller
{
/**
* Create a new controller instance.
*/
public function __construct(
private UserService $users
) {
}
/**
* Display a listing of the resource.
*/
public function edit(Request $request): View
{
$data['user'] = $this->users->findById($id);
return view('admin.users.edit', $data);
}
}
namespace App\Http\Controllers;
use App\Services\UserService;
use Illuminate\View\View;
use Illuminate\Http\Request;
class UserController extends Controller
{
/**
* Create a new controller instance.
*/
public function __construct(
private UserService $users
) {
}
/**
* Display a listing of the resource.
*/
public function index(): View
{
// get all users
$data['users'] = $this->users->query()->latest()->get();
// get active users
$data['activeUsers'] = $this->users->query()->where('status', true)->get();
return view('admin.users.index', $data);
}
/**
* Show the form for editing the specified resource.
*/
public function edit(Request $request): View
{
$data['user'] = $this->users->findById($id);
return view('admin.users.edit', $data);
}
}