@foreach($users as $user)
$users[] = $user->name;
@endforeach
I want to get the output like this.
['X', 'Y', 'Z', 'C'];
Note: i need this because i have to use this in JavaScript function.
First of all, you can't "turn a foreach loop into an array", you would use that foreach loop to get an array as outcome. In this case I wouldn't go with a foreach approach, there are some methods that can help you cleaning out your code a bit.
You have two options depending on the type of the $users variable, pluck() or array_column():
// $users is a collection
json_encode($users->pluck('name'));
// $users is an array
json_encode(array_column($users, 'name'));
The json_encode() is highly recommended (as the comments pointed out) if you are going to use that output in your javascript. Now you can just send it in a respond and use it as a normal JSON.
In case you print the resulting variable using Blade, remember you need to use {!! !!}, otherwise, if you use {{ }} you would get unwanted scaped characters, since it uses htmlspecialchars() function under the hood.
Hope this helps you.
{!! !!} instead of {{ }} to print the variable.I recommend You should perform this action in your controller only, and then pass it to your view as
$userNames=implode(",",array_column($users,'name'));
return view('your_view',['userNames'=>$userNames]);
Then split it in your js as
var names="{!! $userNames!!}";
var names= names.split(",");
<?php echo when he states that he is using blade and laravel?Collections will automatically be converted to json when you try to echo them.
The reason you're seeing " is because using {{ }} will automatically escape strings for your protection. You can prevent this by using {!! !!} instead.
Try something like this:
<script>
var data = '{!! $users->pluck('name') !!}';
console.log( JSON.parse(data));
</script>
Hope this helps!
json_encode.$usersis an Eloquent Collection?