Reputation: 1394
I'm trying to maintain an MVC pattern using the Laravel 4 framework, in my last project I made all the database queries from the controller, I have now learned that is a terrible practice and I'm trying to figure out how to do the same from the model. Here is what I would normally do.
Controller
public function serve($company)
{
$review = Review::select('head', 'body', 'logo', 'name')->where('company', '=', $company)->firstOrFail();
return View::make('layouts.singlereview', compact('review'));
}
Model
class Review extends Eloquent {
protected $table = 'reviews';
protected $guarded = [
'id', 'company', 'head', 'body'
];
}
When I move the $review
variable and database query into the model then I get the error on the view with undefined variable. How do I pass the $review
variable from the model to the controller?
Thanks!
Upvotes: 1
Views: 196
Reputation: 452
Also, while you are on the subject of creating good code, you might as well check out Eloquent relationships. They may require database restructuring for certain occurrences, but most of the time you should be good.
With the code you have provided, I can assume that review and company are in a one-to-one relationship, so once this is defined, you can simply retrieve a company object, then do,
$review = $company->review;
Upvotes: 0
Reputation: 87759
Actually you will still need to do some stuff with your Models in your controller. Use Repository Pattern do to so, which is pretty similar of querying your models in your controller, but being less verbose:
public function serve($company)
{
return View::make('layouts.singlereview')->withReview(with(new Review)->getCompanyData($company));
}
And put the whole logic in your repository:
class Review extends Eloquent {
public function getCompanyData($company)
{
return static::select('head', 'body', 'logo', 'name')
->where('company', '=', $company)
->firstOrFail();
}
}
Upvotes: 2