phparraysjsonlaravel

Decoding JSON array laravel


Hello i am having slight trouble with arrays in my application. I have a table in my database called "contacts" inside that table i have a column "info" of datatype 'TEXT' where i store a json encoded array. This is my function:

/**
 * 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!'
        ];
    }
}

Now this saves perfectly however the issues is when i retrieving the data from the database it returns that column as a "string" and as such i am unable to access that array from my front-end javascript (i use angular).

I have tried decoding the entire returned result but that did not work, still had the same problem:

/**
     * 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)
        ];
    }

Solution

  • Use the $casts property on your model:

    class Contacts extends Eloquent
    {
        protected $casts = ['inof' => 'json'];
    }
    

    It'll handle all encoding/decoding for you.

    $contact->info = $request->info;