Firstly, I'm sorry because I am new in Laravel. I want to do query/eloquent with $request->id_anggota
as result from "POST"
method, so that I can get email
properties from another table and insert email
value to alokasikegiatan
table. Please help!
My code:
public function getEmail($request)
{
$em = '';
//code...
$row_peg = DB::table('users')->where('nip', $request->id_anggota)->first()->email;
if (count($row_peg) > 0) {
$em = $row_peg;
} else {
$em = DB::table('registeredmitra')->where('sobatid', $request->id_anggota)->first()->email;
};
return $em;
}
I want to pass that code before querying this one
public function store_alok(Request $request)
{
try {
AlokasiKegiatan::insert([
'id_keg' => $request->id_keg,
'email' => $this->getEmail($request),
]);
} catch (\Exception $e) {
throw new Exception($e->getMessage());
};
}
As you can see i call this:
'email' => $this->getEmail($request),
But I got this error
Trying to get property 'email' of non-object
Is there another possible way to do that? Thank you for your help!
You're trying to access a record even if it doesn't exist, both times in your getEmail function. Move the ->email
inside of the first if
clause and add another for the second, to make sure the record exists before you try to access it.
public function getEmail($request)
{
$em = '';
//code...
$row_peg = DB::table('users')->where('nip', $request->id_anggota)->first();
if ($row_peg) {
$em = $row_peg->email;
} else {
$row = DB::table('registeredmitra')->where('sobatid', $request->id_anggota)->first();
if($row) {
$em = $row->email;
}
};
return $em;
}