php - How To seperate Requests from controller for making code cleaner


in some cases in my controller i have to recive like 12 params from my client side and i have to like below for each of variables :

$something = $request->get('something');

this makes like 100 line of code extra in my controller for like 10 methods and i want to make my controller short and readable so i want to know if there is any way to seperate this code form my controller and recive them in my controller and use them in my method so my code will become cleaner and more readble




Create Service classes to put logic in it:

class IngredientService
     * @param array $data
     * @return mixed
    public function storeIngredient(array $data)
        $ingredient = Ingredient::create([
            'unit_id' => array_get($data, 'unit_id'),
            'price' => array_get($data, 'price'),
            'name' => array_get($data, 'name')

        return $ingredient;

Then you use it in your controller like below:

class IngredientController {
  public function store(Request $request, IngredientService $ingredientService)
    $ingredient = $ingredientService->store($request->toArray())



You can get your table column and then check if the request has that column name and if so add the data to database. The first step is putting this in your model


public function getTableColumns() {
    return $this->getConnection()->getSchemaBuilder()->getColumnListing($this->getTable());

And then in the controller method where you save the data:


    $something = new Something();
    $somethingColumns = $something->getTableColumns();
    foreach($somethingColumns as $column){
            $something->$column = request($column);

People are also looking for solutions to the problem: php - Cannot catch an Exception while authenticating user with HybridAuth


Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.