I'm trying to utilize the eager loading feature in laravel but it doesn't work as i expected. When i try to check the profile of user who doesn't have information in Profiles table it throws "Trying to get property of non-object" instead of giving a NULL value. I have separated users information into two tables -> users table and Profiles table. How can i get past that?!
ProfilesController.php
use Illuminate\Database\Eloquent\ModelNotFoundException;
class ProfilesController extends \BaseController {
public function show($username)
{
try {
$user = User::with('profile')->whereUsername($username)->firstOrFail();
} catch (ModelNotFoundException $e) {
return Redirect::home()->with('globalerror', 'The user you are trying to search does not exists!');
}
return View::make('profiles.show')->withUser($user);
}
}
Profiles.php Model
class Profile extends Eloquent
{
public function owner(){
return $this->belongsTo('User', 'user_id');
}
}
Users.php model
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableInterface;
class User extends Eloquent implements UserInterface, RemindableInterface {
protected $table = 'users';
protected $fillable = array('first_name', 'last_name', 'username', 'email', 'password', 'password_temp', 'code', 'active');
public function profile(){
return $this->hasOne('Profile');
}
}
That is one downfall of using the with()
function. It will return a user even if the user does not have a profile.
What you can do is make sure there is a profile using something like isset($user->profile) ? $user->profile : 'user does not have a profile';
Or you can use has()
in place of with()
which will only get the user if it has a profile.
You may try this:
$user = User::with('profile')->whereUsername($username)->firstOrFail();
return View::make('profiles.show')->withUser($user);
Then in your view
; you may try something like this:
@if(isset($user) && isset($user->profile))
{{ $user->profile->propertyname or '' }}
@endif
The only way which works so far , i have decided to manually insert a user id into the profiles table whenever new user registers. This will make eager loading work without problems because it won't return null anymore. Here is the code:
$profile = new Profile;
$profile->user_id = $user->id;
$profile->save();`
Hope it might help someone out there someday