switchon@lavalamp.biz
+27(0) 83 419 4851 / +27(0) 21 036 1165
Application & software development
Get A Quote

    • Home
    • Services
      • Application & software development
      • Outsourced software development
      • Project based resourcing
      • Digital marketing & consulting
      • Graphic design & consulting
      • UI / UX design & consulting
      • Recruitment services
      • Lease an expert
    • About
      • How we work
      • NBConsult Group
      • Partners
      • Lightbox Digital
    • Blog
    • Join us
    • Contact

    • Home
    • Services
      • Application & software development
      • Outsourced software development
      • Project based resourcing
      • Digital marketing & consulting
      • Graphic design & consulting
      • UI / UX design & consulting
      • Recruitment services
      • Lease an expert
    • About
      • How we work
      • NBConsult Group
      • Partners
      • Lightbox Digital
    • Blog
    • Join us
    • Contact

    • Home
    • Services
      • Application & software development
      • Outsourced software development
      • Project based resourcing
      • Digital marketing & consulting
      • Graphic design & consulting
      • UI / UX design & consulting
      • Recruitment services
      • Lease an expert
    • About
      • How we work
      • NBConsult Group
      • Partners
      • Lightbox Digital
    • Blog
    • Join us
    • Contact

    • Home
    • Services
      • Application & software development
      • Outsourced software development
      • Project based resourcing
      • Digital marketing & consulting
      • Graphic design & consulting
      • UI / UX design & consulting
      • Recruitment services
      • Lease an expert
    • About
      • How we work
      • NBConsult Group
      • Partners
      • Lightbox Digital
    • Blog
    • Join us
    • Contact
    getting django to talk to mysql 8
    Getting Django To Talk To MySQL 8
    Nov 19, 2019
    ionic custom form builder
    Ionic Custom Form Builder
    Jan 6, 2020

    Working With Eloquent: API Resources In Laravel – Part 2

    Categories
    • Software Development
    Tags
    • api
    • api resourses
    • data objects
    • eloquent
    • json
    • laravel
    • laravel eloquent
    • software development
    laravel eloquent
    laravel eloquent

    Following on from my previous blog Post (found here) we are going to be discussing two interesting parts of API Resources.


    Using Resources to build up a data object


    This is one of my favourite parts of using API Resources. Most people assume resources are only used for building up responses, but they are mistaken. I have used resources to build up JSON data objects for when interacting with external (or even internal) APIs.

    You create the resource just as you normally would:

    $fridge = Fridge::where(‘model’, $request->model)->where(‘black_friday_sale’, true)->first();
    $fridge_resource = json_encode(FridgeResource::make($fridge));
    

    And this should build up a brilliant JSON encoded Fridge Resource. I feel doing this helps with a lot when it comes to managing your APIs. Having to deal with just one file makes life so much easier.

    Don’t forget to put FridgeResource::withoutWrapping() to get rid of the ‘data’ key wrapping the response!


    Conditional Attributes


    Conditional attributes are really interesting for me. If I have a model, let’s call it Fridge, and I’m sending a response to more than one person (depending on their role) I would typically have some sort of nested folder structure like so:

    Fridge > Manager > FridgeResource.php
    Fridge > Customer > FridgeResource.php

    It’s the same file, but with some differences. Perhaps for my Manager I want to show the amount of sales for that specific fridge, or when it’ll go on sale, or what the purchase price is/was, and you don’t want your customers seeing that sort of info!

    So we can use Conditional Attributes in our resources. We can utilise the when helper method that Laravel has so lovingly provided for us.

    return [
    
        // Regular fridge data
        ‘name’ => $this->name,
        ‘model-no’ => $this->model_no,
        ‘price’ => $this->price,
        ‘weight’ => $this->weight,
        ‘on-sale-black-friday’ => $this->black_friday_sale,
        ‘black-friday-discounted-price’ => $this->discount_price,
    
        // Only for managers
        ‘sales-today’ => $this->when(Auth::user()->isManager(), $this->getSales()),
    
        // Only for admins
        ‘self-destruct’ => $this->when(
            Auth::user()->isAdmin(),
            url(“self-destruct/{$this->id}”)
        ),
    
    ];
    

    If the condition is true, then the fields are displayed in the response. If the user is not an admin, or a manager the `sales-today` and `self-destruct` keys will be completely removed from the response.
    If you have multiple attributes you want to keep hidden you can surround them with the mergeWhen method:

    $this->mergeWhen(Auth::user()->isManager(), [
        ‘sales-today’ => $this->getSales(),
        ‘next-sale-date’ => $this->next_sale_date,
    ])
    

    Contact us


      Related posts:

      dynamic doughnut graph using laravel vue componentDynamic Doughnut Graph Using Laravel Vue Component laravel logoWorking With Eloquent: API Resources In Laravel laravel livewireLaravel Livewire laravel observersLaravel Observers
      Share
      76
      Gary Irwin
      Gary Irwin
      Gary is currently the CEO of Lava Lamp Lab, he has extensive experience in ICT Services & Business with global experience focusing on software and product development in emerging market. Working with High-calibre customers to deliver an array of B2B & Consumer Applications. Though Lava Lamp Lab, he leads multi-skilled teams in development & implementation of integrated IT solutions for companies through harnessing IoT (Internet of Things) , ML (Machine Learning) Platforms, Big Data / BI technologies. He consults on Application Modernization, Product Development, Ideation and Delivery Management of Solutions.

      Leave a Reply Cancel reply

      Your email address will not be published. Required fields are marked *

      Lava Lamp Lab


      Like technology, a lava lamp constantly changes form, producing new conditions with every passing moment



      lava lamp lab facebook   lava lamp lab twitter   lava lamp lab linkedin   lava lamp lab instgram

      Services


      Application & software development

      Outsourced software development

      Project based resourcing

      Digital marketing & consulting

      Graphic design & consulting

      UI / UX design & consulting

      Contact Us


      +27(0) 83 419 4851

      +27(0) 21 036 1165


      switchon@lavalamp.biz


      Unit 4 Monaco Square,
      14 Church Street,
      Durbanville,
      Cape Town, 7550

      NBConsult Group


      nbconsult
      nbconnect msp
      nbclearning
      river broadband
      designer needed
      © 2023 Lava Lamp Lab (Pty) Ltd | All Rights Reserved | Privacy Policy
      Contact us now

        Application & software development

          Outsourced software development

            Project based resourcing

              Digital marketing & consulting

                Graphic design & consulting

                  UI/UX design & consulting

                    Lease an expert

                      Recruitment services

                        We are using cookies to give you the best experience on our website.

                        You can find out more about which cookies we are using or switch them off in settings.

                        Lava Lamp Lab
                        Powered by  GDPR Cookie Compliance
                        Privacy Overview

                        This website uses cookies so that we can provide you with the best user experience possible. Cookie information is stored in your browser and performs functions such as recognising you when you return to our website and helping our team to understand which sections of the website you find most interesting and useful.

                        Strictly Necessary Cookies

                        Strictly Necessary Cookie should be enabled at all times so that we can save your preferences for cookie settings.

                        If you disable this cookie, we will not be able to save your preferences. This means that every time you visit this website you will need to enable or disable cookies again.

                        3rd Party Cookies

                        This website uses Google Analytics to collect anonymous information such as the number of visitors to the site, and the most popular pages.

                        Keeping this cookie enabled helps us to improve our website.

                        Please enable Strictly Necessary Cookies first so that we can save your preferences!

                        Cookie Policy

                        More information about our Cookie Policy