Sergej Fomin
Sergej Fomin

Reputation: 2002

Laravel How not to Rewrite the Same code again

I have a model, called Tours and controller ToursController which uses restful methods (index, show, store, edit, update etc).

Now I have this code:

$names = request()->get('names');
$lastnames = request()->get('lastnames');
$hotels = request()->get('hotel');

both in Store and Update. So i duplicate the same code twice. And this is only one exmaple of duplicated code.

I want to create a function "getEverythingFromRequest()"

which I can use in both Store and Update methods. Something like:

public function store (Request $request) {

getEverythingFromRequest();

dd($names[3];

}


public function store (Request $request) {

getEverythingFromRequest();

dd($hotels[2];

}

How can I do it? Globally, how can I avoid re-writing the same code in Controller?

Upvotes: 0

Views: 419

Answers (1)

whoacowboy
whoacowboy

Reputation: 7447

There are a bunch of ways to solve this. One way would be to create a repo that extracts the arrays from your request. (I updated my code to use injection).

Controller

public function store (GuestsRepository $repo, Request $request) {

  dd($repo->names);

}

Repository

<?php

namespace App;

class GuestsRepository
{
    public $names;
    public $lastnames;
    public $hotels;

    public function __construct(){
        $this->names = request()->get('names');
        $this->lastnames = request()->get('lastnames');
        $this->hotels = request()->get('hotel');
    }
}

Upvotes: 2

Related Questions