Do you actually need all of the intermediate steps, or to simply get array result of [1, 3] from the source data?
Feb 1, 2021
7
Level 1
Laravel Collections: Filter with two cloumns
So let's just begin with the question.
I have a database with following structure:
id first_user_id second_user_id
1 1 2
1 2 4
1 2 1
And let's say i have a variable with id=1
$id = 1
I find the needed records with this.
Model::where('status',1)
->where('first_user_id', $id)
->orWhere('second_user_id',$id)->get();
I want to get all of the ids that is not equals to the $id in some of the columns.
For exampe:
if first_user_id is equals to $id
return second_user_id column
if second_user_id is equals to $id
return first_user_id column
I want to done that with Laravel Collections if it is possible?
The result must be array with the ids from condition above.
Example output:
Array
(
[0] => 2 // second_user_id from first record
[1] => 2 // first_user_id from the last record.
)
For more clearly here is some pseudo php code for what i exactly want
<?php
$students = [
[
"first_user_id" => 1,
"second_user_id" => 2
],
[
"first_user_id" => 2,
"second_user_id" => 3
],
[
"first_user_id" => 1,
"second_user_id" => 3
],
[
"first_user_id" => 4,
"second_user_id" => 6
],
];
$var = 2; // Authenticated user
$arr = [];
foreach($students as $student) {
if($student['first_user_id'] == $var || $student['second_user_id'] == $var) {
if($student['first_user_id'] == $var) {
$arr[] = $student['second_user_id'];
} else $arr[] = $student['first_user_id'];
}
}
print_r($arr);
Output:
Array
(
[0] => 1
[1] => 3
)
Thank you.
Level 75
$data = Model::selectRaw('if(first_user_id = ?, second_user_id, first_user_id) as data', [$id])
->where('status', 1)->where(function ($query) use ($id) {
$query->where('first_user_id', $id)
->orWhere('second_user_id', $id);
})->pluck('data');
1 like
Please or to participate in this conversation.