Support the ongoing development of Laravel.io →
posted 9 years ago
Eloquent
Last updated 1 year ago.
0

For your own sake, post additional information or you will not get any help with your problem.

0

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
Last updated 9 years ago.
0

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().

Last updated 9 years ago.
0

Sign in to participate in this thread!

Eventy

Your banner here too?

lovePizza lovepizza Joined 13 Mar 2014

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2024 Laravel.io - All rights reserved.