P
P
Pavel Konchich2021-08-04 00:25:57
Laravel
Pavel Konchich, 2021-08-04 00:25:57

How to get rid of repetitions in Laravel 8 code?

Tell me, how to get rid of repetitions of such code in each function of the controller?

public function home(Request $request)
{
    $agent = new Agent();
    $device = $agent->device();
    $viewer = New Viewers();
    $ip = $request->ip();
    $data = Location::get($ip);

    $viewer->request_uri = $request->getRequestUri();
    $viewer->ip_address = $ip;
    $viewer->country = $data->countryName;
    $viewer->city = $data->cityName;
    if($agent->isMobile()){
        $phone = $agent->isPhone();
        $viewer->device = $agent->platform();
    } else if($agent->isTablet()) {
        $viewer->device = $agent->device();
    } else if($agent->isRobot()) {
        $robot = $agent->robot();
        $viewer->device = $robot;
    } else {
        $platform = $agent->platform();
        $viewer->device = $platform;
    }

    $viewer->save();

   }

This part will be repeated in each function - and this is already too much code clutter.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey Ukolov, 2021-08-04
@konchychp

Logging request data is a middleware job .

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question