1

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)
        ];
    }
2
  • don't you want to encode the string to JSON? Commented Sep 4, 2015 at 16:24
  • I'm confused, the array was already encoded to JSON when it was saved in the DB now i want to decode it and return to the client. Commented Sep 4, 2015 at 16:26

1 Answer 1

3

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;
Sign up to request clarification or add additional context in comments.

3 Comments

Wow!! Didn't know i could do that lol, learned something new today, thanks :)
@Joseph Silber.how many type of properties available like you mentioned .i know proected $table,$hidden
@tester - Just look at the source. Most of them don't make much sense in your own models, but it'll give you a quick overview.

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.