Reputation: 2000
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
Upvotes: 0
Views: 44
Reputation: 1354
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())
}
}
Upvotes: 2
Reputation: 4153
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
Model
public function getTableColumns() {
return $this->getConnection()->getSchemaBuilder()->getColumnListing($this->getTable());
}
And then in the controller method where you save the data:
Controller
$something = new Something();
$somethingColumns = $something->getTableColumns();
foreach($somethingColumns as $column){
if(request($column)){
$something->$column = request($column);
}
}
$something->save();
Upvotes: 0