Reputation: 1394
I'm trying to maintain a skinny controller, but I'm still getting used to what can go in my controller, since before I used to pile just about everything inside of it. In this example I'm inserting validated data into a database, which I assumed is correct. What I'm confused about is that I want to take one of the field inputs, manipulate its text formatting and then save it to another field in my database. What I have written works, but I don't know if its good to have this code in my controller, if not where should it go?
Controller
public function store()
{
$validation = new Services\Validators\Deal;
if($validation->passes())
{
$deals = Deals::create(Input::all());
// start code in question
$image = Input::get('company');
$image = strtolower($image);
$image = str_replace(" ", "-", $image);
$image .= ".png";
$deals->image = $image;
$deals->save();
// end code in question
return Redirect::to('deals/create')
->with('message', 'Deal Created');
}
return Redirect::back()
->withInput()
->withErrors($validation->errors);
}
To recap, I'm not sure if the code in question belongs in my controller, and if it doesn't, where would it be better placed? Thanks for any insights.
Upvotes: 1
Views: 168
Reputation: 87789
Any business logic should be placed in models, or repositories and your controller should look just like
<?php
class DealsController extends controller {
public function __construct(Deals $deals) //// <---- Dependency Injection
{
$this->deals = $deals;
}
public function store()
{
try
{
$this->deals->insertRow(Input::all());
}
catch (\Exceptions\ValidationException $e)
{
return Redirect::back()
->withInput()
->withErrors($this->deals->errors);
}
return Redirect::to('deals/create')
->with('message', 'Deal Created');
}
}
And in your Deals class, you do whatever you need to do with your data
class Deals extends Eloquent {
public function insertRow($input)
{
$validation = new Services\Validators\Deal;
if($validation->passes())
{
$deals = Deals::create($input);
// start code in question
$image = $input['company'];
$image = strtolower($image);
$image = str_replace(" ", "-", $image);
$image .= ".png";
$deals->image = $image;
$deals->save();
// end code in question
}
$this->errors = $validation->errors;
throw new \Exceptions\ValidationException("Error inserting Deals", $validation->errors);
}
}
This is untested and a not-really-refactored code, but I hope you can see a point in it.
Upvotes: 2
Reputation: 1
You could actually remove all the code in question and use Laravel Mutator instead.
Basically, setup a function in your Deals class which will automatically process the text formatting whenever data is about to be set/save via the Model Eloquent ::create, or update.
Something like
public function setImageAttribute($value)
{
$image = strtolower($value);
$image = str_replace(" ", "-", $image);
$image .= ".png";
$this->attributes['image'] = $image;
}
Refer to http://laravel.com/docs/eloquent#accessors-and-mutators
Upvotes: 0