TechnoBeceT
TechnoBeceT

Reputation: 42

Laravel implode array with quotes in controller

I want to implode array with quotes in controller here is my code but that's not doing what I want, starting points and ending points still empty. I tried a lot of code but couldn't get out of it. Thanks for the help.

$product = Product::find($id);
$product = collect($product->images->pluck('image_path'))->implode("','");
return $product;

What I really want to do is send this array into the javascript code in the laravel blade.

initialPreview: ['{{ $product}}'],

But this time, the output is as follows and I can't get the result I want again.

initialPreview: ['img/uploads/urun/1552304918.jpeg','img/uploads/urun/1552304918.jpeg'],

Upvotes: 0

Views: 2070

Answers (3)

Horacio Degiorgi
Horacio Degiorgi

Reputation: 1

my function to automatize the protected $fillable

 $x = collect(Schema::getColumnListing('templatefields'))
   ->transform(function ($item, $key) {
             return "'" . $item ."'";
           })
           ->implode(",");

echo "[".  $x.']'; 

Upvotes: 0

Travis Britz
Travis Britz

Reputation: 5552

Building the javascript string yourself for this purpose has more hidden complexity than you might realize. Not only do you have to implode the array and add quotes and commas to make a valid javascript string, but you also need to securely escape special characters in the strings before they're imploded.

Since your actual goal is to seed an array for javascript, in Laravel it's better to build your php array and then defer to @json for the proper encoding.

To build the array of paths:

$product = Product::find($id);
$product_paths = $product->images->pluck('image_path'); // value: ["img/...","img/..."]

Usage in a Blade view (in a script block):

<script>
    //...

    initialPreview: @json($product_paths),

</script>

Usage in a Blade view (inside an HTML attribute):

<!-- Seeding a data-* attribute, e.g. for jQuery -->
<ul data-initial-preview='@json($product_paths)'></ul>

<!-- Seeding a Vue component property -->
<example-component :initial-preview='@json($product_paths)'></example-component>

Note: The usage of single quotes ' in this context, not double quotes ", is important due to the way quotes are escaped by json_encode() behind the scenes.

Upvotes: 4

Kasper Sanguesa-Franz
Kasper Sanguesa-Franz

Reputation: 617

My Laravel is a little rusty, but this should be what you want to do:

$product = Product::find($id);
$product = collect($product->images->pluck('image_path'))
           ->transform(function ($item, $key) {
              return "'" . $item ."'";
           })
           ->implode(",");
return $product;

Changes:

  • Added transform function call.
  • Removed the quote from the implode call

This solution can be prettier, but this is a very quick way to do it.

Upvotes: 2

Related Questions