Niet leuk zo'n cookie🍪 melding, maar het moet toch gebeuren: Deze website maakt gebruik van cookies en daarom zijn we verplicht om je hierover te informeren en jouw toestemming te vragen. Studio Rebels maakt gebruik van Google Analytics. Wij gebruiken deze dienst om bij te houden en rapportages te krijgen over hoe bezoekers de website gebruiken.

Coding with Murtaza Instagram Livewire Component.

Let's build a Livewire component of our Instagram Feed we've build in part 1 and style it with Tailwind CSS.

Murtaza Yurtsev Full Stack Developer
Murtaza Yurtsev - 22 Feb 2022
1 min leestijd

#Laravel #Livewire #Tailwind CSS #Instagram #API

Assumptions

Install Livewire

You can skip this part if you already have Livewire installed in your Laravel application. If not: Install it with Composer: composer require livewire/livewire and include the assets @livewireStyles in your head and add @livewireScripts right before the closure of the body tag.

Create the Livewire component

After that's done, run the following command to create our component.

php artisan make:livewire InstagramFeed

Two new files should be created in your project:

app/Http/Livewire/InstagramFeed.php
resources/views/livewire/instagram-feed.blade.php

Let's mix it up! 🤓

Let's mix it up a little shall we? Let's say we want to fetch all images, but only show 2 random images with it's captions. To make use of the powers of Livewire, let's say we want to load 2 random images every 5 seconds. Just to make it more alive! All this without a single line of javascript (Livewire magic 🪄).

Preparing the component

So as a start we are going to use the code we've already written in instagramAuthController.php in part 1 of the series. But as we agreed earlier, we want to show only 2 random images. Here's how we can achieve that:

namespace App\Http\Livewire;

use Livewire\Component;

class InstagramFeed extends Component
{
    public function render()
    {
        $instagramFeed = \Dymantic\InstagramFeed\InstagramFeed::for('studiorebels');
        foreach($instagramFeed as $key => $post) {
            $arr_feed[] = $post;
        }

        $feed = [];
        while (count($feed) < 2) {
            $randomKey = mt_rand(0, count($arr_feed)-1);
            $feed[$randomKey] = $arr_feed[$randomKey];
        }

        return view('livewire.instagram-feed', compact('feed'));
    }
}

What happens here? Well, we made a array from the object and with the use of the funnction mt_rand() we chose a random key from the array and store it in a new fresh array $feed. We used a while loop to only store 2 random items in the array and finally pass the feed array to our view.

Markup & Styling

Now we can loop though our images in the view and visualize them however we want. If you visited the homepage of our website, you've probably seen the social feed. If not: it's right there before the footer.

Styling

I like to use Tailwind CSS as my default CSS framework. This utility based framework will have all the classes we need. We can generate classes if it's not supported by default, without the need to write css code. We can extend the css framework in stead of overwriting or altering it like other CSS frameworks out there.

If you don't have Tailwind installed, install it with NPM:

npm install -D tailwindcss postcss autoprefixer
npx tailwindcss init

Tailwind CSS has a specific installation guide for Laravel, follow the steps here and come back when it's ready to rock & roll. I'll wait 😉

View

Now we can build our feed in view instagram-feed.blade.php. Here is how mine looks like:

<div wire:poll.visible.5000ms>
  <div class="md:flex md:flex-wrap items-center text-sr-gray dark:text-blueish-gray leading-7 -px-2 -py-2">
    @foreach ($feed as $key => $post)

      @if($post->type === 'carousel')
        @foreach($post->children as $carouselKey => $carouselPost)
          <div class="{{ $carouselKey === 0 ? 'hidden' : '' }} md:w-1/2 px-2 py-2 transition ease-in-out -skew-y-[4deg] hover:scale-105 hover:skew-y-0 duration-300 cursor-pointer rounded-xl relative">
            <a href="{{ $post->permalink }}" target="_blank">
              <img src="{{ $carouselPost['url'] }}" alt="" class="rounded-xl shadow-2xl transition ease-in-out duration-500">
            </a>
          </div>
        @endforeach
      @else
        <div class="md:w-1/2 px-2 py-2 transition ease-in-out -skew-y-[4deg] hover:scale-105 hover:skew-y-0 duration-300 cursor-pointer rounded-xl relative">
          <a href="{{ $post->permalink }}" target="_blank">
            <img src="{{ $post->url }} " alt="" class="rounded-xl shadow-2xl transition ease-in-out duration-500">
          </a>
        </div>
      @endif

      <div class="md:w-1/2 px-2 py-2 transition h-auto dark:text-white text-xs text-center ease-in-out -skew-y-[4deg] hover:scale-105 hover:skew-y-0 duration-300 cursor-pointer">
        <div class="bg-white dark:bg-deepseablue rounded-xl min-h-[260px] p-5 h-full flex flex-wrap items-center justify-center shadow-xl hover:shadow-2xl">
          <div class="flex-1">
            <span class="block text-2xl text-white mb-2">✍️</span>
            @php
                $caption = trim( preg_replace('/[\x00-\x1F\x80-\xFF]/', ' ', mb_convert_encoding( $post->caption, "UTF-8" ) ) );
            @endphp
            <span class="box-decoration-clone text-transparent bg-clip-text bg-gradient-to-br from-sr-purple to-sr-green fadeIn font-bold">{!! strlen($post->caption) > 150 ? substr($caption,0,150).'...' : $caption !!}</span>

            <div class="block">
              <a href="{{ $post->permalink }}" target="_blank" class="transition ease-in-out hover:scale-110 duration-300 inline-block py-1 px-3 mt-4 bg-sr-green text-white rounded-full font-semibold text-xs">Lees meer</a>
            </div>
          </div>
        </div>
      </div>
    @endforeach
  </div>
</div>

Did you notice <div wire:poll.visible.5000ms>? This is where the magic of Livewire happens. This will refresh the component only if it's visible in the viewport. So a ajax call to the back-end. Every 5 seconds 2 random posts will be shown. All this without a single line of javascript and/or jquery.

Important note however: If you want to copy the markup above, you should change the color classes. I used my own colors that I've added to the Tailwind configuration file. Here is a part of my tailwind configuration if you want to use it anyway.

colors: {
    'deepseablue': '#12171D',
    'sr-purple': '#676BDC',
    'sr-green': '#3BAFCA',
    'sr-gray': '#54565A',
    'blueish-gray': '#7F848C',
  },

Demo on Laravel PLayground

I've constructed a little demo with Laravel Playground. Some side notes:

Klaar om je ideeën om te zetten in software?

Klaar voor uw volgende project? Of heeft u een idee die u wilt verkennen? Neem gerust contact op om de mogelijkheden vrijblijvend te bespreken. Studio Rebels is expert in het ontwikkelen van (zakelijke) apps met additionele webapplicaties, webportalen, dashboards, webshops en websites.

Van idee tot App