Laravel: Retrieve the Last Executed SQL Query and Bindings with Code Examples

This article explains how to enable Laravel's query log to capture the most recent SQL statement and its bound values, demonstrates extracting specific order data, using updateOrCreate for conditional inserts or updates, building complex sub‑queries with multiple conditions, and executing raw SQL fragments via selectRaw.

php Courses
php Courses
php Courses
Laravel: Retrieve the Last Executed SQL Query and Bindings with Code Examples

This article demonstrates how to retrieve the last executed SQL query and its bound values in Laravel by enabling the query log, and shows how to output the logged queries and result arrays.

<code>public function getOrderDetail($orderId){
    \DB::connection()->enableQueryLog(); // 开启查询日志
    $ordeList = OrderItem::where('order_id',$orderId)->get()->toArray();
    $queries = \DB::getQueryLog(); // 获取查询日志
    echo "<pre>";
    print_r($queries);
    echo PHP_EOL;
    print_r($ordeList);
    echo "

"; }

It then presents a method to fetch specific columns of order items, ordering by creation time, and displays the result.

<code>public function getOrderDetail($uid,$orderId){
    $user = $this->check_user($uid);
    $columns = ['id','order_id','item_id','item_name','item_price','original_price','buy_num','real_num','cancel_num','status','create_time'];
    $ordeList = OrderItem::where('order_id',$orderId)
        ->orderBy('create_time','desc')
        ->get($columns)->toArray();
    echo "<pre>";
    print_r($ordeList);
    echo "

"; exit; }

The guide also explains using Model::updateOrCreate to insert a new record when it does not exist or update it when it does.

Model::updateOrCreate(
   ['primary_key' => 8],
   ['field' => 'value', 'another_field' => 'another value']
);

A more complex example illustrates building a sub‑query with multiple conditional clauses using Laravel’s query builder, handling optional parameters such as type, levelId, and lessonId.

public function getCourseProgress($uid,$levelId=0,$lessonId=0,$type=0,$page=0){
    $user = $this->check_user($uid);
    $page = $page>0?$page:0;
    $perPage = config('bcc.per_page');
    $columns = ['*'];
    $result = LessonProgress::where('customer_id',$uid)
        ->where(function($query) use ($type){
            if($type) $query->where('source_type',$type);
        })
        ->where(function($query) use ($levelId,$lessonId){
            if($levelId && $lessonId){
                $query->where(['level_id'=>$levelId,'lesson_id'=>$lessonId]);
            } elseif($levelId){
                $query->where('level_id', $levelId);
            }
        })->get();
    if($result->isEmpty()) return $this->responseSuccess([], 'No relevant information', 20000);
    return $this->responseCollection($result, new CourseProgressTransformer);
}

Finally, it shows how to execute raw SQL fragments with selectRaw, for instance aggregating letters with group_concat, and notes that raw SQL can be written directly inside selectRaw.

// 声母韵母分两类
$data = Pronounce::selectRaw('group_concat(`letter`) as letters')
    ->groupBy('pronounce_type')
    ->get()
    ->toArray();
selectRaw里面可以直接写sql子句
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

LaravelEloquent
php Courses
Written by

php Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.