Latest

Tuesday, July 11, 2017

Laravel How not to Rewrite the Same code again

Asked by: Sergej Fomin


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?


Answers

Answered by: whoacowboy at 2017-07-11 09:03PM



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



Source

No comments:

Post a Comment

Adbox