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');
}
}