I use eager loading in Controller and can't figure out how to show in list of each patients with his visit. Thank's for help! May be i need one more foreach loop inside the first foreach?
Migrations:
class Patients extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('patients', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('diagnosis');
$table->string('sex');
$table->string('birth');
$table->text('description')->nullable();
$table->timestamps();
});
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('patients');
}
}
class CreateVizitsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('vizits', function (Blueprint $table) {
$table->increments('id');
$table->timestamps();
$table->string('diagnosis')->nullable();
$table->integer('patients_id')->unsigned();
$table->foreign('patients_id')->references('id')->on('patients')
->onDelete('cascade')
->onUpdate('cascade');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('vizits');
}
}
Models:
class Patients extends Model
{
protected $table = 'patients';
public function vizit()
{
return $this->hasMany('App\Vizit');
}
}
}
class Vizit extends Model
{
protected $table = 'vizits';
public function patients()
{
return $this->belongsTo('App\Patients');
}
}
}
Controller
class PatientsController extends Controller
{
public function index() {
$patients= Patients::all()->paginate(10);
$vizits= Vizit::with('patients')->get();
return view('test',compact('vizits','patients'));
}
}
View:
@foreach($patients() as $patient)
show vizits of each patients ???
@endforeach
via Yrtymd