Thứ Tư, 15 tháng 8, 2018

Cách sửa lỗi thêm kí tự "/" vào column có kiểu json khi sử dụng lệnh response()->json

Gỉa sử ta có 1 model là Place được mapping từ table places, table này có feild là place_list_image có kiể dữ liệu là json

Và có 1 PlaceController có 1 function là indexJson dùng để tạo file json có nội dung như sau

public function indexJson(){    $places = Place::all();    $header = array (       'Content-Type' => 'application/json; charset=UTF-8',       'charset' => 'utf-8'    );
      return response()->json(['places' => $places,           'status' => Response::HTTP_OK],200,$header,JSON_UNESCAPED_UNICODE);
}

Khi tạo Json thì trường place_list_image sẽ bị encode 1 lần nữa và sẽ thêm các kí tự "/" vào nộii dung trường place_list_image. Để giải quyết vấn đề này có 2 cách

1. Vào file Model Place ta thêm code sau để chuyển sang array:

protected $casts = [    'place_list_image' => 'array',];

2. Vào file Model Place ta thêm code sau để decode trường place_list_image:

public function getPlaceListImageAttribute($value){    return json_decode($value);}



Không có nhận xét nào:

Đăng nhận xét

Laravel với MongoDB

Mở đầu Hello anh em, đến hẹn lại lên hôm nay mình xin chia sẻ với mọi người về chủ đề Laravel kết hợp với MongoDB mà thông thường ta hay ...