0

I have this table in Mysql, details column is a json type. Sample table capture

This is the OrderDetails model

class OrderDetail extends Model
{   
    protected $casts = [
        'details' => 'array',
    ];
}

This is the controller

class HomeController extends Controller
{
    public function index()
    {
        $result = OrderDetail::where('details->options->size', 'L')
            ->limit(10)
            ->get();

        return view('home', compact(['result']));
     }
}

And the home view

@if($result->count())
    @foreach($result as $item)
        <li>{{ $item->details }}</li>
    @endforeach
@endif

Im getting this error

htmlspecialchars() expects parameter 1 to be string, array given (View: /***/resources/views/home.blade.php)

But if i remove the protected $casts[] from the model it shows me the JSON, how can i convert the details field in to an object having the the id and order_id fields in the same query?

Edit

Now i have get a JSON to object conversion inserting a foreach with a json_decode and removing the protected $casts[] from the model, is there a better way to this?

class HomeController extends Controller
{
    public function index()
    {
        $result = OrderDetail::where('details->options->size', 'L')
            ->limit(10)
            ->get();

        foreach($result as $key => $item){
               $result[$key]->details = json_decode($item->details);
        }

        return view('home', compact('result'));
    }
}
3
  • 1
    Laravel 5.3 - htmlspecialchars() expects parameter 1 to be string Commented Nov 7, 2017 at 10:38
  • @KrisRoofe I check this before, but is there any way to get the json field as an object to avoid this in blade {{ $item->details['options']['size'] }} ? Commented Nov 7, 2017 at 10:58
  • cast it as object. Commented Mar 22, 2018 at 15:08

1 Answer 1

2

Remove square brackets from compact function

return view('home', compact('result'));
Sign up to request clarification or add additional context in comments.

1 Comment

I try this before and the **htmlspecialchars() ** error persist.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.