Adil
Adil

Reputation: 27

Relationship function is not working in laravel

relationship function is not working of any type. i am creating 2 tables relationship of one to many but it is not working i have no idea at all about that i have follow tutorials and laravel documentation as well but all is vain please guide me thanks.

//this is user model..

<?php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    use Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name','email','password','image','candidate_id'
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];
//

}



// and this is candidate model.


<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Candidate extends Model
{
    public function user()
    {
        return $this->hasOne('app\User');
    }
}

Upvotes: 1

Views: 128

Answers (2)

Adil
Adil

Reputation: 27

All things were correct, I just call a single attribute of a second table instead of function. In Laravel we call function of related table not its attribute this is the mistake.

Upvotes: 0

ZeroOne
ZeroOne

Reputation: 9117

It shows your model User store candidate_id, so there is 1 Candidate many User..

in Candidate model (Table Name should be candidates)

public function user()
{
    return $this->hasMany(User::class);
}

in User model (Table Name should be users)

public function candidate()
{
    return $this->belongsTo(Candidate::class);
}

Upvotes: 1

Related Questions