John Davidson

php - Laravel 8 eloquent query - Put external variable to 'Select after join'

0 comments
Message:


Below is the code where I am getting relevant records by joining 3 table and then the 'Select' statement at the end is fetching specific fields. It's working perfectly. Now I want to add the variable '$userName' in to 'Select' statement to pass it with each record to view.
also I want the key of $userName as userName and the value is dynamic.


here is the code.


    $fromDate = request('fromDate');
$toDate = request('toDate');
$user = auth()->user();
$userName = $user->name;

$records = $user->cases()
->join('myrequests', 'mycases.id', 'myrequests.mycase_id')
->whereDate('myrequests.created_at', '>=', $fromDate)
->whereDate('myrequests.created_at', '<=', $toDate)
->select(
'mycases.*',
'myrequests.number',
'myrequests.created_at',
'myrequests.requested',
**here I want the '$userName'**
)->get();

I've tried 'username' => $userName and {{$userName}}


but it's not working.



My Answer:
To add the variable `$userName` to the `Select` statement and pass it with each record to the view, you can use the `selectRaw` method in Laravel Eloquent. Here's how you can modify your code to achieve this:

php
$fromDate = request('fromDate');
$toDate = request('toDate');
$user = auth()->user();
$userName = $user->name;

$records = $user->cases()
->join('myrequests', 'mycases.id', 'myrequests.mycase_id')
->whereDate('myrequests.created_at', '>=', $fromDate)
->whereDate('myrequests.created_at', '<=', $toDate)
->select(
'mycases.*',
'myrequests.number',
'myrequests.created_at',
'myrequests.requested'
)
->selectRaw('? as userName', [$userName])
->get();


In the `selectRaw` method, you can pass the placeholder `?` for the dynamic value of `$userName` and then pass the actual value as an array in the second parameter of the method.

This will add the `userName` field to each record in the result set with the value of the `$userName` variable. You can access this field in your view as `$record->userName`.

Rate this post

3 of 5 based on 2561 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us