Laravel whereIn doesn’t return all data

I have following array (created by explode method)

["3D Printing"," 3D Architecture"," .NET Micro Framework"]

when I try to match this titles to my database and get id of each of them, I only get id of first item.

["d21c6805-8780-4726-ba1d-12c9c3a28d0a"]

it supposed to return something like this

["d21c6805-8780-4726-ba1d-12c9c3a28d0a", "1234...", "567...]

code

$a = $request->input('tags');
$b = str_replace(['[',']'], null, $a);
$comingTags = explode(',',$b);

$iddss = Tag::whereIn('title', $comingTags)->pluck('id');
return response()->json($iddss);

Any suggestion?

PS: My best guess is that 2nd and 3rd item in my array have spaces and that might be causing the problem "{SPACE IS HERE}3D Architecture" not sure if that’s the reason.

Update

I’ve tried $b = str_replace([',', ' '], ['',''], $a); but all I get now is []

Update 2

By using $b = str_replace(['[', ']', ' '], null, $a); it does remove spaces from my strings but also removes spaces between my titles words so 3D Architecture becomes 3DArchitecture and by that I’m also not able to match the title with my database in $iddss = Tag::whereIn('title', $comingTags)->pluck('id'); because my database title is 3D Architecture and what I’m trying to match with it is 3DArchitecture.

Any suggestion on that?

Update 3

$a = $request->input('tags');
// return 
"[3D Printing, 3D Architecture, .NET Micro Framework]"

.

$b = str_replace(['[',']'], null, $a);
// return
"3D Printing, 3D Architecture, .NET Micro Framework"

.

$comingTags = explode(',',$b);
// return
["3D Printing"," 3D Architecture"," .NET Micro Framework"]

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

To get rid of whitespace you can do
array_map('trim', $a); (credits)

whereIn expects an array, so this should work

$a = $request->input('tags');
$b = str_replace(['[',']'], null, $a);
$comingTags = array_map('trim', explode(',', $b));

$iddss = Tag::whereIn('title', $comingTags)->pluck('id');

return response()->json($iddss);


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x