S
S
SM_ST2021-06-14 10:24:06
Laravel
SM_ST, 2021-06-14 10:24:06

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);
    }
}

and a service layer that handles the cities repository
<?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, '');
    }
}

have middleware
<?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);
    }
}

and a service provider that substitutes the prefix
<?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'));
    }
}

How can I call a repository or service layer in a static method to get a list of cities?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
Eugene, 2021-06-14
@Nc_Soft

For that fought for it and ran. Use something like app->make
https://laravel.com/docs/8.x/container

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question