I have define user relation with portfolio but it giving me null my user model is
class User extends Model implements AuthenticatableContract,
AuthorizableContract,
CanResetPasswordContract
{
use Authenticatable, Authorizable, CanResetPassword;
protected $table = 'users';
protected $fillable = ['name', 'email', 'password'];
protected $hidden = ['password', 'remember_token'];
public function portfolio()
{
$this->hasMany('App\Portfolio');
}
}
My portfolio model is
class Portfolio extends Model
{
protected $fillable = ['user_id', 'ptitle', 'pdate','pedate','purl','languages','pdes','attachments'];
public function user()
{
$this->belongsTo('App\User');
}
public function attachments()
{
$this->hasMany('App\Attachment');
}
}
and I have define foreign key on migration my migration code is
public function up()
{
Schema::create('portfolios', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->string('ptitle');
$table->timestamps();
$table->foreign('user_id')
->references('id')
->on('users')
->onDelete('cascade');
});
}
I run the migration again. when i try get user portfolios it giving me null value i declare this on the top of my controller use App\\User;
then i am finding the user by this command $user=User::find(1)
and finally i doing this $user->portfolio()
but it giving me null i am stuck in that from 2 to 3 hour please help me
you should return the relationship to get relation data
public function portfolio()
{
return $this->hasMany('App\Portfolio');
}
Basic shortend example setup (used in the following example):
class User extends Model {
public function portfolio()
{
//you missed the return
return $this->hasMany('App\Portfolio');
}
}
class Portfolio extends Model {
public function user()
{
//you missed the return
return $this->belongsTo('App\User');
}
}
Assuming you have an user with ID 1 and a related portfolio entry:
$mUser = User::findOrFail(1); //Return User model
$mUserLazy = User::with('portfolio')->findOrFail(1); //Preload portfolio
$mPortfolioQueryBuilder = $mUser->portfolio(); //QueryBuilder
$aPortfolio = $mUser->portfolio; //Portfolio Collection
$aPortfolio = $mUserLazy->portfolio; //Portfolio Collection
$aPortfolio = $mPortfolioQueryBuilder->get(); //Portfolio Collection
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.