Answer the question
In order to leave comments, you need to log in
How to connect repository to middleware in Laravel?
I make a city selection based on the language choice in Laravel
for cities, I have a CityRepository repository
<?php
namespace App\Repository\Eloquent;
use App\Repository\Contracts\CityRepositoryInterface;
use Illuminate\Database\Eloquent\Model;
class CityRepository extends BaseRepository implements CityRepositoryInterface
{
public function __construct(Model $model)
{
parent::__construct($model);
}
}
<?php
namespace App\Services\Api\V1;
use App\Repository\Contracts\CityRepositoryInterface;
use App\Traits\Api\V1\Messages\ResponseTrait;
class CityService
{
use ResponseTrait;
public function show(int $id)
{
$model = $this->repository->findById($id);
if (!$model)
return $this->notFoundApiResponse([], 'Запись не найдена!');
return $this->successModelApiResponse($model, '');
}
}
<?php
namespace App\Http\Middleware\Client;
use Illuminate\Support\Facades\Request;
class RegionMiddleware
{
public static function getRegion()
{
$uri = Request::path(); //получаем URI
$segmentsURI = explode('/', $uri); //делим на части по разделителю "/"
//Проверяем slug города - есть ли он среди доступных городов
if (!empty($segmentsURI[0])) {
$cities = $city->getAll();
$rec = $cities->firstWhere('slug', $segmentsURI[0]);
if ($rec->slug) {
$current = $cities->firstWhere('is_current', 1);
if ($segmentsURI[0] != $current->slug) return $segmentsURI[0];
}else dd(Request::getBaseUrl());
}
return null;
}
public function handle($request, \Closure $next)
{
//Убираем дубли из URI (public и public/index.php)
if (preg_match("/^\/(public)|(public\/index.php)/", $request->getBaseUrl())) {
$newUrl = str_replace($request->getBaseUrl(), '', $request->getUri());
header('Location: ' . $newUrl, true, 301);
exit();
}
$lang = self::getRegion();
return $next($request);
}
}
<?php
namespace App\Providers\Client;
use App\Http\Middleware\Client\RegionMiddleware;
use App\Providers\RouteServiceProvider;
use Illuminate\Support\Facades\Route;
class RegionServiceProvider extends RouteServiceProvider
{
public function boot()
{
parent::boot();
/*
* Cоздаем префикс для всех маршрутов и устанавливаем посредника
* Для корректной работы префикса, класс наследуется от RouteServiceProvider
*/
$prefix = RegionMiddleware::getRegion();
Route::prefix($prefix)
->middleware(LocaleMiddleware::class, 'web')
->namespace('App\Http\Controllers')
->group(base_path('routes/web.php'));
}
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question