I've two model called application and user.
id | name
id | first name
id | application_id | user_id | comment| rating | like
Here is the model classes
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use App\ModelValidator;
class Application extends ModelValidator
{
//
protected $table = "application";
public function user()
{
return $this->belongsToMany('App\User','application_user','application_id','user_id')->withPivot(['rating','like','comment'])->withTimestamps();
}
public function getComment()
{
$comments = array();
foreach ($this->user as $user) {
$comments[] = $user->comment;
}
return compact($comments);
}
}
<?php
namespace App;
use Illuminate\Auth\Authenticatable;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;
use Illuminate\Database\Eloquent\Model;
class User extends ModelValidator implements AuthenticatableContract,CanResetPasswordContract
{
use Authenticatable,CanResetPassword;
protected $table = 'user';
public function application()
{
return $this->belongsToMany('App\Application')->withPivot(['rating','like','comment'])->withTimestamps();
}
}
But when i run the below code it prints empty array.
$apps = \App\Application::all();
foreach ($apps as $app) {
print_r($app->getComment());
}
Why its returning empty array ?
Thanks in advance
just change your relationship like
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use App\ModelValidator;
class Application extends ModelValidator
{
//
protected $table = "application";
public function user()
{
return $this->hasMany('App\ApplicationUser','application_id','id')
->withPivot(['rating','like','comment'])->withTimestamps();
}
}
<?php
namespace App;
use Illuminate\Auth\Authenticatable;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;
use Illuminate\Database\Eloquent\Model;
class User extends ModelValidator implements AuthenticatableContract,CanResetPasswordContract
{
use Authenticatable,CanResetPassword;
protected $table = 'user';
public function application()
{
return $this->belongsToMany('App\Application')->withPivot(['rating','like','comment'])->withTimestamps();
}
}
change your code like this.
foreach ($apps as $app) {
print_r($app->user);
}
Now you get data from application_user table, you got empty result because of you trying to find a data into user table so for that you got empty result.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments