0

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"]
mafortis
  • 6,750
  • 23
  • 130
  • 288

1 Answers1

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);
Sidney Gijzen
  • 1,931
  • 3
  • 24
  • 27
  • it says `array_map(): Expected parameter 2 to be an array, string given` – mafortis Apr 20 '21 at 09:15
  • still giving same error, somehow it doesn't recognize `$b` as of array. – mafortis Apr 20 '21 at 09:28
  • can you update your question with the exact values of $a and $b? – Sidney Gijzen Apr 20 '21 at 09:30
  • this does the job :D `$a = $request->input('tags'); $b = str_replace(['[',']'], null, $a); $comingTags = explode(',',$b); $comingTags2 = array_map('trim', $comingTags); $iddss = Tag::whereIn('title', $comingTags2)->pluck('id'); return response()->json($iddss);` – mafortis Apr 20 '21 at 09:34
  • I am gonna accept your answer because the `trim` did the trick but please update your answer with my provided solution which is working code. Thanks a lot. – mafortis Apr 20 '21 at 09:41