如何从Eloquent查询中获取变量并在创建Peminjaman模型实例时正确赋值
Hey there! Let's break down what's going wrong and fix this step by step.
The Problem with Your Current Code
Your initial query $petugas = petugas::where('ID_PETUGAS','=',auth()->user()->id); only creates a query builder instance—it doesn't actually run the query or fetch any data from the database. That's why trying to access $petugas->ID_PETUGAS directly throws an error.
Solution 1: Fetch the Single Value Directly (Most Efficient)
If you only need the ID_PETUGAS value (and nothing else from the petugas record), use the value() method to get it in one go. This skips loading a full model instance:
// First, make sure your model follows Laravel conventions (capitalized class name) use App\Models\Petugas; // Directly retrieve the ID_PETUGAS value matching the authenticated user's ID $idPetugas = Petugas::where('ID_PETUGAS', auth()->user()->id)->value('ID_PETUGAS');
Solution 2: Fetch the Full Model Instance (With Error Handling)
If you might need other data from the petugas record later, use first() to get the model instance. Always add a check to handle cases where no matching record exists:
use App\Models\Petugas; $petugas = Petugas::where('ID_PETUGAS', auth()->user()->id)->first(); // Handle the case where no petugas record exists for the user if (!$petugas) { // You can abort, return an error response, or throw an exception abort(404, 'No petugas record found for the authenticated user'); } $idPetugas = $petugas->ID_PETUGAS;
Update Your Peminjaman Creation Code
Now use the $idPetugas variable in your create() call:
use App\Models\Peminjaman; Peminjaman::create([ 'ID_ANGGOTA' => $request->ID_ANGGOTA, 'ID_BUKU' => $request->ID_BUKU, 'ID_PETUGAS' => $idPetugas, // Use the fetched value here 'TANGGAL_PINJAM' => $request->TANGGAL_PINJAM, 'TANGGAL_KEMBALI' => $request->TANGGAL_KEMBALI ]);
Quick Note on Model Naming
Laravel follows PSR-4 conventions, so your model class should be capitalized (e.g., Petugas instead of petugas). If your model file is named petugas.php, either rename it to Petugas.php (recommended) or explicitly set the table name in the model:
class petugas extends Model { protected $table = 'petugas'; }
内容的提问来源于stack exchange,提问作者Dhargombeths

