D
D
Denis Kainazarov2014-08-15 13:49:59
Laravel
Denis Kainazarov, 2014-08-15 13:49:59

Laravel why does the one-to-one model not work?

I set up models in laravel user and profile
User::find(1)->Profile outputs

LogicException

Relationship method must return an object of type Illuminate\Database\Eloquent\Relations\Relation

Migration
public function up()
  {
        Schema::create('users',function($table){
            $table->increments('id');
            $table->string('email');
            $table->string('password');
            $table->string('status')->default('new');
            $table->string('status_ex')->default('new');
            $table->string('type')->default('user');
            $table->string('remember_token');
            $table->timestamps();
            $table->softDeletes();
            $table->unique('email');
            $table->index(['id','email','status','status_ex','type']);
        });
        Schema::create('profiles',function($table){
            $table->increments('id');
            $table->integer('user_id')->unsigned();
            $table->string('name');
            $table->string('family');
            $table->timestamps();
            $table->softDeletes();
            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
        });
  }

Models
class Profile extends Eloquent {

    protected $table = 'profiles';

    protected $guarded = array('id');

    protected $softDelete = true;

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

and
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;

  /**
   * 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');
    /**
     * Guarded attributes
     *
     * @var array
     */
    protected $guarded = array('id', 'password','remember_token');
    /**
     * Soft delete
     *
     * @var bool
     */
    protected $softDelete = true;
    /**
     * User profile
     */
    public function Profile(){
        return $this->hasMany('Profile');
    }

i.e. through the profile you can get the user, but not vice versa.
What could be the problem?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Vinogradov, 2014-08-15
@iit

For a one-to-one relationship, you need to use the hasOne method , not hasMany.
It should be like this:

/**
 * User profile
 */
public function Profile(){
    return $this->hasOne('Profile');
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question