Reputation: 109
the question is how to get data from foreign key into my controller and pass to Session flash message view.
AbsenController@store
$this->validate($request, [
'siswa_id' => 'required',
'keterangan' => 'required',
]);
$alpaCount = Absen::where('siswa_id', '=', $request->siswa_id)
->where('keterangan', '=', 'Alpa')
->count();
if (Absen::where('siswa_id', '=', $request->siswa_id)
->whereRaw('DATE(created_at) = CURDATE()')
->exists()) {
return redirect()->back()->with('message', 'Data Telah Tersedia');
} elseif($alpaCount >= 3) {
$absen = new Absen;
$absen->siswa_id = $request->siswa_id;
$absen->keterangan = $request->keterangan;
$absen->save();
$nama = Siswa::where('id', '=', $request->siswa_id)->get();
Session::flash('warning', $nama->nama.' Sudah Lebih Dari 3 Kali
Alpa');
return redirect()->route('absen.index')
Look on $nama = Siswa::where('id', '=', $request->siswa_id)->get(); im trying to get data with $request->id and get the nama field and then pass to Session::flash('warning', $nama->nama.' Sudah Lebih Dari 3 Kali Alpa'); return redirect()->route('absen.index');
Absen@siswa
public function siswa()
{
return $this->belongsTo('App\Siswa');
}
Siswa@absen
public function absen()
{
return $this->hasMany('App\Absen');
}
maybe you can help me, Thanks
Siswa Table
Upvotes: 0
Views: 1895
Reputation: 2172
You can load Absen
with siswa
, in where clause while filtering siswa_id
, it binds to $request->siswa_id
$nama = Absen::with(['siswa' => function ($query) use($request) {
$query->where('siswa_id', $request->siswa_id;);
}])->get();
Also, you can lazy-eager load:
$name = Absen::find($request->id);
and then call load
function to load related model.
$name->load('siswa');
Since siswa is an array. You can loop through that and find the desired object name. Or you can simply just take the first element by using first()
function. e.g.
$nama->siswa->first()->anyproperty;
Upvotes: 0
Reputation: 9117
find($request->id)
i assume that $request->siswa_id
because i can't find $request->id anywhere in your code
try this using Constraining Eager Loads
$nama = Absen::with(['siswa' => function ($query) use ($request) {
$query->where('id', $request->siswa_id);
}])->get();
Session::flash('warning', $nama->siswa->nama.' Sudah Lebih Dari 3
Kali Alpa');
EDIT ANSWERS
Based on table you shown in your question, it can be done like this
$namas = Absen::where('siswa',$request->siswa_id)->get(); //will return array because of absent as many siswa
foreach($namas as $nama) {
$siswa_name = $nama->siswa->nama;
}
Upvotes: 0