Laravel change every model in collection












0















I have a collection of Items. Now, before I am sending it though my api, I want to change a value of the model (but I don't want to update my model in the database).



Now I want to loop though my collection and return it as json, but I am getting invalid Payload.



Here is the code I perform:



$trainees = Trainee::select();
if(!$request->user()->hasPermission('read-trainees')) {
$trainees->where('status', 1)->where('visible', 1);
} else {
$trainees->with(array('user'=>function($query){
$query->select('id','firstname', 'lastname');
}));
$trainees->select('user_id');
}
$trainees->select('interested_jobs', 'graduation');
$trainees = $trainees->get();
return $trainees
->map(function ($item) {
$item->id = encrypt($item->id);
return $item;
})
->toJson();









share|improve this question

























  • And the problem is only in the json conversion? The value is changed and the $trainees is the array you want?

    – pr1nc3
    Nov 14 '18 at 16:08













  • Decrypting item id? It comes encrypted from the database?

    – Phiter
    Nov 14 '18 at 16:10











  • I dont know if the collection is getting updated. Without the code everything works fine, but with this code it doenst work

    – Patrick Schocke
    Nov 14 '18 at 16:10











  • That with decrypt was stupid from me. But now I get call do undefined function toJson()

    – Patrick Schocke
    Nov 14 '18 at 16:13











  • @KuebelElch15 when you do Trainee::each(...) doens't save the collection, just iterates over every item. Check this

    – HCK
    Nov 14 '18 at 16:31
















0















I have a collection of Items. Now, before I am sending it though my api, I want to change a value of the model (but I don't want to update my model in the database).



Now I want to loop though my collection and return it as json, but I am getting invalid Payload.



Here is the code I perform:



$trainees = Trainee::select();
if(!$request->user()->hasPermission('read-trainees')) {
$trainees->where('status', 1)->where('visible', 1);
} else {
$trainees->with(array('user'=>function($query){
$query->select('id','firstname', 'lastname');
}));
$trainees->select('user_id');
}
$trainees->select('interested_jobs', 'graduation');
$trainees = $trainees->get();
return $trainees
->map(function ($item) {
$item->id = encrypt($item->id);
return $item;
})
->toJson();









share|improve this question

























  • And the problem is only in the json conversion? The value is changed and the $trainees is the array you want?

    – pr1nc3
    Nov 14 '18 at 16:08













  • Decrypting item id? It comes encrypted from the database?

    – Phiter
    Nov 14 '18 at 16:10











  • I dont know if the collection is getting updated. Without the code everything works fine, but with this code it doenst work

    – Patrick Schocke
    Nov 14 '18 at 16:10











  • That with decrypt was stupid from me. But now I get call do undefined function toJson()

    – Patrick Schocke
    Nov 14 '18 at 16:13











  • @KuebelElch15 when you do Trainee::each(...) doens't save the collection, just iterates over every item. Check this

    – HCK
    Nov 14 '18 at 16:31














0












0








0








I have a collection of Items. Now, before I am sending it though my api, I want to change a value of the model (but I don't want to update my model in the database).



Now I want to loop though my collection and return it as json, but I am getting invalid Payload.



Here is the code I perform:



$trainees = Trainee::select();
if(!$request->user()->hasPermission('read-trainees')) {
$trainees->where('status', 1)->where('visible', 1);
} else {
$trainees->with(array('user'=>function($query){
$query->select('id','firstname', 'lastname');
}));
$trainees->select('user_id');
}
$trainees->select('interested_jobs', 'graduation');
$trainees = $trainees->get();
return $trainees
->map(function ($item) {
$item->id = encrypt($item->id);
return $item;
})
->toJson();









share|improve this question
















I have a collection of Items. Now, before I am sending it though my api, I want to change a value of the model (but I don't want to update my model in the database).



Now I want to loop though my collection and return it as json, but I am getting invalid Payload.



Here is the code I perform:



$trainees = Trainee::select();
if(!$request->user()->hasPermission('read-trainees')) {
$trainees->where('status', 1)->where('visible', 1);
} else {
$trainees->with(array('user'=>function($query){
$query->select('id','firstname', 'lastname');
}));
$trainees->select('user_id');
}
$trainees->select('interested_jobs', 'graduation');
$trainees = $trainees->get();
return $trainees
->map(function ($item) {
$item->id = encrypt($item->id);
return $item;
})
->toJson();






php laravel eloquent






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 14 '18 at 16:32







Patrick Schocke

















asked Nov 14 '18 at 16:06









Patrick SchockePatrick Schocke

969216




969216













  • And the problem is only in the json conversion? The value is changed and the $trainees is the array you want?

    – pr1nc3
    Nov 14 '18 at 16:08













  • Decrypting item id? It comes encrypted from the database?

    – Phiter
    Nov 14 '18 at 16:10











  • I dont know if the collection is getting updated. Without the code everything works fine, but with this code it doenst work

    – Patrick Schocke
    Nov 14 '18 at 16:10











  • That with decrypt was stupid from me. But now I get call do undefined function toJson()

    – Patrick Schocke
    Nov 14 '18 at 16:13











  • @KuebelElch15 when you do Trainee::each(...) doens't save the collection, just iterates over every item. Check this

    – HCK
    Nov 14 '18 at 16:31



















  • And the problem is only in the json conversion? The value is changed and the $trainees is the array you want?

    – pr1nc3
    Nov 14 '18 at 16:08













  • Decrypting item id? It comes encrypted from the database?

    – Phiter
    Nov 14 '18 at 16:10











  • I dont know if the collection is getting updated. Without the code everything works fine, but with this code it doenst work

    – Patrick Schocke
    Nov 14 '18 at 16:10











  • That with decrypt was stupid from me. But now I get call do undefined function toJson()

    – Patrick Schocke
    Nov 14 '18 at 16:13











  • @KuebelElch15 when you do Trainee::each(...) doens't save the collection, just iterates over every item. Check this

    – HCK
    Nov 14 '18 at 16:31

















And the problem is only in the json conversion? The value is changed and the $trainees is the array you want?

– pr1nc3
Nov 14 '18 at 16:08







And the problem is only in the json conversion? The value is changed and the $trainees is the array you want?

– pr1nc3
Nov 14 '18 at 16:08















Decrypting item id? It comes encrypted from the database?

– Phiter
Nov 14 '18 at 16:10





Decrypting item id? It comes encrypted from the database?

– Phiter
Nov 14 '18 at 16:10













I dont know if the collection is getting updated. Without the code everything works fine, but with this code it doenst work

– Patrick Schocke
Nov 14 '18 at 16:10





I dont know if the collection is getting updated. Without the code everything works fine, but with this code it doenst work

– Patrick Schocke
Nov 14 '18 at 16:10













That with decrypt was stupid from me. But now I get call do undefined function toJson()

– Patrick Schocke
Nov 14 '18 at 16:13





That with decrypt was stupid from me. But now I get call do undefined function toJson()

– Patrick Schocke
Nov 14 '18 at 16:13













@KuebelElch15 when you do Trainee::each(...) doens't save the collection, just iterates over every item. Check this

– HCK
Nov 14 '18 at 16:31





@KuebelElch15 when you do Trainee::each(...) doens't save the collection, just iterates over every item. Check this

– HCK
Nov 14 '18 at 16:31












2 Answers
2






active

oldest

votes


















1














You can use the map function to change the data for each item in a collection.



return $trainees
->map(function ($item) {
$item->id = decrypt($item->id);
return $item;
})
->toJson();





share|improve this answer
























  • This produces a Call to undefined method IlluminateDatabaseEloquentBuilder::map()

    – Patrick Schocke
    Nov 14 '18 at 16:13











  • It seems the query is not yet executed. Add ->get() before the ->map function.

    – Jerodev
    Nov 14 '18 at 16:15











  • I've updated my question. I am performing ->get()

    – Patrick Schocke
    Nov 14 '18 at 16:17











  • You need to assign the output of your get() function. $trainees = $trainees->get();

    – Jerodev
    Nov 14 '18 at 16:19











  • Oh yes, thats the Problem. Wow, I am so stupid...

    – Patrick Schocke
    Nov 14 '18 at 16:21



















1
















You can achieve this in several ways.



Every Eloquent collection extends the Collection class, that let you use helpful method like Map():



// get your collection
$trainees = Trainee::all();

// customize them
$trainees->each(function ($trainee) {
$trainee->id = encrypt($item->id);
});

return $trainees;


PS: By default, when returning an array/collection to an API Laravel will return it as JSON.





The second approach, more granular and recommended in my opinion, is to use API Resources. From the documentation:




When building an API, you may need a transformation layer that sits
between your Eloquent models and the JSON responses that are actually
returned to your application's users. Laravel's resource classes allow
you to expressively and easily transform your models and model
collections into JSON.




So, you'll need to:



1. Generate your API Resource



php artisan make:resource TraineeResource


2. Customize it



AppHttpResourcesTraineeResource.php



<?php

namespace AppHttpResources;

use IlluminateHttpResourcesJsonJsonResource;

class TraineeResource extends JsonResource
{
/**
* Transform the resource into an array.
*
* @param IlluminateHttpRequest $request
* @return array
*/
public function toArray($request)
{
return [
'id' => encrypt($this->id),
// ...
];
}
}


3. Apply it



In your controller:



App/Http/Controllers/MyCoolController.php



use AppHttpResourcesTraineeResource

public function aCoolMethod(Request $request)
{
// get your collection
$trainees = Trainee::all();

// return it
return TraineeResource::collection($trainees);
}





share|improve this answer

























    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53304346%2flaravel-change-every-model-in-collection%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    1














    You can use the map function to change the data for each item in a collection.



    return $trainees
    ->map(function ($item) {
    $item->id = decrypt($item->id);
    return $item;
    })
    ->toJson();





    share|improve this answer
























    • This produces a Call to undefined method IlluminateDatabaseEloquentBuilder::map()

      – Patrick Schocke
      Nov 14 '18 at 16:13











    • It seems the query is not yet executed. Add ->get() before the ->map function.

      – Jerodev
      Nov 14 '18 at 16:15











    • I've updated my question. I am performing ->get()

      – Patrick Schocke
      Nov 14 '18 at 16:17











    • You need to assign the output of your get() function. $trainees = $trainees->get();

      – Jerodev
      Nov 14 '18 at 16:19











    • Oh yes, thats the Problem. Wow, I am so stupid...

      – Patrick Schocke
      Nov 14 '18 at 16:21
















    1














    You can use the map function to change the data for each item in a collection.



    return $trainees
    ->map(function ($item) {
    $item->id = decrypt($item->id);
    return $item;
    })
    ->toJson();





    share|improve this answer
























    • This produces a Call to undefined method IlluminateDatabaseEloquentBuilder::map()

      – Patrick Schocke
      Nov 14 '18 at 16:13











    • It seems the query is not yet executed. Add ->get() before the ->map function.

      – Jerodev
      Nov 14 '18 at 16:15











    • I've updated my question. I am performing ->get()

      – Patrick Schocke
      Nov 14 '18 at 16:17











    • You need to assign the output of your get() function. $trainees = $trainees->get();

      – Jerodev
      Nov 14 '18 at 16:19











    • Oh yes, thats the Problem. Wow, I am so stupid...

      – Patrick Schocke
      Nov 14 '18 at 16:21














    1












    1








    1







    You can use the map function to change the data for each item in a collection.



    return $trainees
    ->map(function ($item) {
    $item->id = decrypt($item->id);
    return $item;
    })
    ->toJson();





    share|improve this answer













    You can use the map function to change the data for each item in a collection.



    return $trainees
    ->map(function ($item) {
    $item->id = decrypt($item->id);
    return $item;
    })
    ->toJson();






    share|improve this answer












    share|improve this answer



    share|improve this answer










    answered Nov 14 '18 at 16:10









    JerodevJerodev

    19k84572




    19k84572













    • This produces a Call to undefined method IlluminateDatabaseEloquentBuilder::map()

      – Patrick Schocke
      Nov 14 '18 at 16:13











    • It seems the query is not yet executed. Add ->get() before the ->map function.

      – Jerodev
      Nov 14 '18 at 16:15











    • I've updated my question. I am performing ->get()

      – Patrick Schocke
      Nov 14 '18 at 16:17











    • You need to assign the output of your get() function. $trainees = $trainees->get();

      – Jerodev
      Nov 14 '18 at 16:19











    • Oh yes, thats the Problem. Wow, I am so stupid...

      – Patrick Schocke
      Nov 14 '18 at 16:21



















    • This produces a Call to undefined method IlluminateDatabaseEloquentBuilder::map()

      – Patrick Schocke
      Nov 14 '18 at 16:13











    • It seems the query is not yet executed. Add ->get() before the ->map function.

      – Jerodev
      Nov 14 '18 at 16:15











    • I've updated my question. I am performing ->get()

      – Patrick Schocke
      Nov 14 '18 at 16:17











    • You need to assign the output of your get() function. $trainees = $trainees->get();

      – Jerodev
      Nov 14 '18 at 16:19











    • Oh yes, thats the Problem. Wow, I am so stupid...

      – Patrick Schocke
      Nov 14 '18 at 16:21

















    This produces a Call to undefined method IlluminateDatabaseEloquentBuilder::map()

    – Patrick Schocke
    Nov 14 '18 at 16:13





    This produces a Call to undefined method IlluminateDatabaseEloquentBuilder::map()

    – Patrick Schocke
    Nov 14 '18 at 16:13













    It seems the query is not yet executed. Add ->get() before the ->map function.

    – Jerodev
    Nov 14 '18 at 16:15





    It seems the query is not yet executed. Add ->get() before the ->map function.

    – Jerodev
    Nov 14 '18 at 16:15













    I've updated my question. I am performing ->get()

    – Patrick Schocke
    Nov 14 '18 at 16:17





    I've updated my question. I am performing ->get()

    – Patrick Schocke
    Nov 14 '18 at 16:17













    You need to assign the output of your get() function. $trainees = $trainees->get();

    – Jerodev
    Nov 14 '18 at 16:19





    You need to assign the output of your get() function. $trainees = $trainees->get();

    – Jerodev
    Nov 14 '18 at 16:19













    Oh yes, thats the Problem. Wow, I am so stupid...

    – Patrick Schocke
    Nov 14 '18 at 16:21





    Oh yes, thats the Problem. Wow, I am so stupid...

    – Patrick Schocke
    Nov 14 '18 at 16:21













    1
















    You can achieve this in several ways.



    Every Eloquent collection extends the Collection class, that let you use helpful method like Map():



    // get your collection
    $trainees = Trainee::all();

    // customize them
    $trainees->each(function ($trainee) {
    $trainee->id = encrypt($item->id);
    });

    return $trainees;


    PS: By default, when returning an array/collection to an API Laravel will return it as JSON.





    The second approach, more granular and recommended in my opinion, is to use API Resources. From the documentation:




    When building an API, you may need a transformation layer that sits
    between your Eloquent models and the JSON responses that are actually
    returned to your application's users. Laravel's resource classes allow
    you to expressively and easily transform your models and model
    collections into JSON.




    So, you'll need to:



    1. Generate your API Resource



    php artisan make:resource TraineeResource


    2. Customize it



    AppHttpResourcesTraineeResource.php



    <?php

    namespace AppHttpResources;

    use IlluminateHttpResourcesJsonJsonResource;

    class TraineeResource extends JsonResource
    {
    /**
    * Transform the resource into an array.
    *
    * @param IlluminateHttpRequest $request
    * @return array
    */
    public function toArray($request)
    {
    return [
    'id' => encrypt($this->id),
    // ...
    ];
    }
    }


    3. Apply it



    In your controller:



    App/Http/Controllers/MyCoolController.php



    use AppHttpResourcesTraineeResource

    public function aCoolMethod(Request $request)
    {
    // get your collection
    $trainees = Trainee::all();

    // return it
    return TraineeResource::collection($trainees);
    }





    share|improve this answer






























      1
















      You can achieve this in several ways.



      Every Eloquent collection extends the Collection class, that let you use helpful method like Map():



      // get your collection
      $trainees = Trainee::all();

      // customize them
      $trainees->each(function ($trainee) {
      $trainee->id = encrypt($item->id);
      });

      return $trainees;


      PS: By default, when returning an array/collection to an API Laravel will return it as JSON.





      The second approach, more granular and recommended in my opinion, is to use API Resources. From the documentation:




      When building an API, you may need a transformation layer that sits
      between your Eloquent models and the JSON responses that are actually
      returned to your application's users. Laravel's resource classes allow
      you to expressively and easily transform your models and model
      collections into JSON.




      So, you'll need to:



      1. Generate your API Resource



      php artisan make:resource TraineeResource


      2. Customize it



      AppHttpResourcesTraineeResource.php



      <?php

      namespace AppHttpResources;

      use IlluminateHttpResourcesJsonJsonResource;

      class TraineeResource extends JsonResource
      {
      /**
      * Transform the resource into an array.
      *
      * @param IlluminateHttpRequest $request
      * @return array
      */
      public function toArray($request)
      {
      return [
      'id' => encrypt($this->id),
      // ...
      ];
      }
      }


      3. Apply it



      In your controller:



      App/Http/Controllers/MyCoolController.php



      use AppHttpResourcesTraineeResource

      public function aCoolMethod(Request $request)
      {
      // get your collection
      $trainees = Trainee::all();

      // return it
      return TraineeResource::collection($trainees);
      }





      share|improve this answer




























        1












        1








        1









        You can achieve this in several ways.



        Every Eloquent collection extends the Collection class, that let you use helpful method like Map():



        // get your collection
        $trainees = Trainee::all();

        // customize them
        $trainees->each(function ($trainee) {
        $trainee->id = encrypt($item->id);
        });

        return $trainees;


        PS: By default, when returning an array/collection to an API Laravel will return it as JSON.





        The second approach, more granular and recommended in my opinion, is to use API Resources. From the documentation:




        When building an API, you may need a transformation layer that sits
        between your Eloquent models and the JSON responses that are actually
        returned to your application's users. Laravel's resource classes allow
        you to expressively and easily transform your models and model
        collections into JSON.




        So, you'll need to:



        1. Generate your API Resource



        php artisan make:resource TraineeResource


        2. Customize it



        AppHttpResourcesTraineeResource.php



        <?php

        namespace AppHttpResources;

        use IlluminateHttpResourcesJsonJsonResource;

        class TraineeResource extends JsonResource
        {
        /**
        * Transform the resource into an array.
        *
        * @param IlluminateHttpRequest $request
        * @return array
        */
        public function toArray($request)
        {
        return [
        'id' => encrypt($this->id),
        // ...
        ];
        }
        }


        3. Apply it



        In your controller:



        App/Http/Controllers/MyCoolController.php



        use AppHttpResourcesTraineeResource

        public function aCoolMethod(Request $request)
        {
        // get your collection
        $trainees = Trainee::all();

        // return it
        return TraineeResource::collection($trainees);
        }





        share|improve this answer

















        You can achieve this in several ways.



        Every Eloquent collection extends the Collection class, that let you use helpful method like Map():



        // get your collection
        $trainees = Trainee::all();

        // customize them
        $trainees->each(function ($trainee) {
        $trainee->id = encrypt($item->id);
        });

        return $trainees;


        PS: By default, when returning an array/collection to an API Laravel will return it as JSON.





        The second approach, more granular and recommended in my opinion, is to use API Resources. From the documentation:




        When building an API, you may need a transformation layer that sits
        between your Eloquent models and the JSON responses that are actually
        returned to your application's users. Laravel's resource classes allow
        you to expressively and easily transform your models and model
        collections into JSON.




        So, you'll need to:



        1. Generate your API Resource



        php artisan make:resource TraineeResource


        2. Customize it



        AppHttpResourcesTraineeResource.php



        <?php

        namespace AppHttpResources;

        use IlluminateHttpResourcesJsonJsonResource;

        class TraineeResource extends JsonResource
        {
        /**
        * Transform the resource into an array.
        *
        * @param IlluminateHttpRequest $request
        * @return array
        */
        public function toArray($request)
        {
        return [
        'id' => encrypt($this->id),
        // ...
        ];
        }
        }


        3. Apply it



        In your controller:



        App/Http/Controllers/MyCoolController.php



        use AppHttpResourcesTraineeResource

        public function aCoolMethod(Request $request)
        {
        // get your collection
        $trainees = Trainee::all();

        // return it
        return TraineeResource::collection($trainees);
        }






        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Nov 14 '18 at 16:28

























        answered Nov 14 '18 at 16:15









        HCKHCK

        3,56911035




        3,56911035






























            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53304346%2flaravel-change-every-model-in-collection%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Xamarin.iOS Cant Deploy on Iphone

            Glorious Revolution

            Dulmage-Mendelsohn matrix decomposition in Python