您好我的应用程序中的数组有点麻烦。我的数据库中有一个名为" contacts"在那张桌子里面我有一个专栏" info"数据类型' TEXT'我存储一个json编码的数组。这是我的功能:
/**
* Store a newly created resource in storage.
*
* @return Response
*/
public function store(Request $request)
{
$contact = new Contacts;
$contact->type = $request->type;
$contact->name = str_replace(' ', ' ', $request->type == 'person' ? $request->first_name . ' ' . $request->other_name . ' ' . $request->last_name : $request->description);
$contact->email = $request->email;
$contact->info = json_encode($request->info);
if ($contact->save())
{
return [
'success' => 'Data was saved successfully!'
];
}
}
现在这完全保存了但问题是当我从数据库中检索数据时它将该列作为"字符串"因此我无法从我的前端javascript访问该数组(我使用angular)。
我尝试解码整个返回的结果但是没有用,仍然有同样的问题:
/**
* Display a listing of the resource.
*
* @return Response
*/
public function index()
{
$type = Input::get('type');
$contacts = "";
if (empty($type))
{
$contacts = Contacts::get();
}
elseif ($type == 'persons')
{
$contacts = Contacts::where('type', 'person')->get();
}
elseif ($type == 'companies')
{
$contacts = Contacts::where('type', 'company')->get();
}
return [
'contacts' => json_decode($contacts)
];
}
答案 0 :(得分:2)
在您的模型上使用the $casts
property:
class Contacts extends Eloquent
{
protected $casts = ['inof' => 'json'];
}
它将为您处理所有编码/解码。
$contact->info = $request->info;