Love Fuel?    Donate

FuelPHP Forums

Ask your question about FuelPHP in the appropriate forum, or help others by answering their questions.
model to json (only specific fields)
  • Is there a way to get all objects from a specific model, and only pass specific fields to the front end?
    I have a model User, which has fields such as password, that I do not want to pass to the front end.

    I'm currently running the following operation:

        $result = Model_Tmuser::query()->where('username', 'like', "%user1%")->get();
        $json = Format::forge($result)->to_json();
        return $json;


    This way, the password is passed inside the json for every user retrieved..

    I thought of the alternative of writing a query selecting only the columns I need, and using DB::query()... However, this way, I would not be using the model, and I would have to type every single column, for every single model I want to do this to..

    Thanks
  • HarroHarro
    Accepted Answer
    Only on a per-object bases.

    You can define a static property in your model called "$_to_array_exclude" which is an array of model properties you don't want to expose (so it acts like a filter).

    Then do

    foreach ($result as $key => $value)
    {
        $result[$key] = $value->to_array();
    }
    $json = Format::forge($result)->to_json();

    You can control whether or not custom properties, relations or EAV values are included in the result using the parameters of the to_array() method.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

In this Discussion