For your own sake, post additional information or you will not get any help with your problem.
For example I need to run a method in the model class:
class User extends Eloquent
{
public function getAge()
{
$from = new DateTime($this->born);
$to = new DateTime('today');
return $from->diff($to)->y;
}
}
But I need to execute an advanced query like this:
class UserController extends \BaseController
{
public function index()
{
$users = DB::table('users')
->select('users.*')
->join('cities', 'users.city_id', '=', 'cities.id')
->where('cities.name', '=', Input::get('city'))
->get();
return View::make('users.index')->with('users', $users);
}
}
And I need to print the age of my user in Blade (ERROR HERE):
@foreach ($users as $user)
<div class="result">
{{{$user->username}}}"
<div class="age">{{ $user->getAge() }}</div>
</div>
@endforeach
You should use Eloquent relationships instead of db and joins to accomplish what you are doing in your controller.
You would want a hasOne relationship. This is written on mobile and is not tested, but should work.
On your user model add something like this:
public function city()
{
return $this->hasOne('City');
}
To select the user, like you do in your controller:
$users = User::whereHas('city', function($q) {
$q->where('name', Input::get('city'));
})->get();
Read about relationships in the documentation, it would have teached you this kind of stuff :-)
And just a tip for your getAge function. If you name the function getAgeAttribute instead you can retrieve it's return value by $model->age instead of $model->getAge().
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community