Support the ongoing development of Laravel.io →
Database Eloquent Views
Last updated 2 years ago.
0

Try this


{{ $user->user_profile()->place_of_birth }}

Last updated 2 years ago.
0

Then i get this

Call to undefined method Illuminate\Database\Query\Builder::user_profile() (View: 
Last updated 2 years ago.
0

Lets start over

Create Migrations

users Table

php artisan migrate:make create_users_table

user_profiles Table

php artisan migrate:make create_user_profiles_table

Edit your migrations

  • Create users Table
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateUsersTable extends Migration {

	/**
	 * Run the migrations.
	 *
	 * @return void
	 */
	public function up()
	{
        Schema::create('users', function(Blueprint $table) {
            $table->engine = 'InnoDB';
            $table->increments('id');
            $table->string('first_name');
            $table->string('last_name');
            $table->string('username')->unique('username', 'users_username_unique');
            $table->string('email')->unique('email', 'users_email_unique');
            $table->string('mobile')->unique('mobile', 'users_mobile_unique');
            $table->string('password');
            $table->softDeletes();
            $table->timestamps();
        });
	}

	/**
	 * Reverse the migrations.
	 *
	 * @return void
	 */
	public function down()
	{
        Schema::drop('users');
	}

}
  • Create user_profiles Table
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateUserProfilesTable extends Migration {

	/**
	 * Run the migrations.
	 *
	 * @return void
	 */
	public function up()
	{
        Schema::create('user_profiles', function(Blueprint $table) {
            $table->engine = 'InnoDB';
            $table->increments('id');
            $table->integer('user_id')->unsigned()->unique('user_id', 'user_profiles_user_id');
            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
            $table->string('place_of_birth');
            $table->timestamps();
        });
	}

	/**
	 * Reverse the migrations.
	 *
	 * @return void
	 */
	public function down()
	{
        Schema::drop('user_profiles');
	}

}

Run your migrations

php artisan migrate

Edit the model User.php

use Illuminate\Auth\UserTrait;
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableTrait;
use Illuminate\Auth\Reminders\RemindableInterface;

class User extends Eloquent implements UserInterface, RemindableInterface {

	use UserTrait, RemindableTrait, SoftDeletingTrait;

	/**
	 * The database table used by the model.
	 *
	 * @var string
	 */
	protected $table = 'users';

	/**
	 * The attributes excluded from the model's JSON form.
	 *
	 * @var array
	 */
	protected $hidden = array('password', 'remember_token');
    /**
     * Blacklist
     *
     * Allow for mass Update
     *
     * @var string
     */
    protected $guarded = array();

    protected $dates = ['deleted_at'];

    public function userProfile()
    {
        return $this->hasOne('UserProfile');
    }

}

Edit the model UserProfile.php

class UserProfile extends Eloquent {
    protected $table = 'user_profiles';
    /**
     * Blacklist
     *
     * Allow for mass Update
     *
     * @var string
     */
    protected $guarded = array();

    public function user()
    {
        return $this->belongsTo('User');
    }
}

Testing the relationship from routes.php

The code below should work, it should be able to add user data belonging to the two tables successfully

Route::get('create', function() {
   return User::create(array(
      'first_name' => 'John',
       'last_name' => 'Doe',
       'username' => 'JohnDoe',
       'email' => '[email protected]',
       'mobile' => '123456789',
       'password' => Hash::make('JohnDoe')
   ));
});

Route::get('create_profile', function() {
    return User::find(1)->userProfile()->save(new UserProfile(array(
        'place_of_birth' => 'texas'
    )));
});

To render your view

Route::get('showme', function() {
    $user = User::find(1);
    return View::make('showme')->with('user', $user);
});

And now to your answer, use this in your blade template [showme.blade.php]

{{ $user->userProfile->place_of_birth }}

####Now everything should work fine

Last updated 2 years ago.
0

Doesn't work...

Models/User_Profiles.php

 <?php

class User_Profile extends Eloquent {
 protected $table = 'user_profiles';
    /**
     * Blacklist
     *
     * Allow for mass Update
     *
     * @var string
     */
    protected $guarded = array();
    /**
     * Allow soft deleting this model
     *
     * @var array
     */
    protected $softDelete = true;

    public function user()
    {
        return $this->belongsTo('User');
    }
}

Models/User.php

<?php

use Zizaco\Confide\ConfideUser;

class User extends ConfideUser {

    /**
     * Allow soft deleting this model
     *
     * @var array
     */
    protected $softDelete = true;

	public function departments()
	{
	   return $this->belongsToMany('Department', 'department_user','user_id','department_id');
	}

    public function projects()
    {
        return $this->belongsToMany('Project', 'project_user');
    }

	/**
     * Get user by email
     * @param $email
     * @return mixed
     */
    public function getUserByEmail( $email )
    {
        return $this->where('email', '=', $email)->first();
    }

    public function user_profile()
    {
        return $this->hasOne('User_Profile');
    }

    public function user_friend()
    {
      //  return $this->belongsToMany('User_Friend');
        return $this->belongsToMany('User', 'User_Friends', 'user_id', 'friend_id');
    }


}

Controller

$user = Confide::user();
    return View::make('department.create')->with('user', $user);

view

{{ $user->user_profile->firstname }}

ERROR

Trying to get property of non-object (View:
Last updated 2 years ago.
0

hmm that's interesting, in your controller just try and do this

$user = Confide::user();
dd($user);

I would like to see the result, post it back

Last updated 2 years ago.
0
object(User)#274 (29) { ["softDelete":protected]=> bool(true) ["table":protected]=> string(5) "users" ["hidden":protected]=> array(1) { [0]=> string(8) "password" } ["autoHashPasswordAttributes"]=> bool(true) ["updateRules":protected]=> array(4) { ["username"]=> string(19) "required|alpha_dash" ["email"]=> string(14) "required|email" ["password"]=> string(15) "min:4|confirmed" ["password_confirmation"]=> string(5) "min:4" } ["validationErrors"]=> object(Illuminate\Support\MessageBag)#275 (2) { ["messages":protected]=> array(0) { } ["format":protected]=> string(8) ":message" } ["throwOnValidation"]=> bool(false) ["autoHydrateEntityFromInput"]=> bool(false) ["forceEntityHydrationFromInput"]=> bool(false) ["autoPurgeRedundantAttributes"]=> bool(false) ["purgeFilters":protected]=> array(0) { } ["purgeFiltersInitialized":protected]=> bool(false) ["connection":protected]=> NULL ["primaryKey":protected]=> string(2) "id" ["perPage":protected]=> int(15) ["incrementing"]=> bool(true) ["timestamps"]=> bool(true) ["attributes":protected]=> array(9) { ["id"]=> int(1) ["username"]=> string(7) "RokSiEu" ["email"]=> string(23) "[email protected]@gmail.com" ["password"]=> string(60) "$2y$10$foH8QSmXbkTkY4FcCww4DulWRE3kbmAwxDIePL.81rMoMrI.4HlmS" ["confirmation_code"]=> string(32) "fc8bfa48b06e7b79825e2c676c4536a4" ["confirmed"]=> int(0) ["created_at"]=> string(19) "2014-05-25 21:57:05" ["updated_at"]=> string(19) "2014-05-25 21:57:05" ["deleted_at"]=> string(19) "0000-00-00 00:00:00" } ["original":protected]=> array(9) { ["id"]=> int(1) ["username"]=> string(7) "RokSiEu" ["email"]=> string(23) "[email protected]@gmail.com" ["password"]=> string(60) "$2y$10$foH8QSmXbkTkY4FcCww4DulWRE3kbmAwxDIePL.81rMoMrI.4HlmS" ["confirmation_code"]=> string(32) "fc8bfa48b06e7b79825e2c676c4536a4" ["confirmed"]=> int(0) ["created_at"]=> string(19) "2014-05-25 21:57:05" ["updated_at"]=> string(19) "2014-05-25 21:57:05" ["deleted_at"]=> string(19) "0000-00-00 00:00:00" } ["relations":protected]=> array(0) { } ["visible":protected]=> array(0) { } ["appends":protected]=> array(0) { } ["fillable":protected]=> array(0) { } ["guarded":protected]=> array(1) { [0]=> string(1) "*" } ["dates":protected]=> array(0) { } ["touches":protected]=> array(0) { } ["observables":protected]=> array(0) { } ["with":protected]=> array(0) { } ["exists"]=> bool(true) }
Last updated 2 years ago.
0

Do you need anything else?

Last updated 2 years ago.
0

from the dump you can see that the relation is not attached

["relations":protected]=> array(0) { } ...........

so trying to access it through

{{ $user->user_profile->firstname }}

triggers an error, because it does not exist.

How did you create your tables? Was it through migrations or manually in mysql? Because i am thinking your table relationships are not set up properly.

Last updated 2 years ago.
0

It was through migrations and then exported in mysql and imported on production server.

Edit: I only run migration for user_profiles table, because user table was created by Confide.

Last updated 2 years ago.
0

Okay, i have not used confide before but i dont think that is the cause of the issue. Can i see the migration for the user_profiles table, its the one that is important....because we have to create a foreign key from it to the id on the users table that Confide created

Last updated 2 years ago.
0

use this link to paste your code, save it then let me have the link

Last updated 2 years ago.
0

Here it is: http://laravel.io/bin/E8GL2

Really thanks !

Last updated 2 years ago.
0

Your migration is fine, I think i have seen the problem....you are using the ConfideUser Model, which does not have the relationship set into it, you have to use the model that extends the ConfideUser which is User from your above code

can i see this dump

dd(User::find(1)->user_profile());

Make sure the 1 is be an existing id of a user

Last updated 2 years ago.
0

I must warn you that dump file is big... http://laravel.io/bin/DPqDW

Last updated 2 years ago.
0

Thats a big one....do you still get an error when you do this

Controller

$user = User::find(1);
return View::make('department.create')->with('user', $user);

View

{{ $user->user_profile->firstname }}
Last updated 2 years ago.
0

Please add to User model: Overidding getAttribute method from Illuminate\Database\Eloquent\Model

    public function getAttribute($key)
    {
        $profile = Profile::where('user_id', '=', $this->attributes['id'])->first()->toArray();

        foreach ($profile as $attr => $value) {
            if (!array_key_exists($attr, $this->attributes)) {
                $this->attributes[$attr] = $value;
            }
        }
        
        return parent::getAttribute($key);
    }

And try

{{ $user->place_of_birth }}
Last updated 9 years ago.
0

evandertino, thanks for many helpful tips! nurmanhabib, work perfectly!

0

Sign in to participate in this thread!

Eventy

Your banner here too?

RokSiEu roksieu Joined 31 Jan 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.