You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从Eloquent查询中获取变量并在创建Peminjaman模型实例时正确赋值

Fixing Your Petugas ID Retrieval for Peminjaman Creation

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 03:48:12