0

I have database records that are saved in json. In edit form I want those check boxes checked if, the values are saved in database.

Database Value

| ID |           items            |
|----|----------------------------|
|  1 | ["cars","bikes","planes"] |
|  2 | ["fruits", "vegetables"]   |

Form

<input type="checkbox" name="items[]" value="cars">
<input type="checkbox" name="items[]" value="planes">

Controller

 $items= Items::pluck('items');
 return view('edit', compact('items'));

I tried

 <input type="checkbox" name="items[]" value="cars" {{ json_decode($items),"cars" ? 'checked' : '' }}>

and

<input type="checkbox" name="items[]" value="cars" {{ $items == "cars" ? 'checked' : '' }}>

But none of them worked.

4
  • Add the items json to your question please. Commented Apr 23, 2018 at 11:49
  • Oh sorry I saw it above Commented Apr 23, 2018 at 11:55
  • and by the way its array, not json, json is in key value pair Commented Apr 23, 2018 at 11:56
  • Find if value exists in a JSONArray in php Commented May 2, 2024 at 1:18

3 Answers 3

1

Try it like this:

$items= json_decode(Items::pluck('items'));

And then you can use in_array() method to find the exact match item you want to check.

<input type="checkbox" name="items[]" value="cars" {{ in_array('cars',$items) ? 'checked' : '' }}>
Sign up to request clarification or add additional context in comments.

7 Comments

It throws unserialize(): Error at offset 0 of 43 bytes
can you show me what does this return $items= Items::pluck('items');
0 "[\"cars\",\"bikes\"]"
use the json_decode to parse the string, And then in_array method will check for the specific value in the array
in_array() expects parameter 2 to be array, string given
|
0

I think you need to fetch all items first

$items= Items::select('items')->get();

then merged all columns contains items

$new_items = [] 

$items.map(function($item){
array_merge($new_items,item)  
}

should be resulted here on 1 array

$new_items  = ["cars","bikes","planes","fruits", "vegetables"]

then you can use Haider Ali answer on frontend

return view('edit', compact('new_items'));

1 Comment

PHP's array_merge() doesn't modify data by reference. Your map() call is not returning anything in the callback.
0

You need something like this :

<?php $items = json_decode($items); ?>


<input type="checkbox" name="items[]" value="cars" {{ array_has($items, "cars") ? 'checked' : '' }}>

3 Comments

Not worked. Only this works. I know it's not efficient. <input type="checkbox" name="items[]" @foreach($items as $item) @foreach(json_decode($item) as $itm) {{ $itm == "cars" ? "checked" : "" }} @endforeach @endforeach> Cars for each item.
what is in $item variable ?
$item is used for foreach parameter. $items is collection of array in database

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.