I have this table in Mysql, details column is a json type.
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'));
}
}
从compact
功能中删除方括号
return view('home', compact('result'));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.