Tag: Web Development

  • How to test Laravel with Sanctum API using the Postman

    In the last part, we completed the Laravel Breeze API installation and validated the API using the Breeze Next front end.

    In this blog, we going to test the API using the Postman application.

    About Postman

    Postman is software used to test the API by sending and receiving the request with multiple data formats along with auth.

    Postman is an API platform for building and using APIs. Postman simplifies each step of the API lifecycle and streamlines collaboration so you can create better APIs — faster.

    Install Postman

    Click here and complete your Postman installation. After installation opens the Postman application.

    Create a new Postman Collection

    Click the create new button

    In the popup window click the collections

    Enter the name “Laravel Admin API” and select auth type that is No auth.


    Pre-request Script

    In the Laravel Sanctum, we used SPA authentication. So it works by using Laravel’s built-in cookie-based session authentication services. So, we need to set the cookie for all the requests in Postman.

    We can set the cookie by using the Postman Pre-request Script. Add the below code to Pre-request Script.

    pm.sendRequest({
        url: pm.collectionVariables.get('base_url')+'/sanctum/csrf-cookie',
        method: 'GET'
    }, function (error, response, {cookies}) {
        if (!error){
            pm.collectionVariables.set('xsrf-cookie', cookies.get('XSRF-TOKEN'))
        }
    })

    In this script, we used some variables. We will create variables in the next step.


    Postman Variables

    Add the host, base_url, and xsrf-cookie variables in the Postman variables section


    Postman Add Request

    Click the “Add a request” link and create a new request for registration.

    In the header section add the “Accept” and “X-XSRF-TOKEN” like below

    Also, you can add plain text values by clicking the “Bulk Edit”

    Accept:application/json
    X-XSRF-TOKEN:{{xsrf-cookie}}

    In the request Body, add the below values on form-data

    name:admin
    email:user1@admin.com
    password:password
    password_confirmation:password

    Register API request

    Click the “send” button

    You will get an empty response if the user is registered successfully


    Get User API request

    Now we going to create an API to get the current user details. Click and create a New Request with the get method.

    The API URL is /api/user and also add the below headers.

    Accept:application/json
    Referer:{{host}}

    For this request, the body is none, and then click send the request. You will get the current user details in the response.


    Logout Request

    Create the logout request with /logout URL with the post method. Also, add the headers.

    Accept:application/json
    X-XSRF-TOKEN:{{xsrf-cookie}}

    You will get an empty response after sending the request.


    Login Request

    We have completed the user register, get the user, and logout. Only login is pending.

    Header

    Accept:application/json
    X-XSRF-TOKEN:{{xsrf-cookie}}

    Body: Select form-data and insert the below values

    email:user1@admin.com
    password:password

    We have created 4 requests in Postman and validated our Admin API. You can import the below-exported data and use it in the Postman. Next part we add permission and roles to our admin API.

    {
     "info": {
      "_postman_id": "6822504e-2244-46f9-bba8-115dc36644f6",
      "name": "Laravel Admin API",
      "schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json",
      "_exporter_id": "25059912"
     },
     "item": [
      {
       "name": "Register",
       "request": {
        "method": "POST",
        "header": [
         {
          "key": "Accept",
          "value": "application/json",
          "type": "text"
         },
         {
          "key": "X-XSRF-TOKEN",
          "value": "{{xsrf-cookie}}",
          "type": "text"
         }
        ],
        "body": {
         "mode": "formdata",
         "formdata": [
          {
           "key": "name",
           "value": "admin",
           "type": "text"
          },
          {
           "key": "email",
           "value": "user1@admin.com",
           "type": "text"
          },
          {
           "key": "password",
           "value": "password",
           "type": "text"
          },
          {
           "key": "password_confirmation",
           "value": "password",
           "type": "text"
          }
         ]
        },
        "url": {
         "raw": "{{base_url}}/register",
         "host": [
          "{{base_url}}"
         ],
         "path": [
          "register"
         ]
        }
       },
       "response": []
      },
      {
       "name": "User",
       "request": {
        "method": "GET",
        "header": [
         {
          "key": "Accept",
          "value": "application/json",
          "type": "text"
         },
         {
          "key": "Referer",
          "value": "{{host}}",
          "type": "text"
         }
        ],
        "url": {
         "raw": "{{base_url}}/api/user",
         "host": [
          "{{base_url}}"
         ],
         "path": [
          "api",
          "user"
         ]
        }
       },
       "response": []
      },
      {
       "name": "Logout",
       "request": {
        "method": "POST",
        "header": [
         {
          "key": "Accept",
          "value": "application/json",
          "type": "text"
         },
         {
          "key": "X-XSRF-TOKEN",
          "value": "{{xsrf-cookie}}",
          "type": "text"
         }
        ],
        "url": {
         "raw": "{{base_url}}/logout",
         "host": [
          "{{base_url}}"
         ],
         "path": [
          "logout"
         ]
        }
       },
       "response": []
      },
      {
       "name": "Login",
       "request": {
        "method": "POST",
        "header": [
         {
          "key": "Accept",
          "value": "application/json",
          "type": "text"
         },
         {
          "key": "X-XSRF-TOKEN",
          "value": "{{xsrf-cookie}}",
          "type": "text"
         }
        ],
        "body": {
         "mode": "formdata",
         "formdata": [
          {
           "key": "email",
           "value": "user1@admin.com",
           "type": "text"
          },
          {
           "key": "password",
           "value": "password",
           "type": "text"
          }
         ]
        },
        "url": {
         "raw": "{{base_url}}/login",
         "host": [
          "{{base_url}}"
         ],
         "path": [
          "login"
         ]
        }
       },
       "response": []
      }
     ],
     "event": [
      {
       "listen": "prerequest",
       "script": {
        "type": "text/javascript",
        "exec": [
         "pm.sendRequest({",
         "    url: pm.collectionVariables.get('base_url')+'/sanctum/csrf-cookie',",
         "    method: 'GET'",
         "}, function (error, response, {cookies}) {",
         "    if (!error){",
         "        pm.collectionVariables.set('xsrf-cookie', cookies.get('XSRF-TOKEN'))",
         "    }",
         "})"
        ]
       }
      },
      {
       "listen": "test",
       "script": {
        "type": "text/javascript",
        "exec": [
         ""
        ]
       }
      }
     ],
     "variable": [
      {
       "key": "host",
       "value": "localhost:3000",
       "type": "string"
      },
      {
       "key": "base_url",
       "value": "http://localhost",
       "type": "string"
      },
      {
       "key": "xsrf-cookie",
       "value": "",
       "type": "string"
      }
     ]
    }
    

    Also, all the Request is available in below Postman public workspace

    https://www.postman.com/balajidharma/workspace/laravel-admin-api/collection/25059912-6822504e-2244-46f9-bba8-115dc36644f6?action=share&creator=25059912

  • Add Role and Permissions based authentication to Laravel API

    To manage roles & permission, we going to add the Spatie Laravel-permission package to our Laravel Admin API.

    The following steps are involved to install the Laravel permission package for our Laravel Admin API.

    • Install Spatie Laravel-permission package
    • Publish the configuration and migration file
    • Running Migration

    Install Spatie Laravel-permission package

    Install the package using the composer command

    ./vendor/bin/sail composer require spatie/laravel-permission

    Publish the configuration and migration file

    The vendor:publish artisan command is used to publish the package configuration to the config folder. Also, copy the migration files to the migration folder.

    ./vendor/bin/sail artisan vendor:publish --provider="Spatie\Permission\PermissionServiceProvider"

    Running Migration

    Run the migrations using artisan migrate

    ./vendor/bin/sail artisan migrate

    Now we need to add some roles & permission. Then need to assign the role to users. So we need to create seeders.

    I created an Admin core package with seeders and common functionality when I was working on Basic Laravel Admin Panel & Laravel Vue admin panel

    Add the admin core package to our Admin API

    ./vendor/bin/sail composer require balajidharma/laravel-admin-core

    This admin core package will install the Laravel Menu package. So run the below publish commands

    ./vendor/bin/sail artisan vendor:publish --provider="BalajiDharma\LaravelAdminCore\AdminCoreServiceProvider"
    ./vendor/bin/sail artisan vendor:publish --provider="BalajiDharma\LaravelMenu\MenuServiceProvider"

    Now run the migration with the seeder

    ./vendor/bin/sail artisan migrate --seed --seeder=AdminCoreSeeder

    The seeder throws the error

    We need to add HasRoles Traits in the user model. Open the app/Models/User.php

    <?php
    
    .
    .
    .
    .
    .
    use Spatie\Permission\Traits\HasRoles;
    
    class User extends Authenticatable
    {
        use HasApiTokens, HasFactory, Notifiable, HasRoles;
    
        /**
         * The attributes that are mass assignable.
         *

    Try again to run the seeder with migrate:fresh. So it will drop all tables and re-run all of our migrations.

    ./vendor/bin/sail artisan migrate:fresh --seed --seeder=AdminCoreSeeder

    Open the Postman application and test the new user login. In the login, change the form data to the below email and password

    Email — superadmin@example.com

    Password — password

    After login, runs the get user request. You will get the super admin details on the response.


    We will create an API for Permission CRUD operations in the next blog.

  • Laravel: Automate Code Formatting!

    Pint is one the newest members of Laravel first-party packages and will help us to have more readable and consistent codes.

    Installing and Configuring Laravel Pint is so easy and It is built on top of PHP-CS-Fixer so it has tones of rules to fix code style issues. (You don’t need Laravel 9 to use Pint and it’s a zero dependency package)

    But running Pint is quite painful because every time we want to push our changes to the remote repository we have to run below command manually:

    ./vendor/bin/pint --dirty

    The --dirty flag will run PHP-CS-Fixer for changed files only. If we want to check styles for all files just remove --dirty flag.

    In this article we want to simply automate running code styles check with Pint before committing any changed file so even team developers will have a well defined code structure and don’t need to run Laravel Pint every time before we push our codes to remote repo!

    Before we start, be careful this is a very simple setup and you can add as many options as you want to Laravel Pint.

    In order to run ./vendor/bin/pint --dirty just before every commit, we should use the pre-commit hook inside .git folder.

    First of all we will create a scripts folder inside our root Laravel directory. In this folder we will have a setup.sh file and pre-commit file without any extension.

    scripts/
    setup.sh
    pre-commit

    Inside our setup.sh we have:

    #! /usr/bin/env bash
    
    cp scripts/pre-commit .git/hooks/pre-commit
    chmod +x .git/hooks/pre-commit

    And write the following lines on pre-commit file:

    #! /usr/bin/env bash
    
    echo "Check php code styles..."
    echo "Running PHP cs-fixer"
     ./vendor/bin/pint --dirty
     git add .
    echo "Done!"

    Second of all, we should go to composer.json file and on the scripts object add this line: (If post-install-cmd key does not exist, you should create post-install-cmd part and then add below)

    "post-install-cmd": [
                "bash scripts/setup.sh"
            ]

    Third of all, we will require Pint package by this:

    composer require laravel/pint --dev

    And To be sure Don’t Forget to run:

    composer install

    The composer install command will add the pre-commit hook to our .git folder and after that we are ready to go!

    From now on, we can simply write our code and just before we commit our changes the Pint command will run automatically and will fix our code styles!

    Pint use Laravel code styles as defaultbut if you want to use psr-12 like me, you can create a pint.json file inside the root directory of your Laravel project and copy below json to have a more opinionated PHP code styles:

    {
        "preset": "psr12",
        "rules": {
            "simplified_null_return": true,
            "blank_line_before_statement": {
                "statements": ["return", "try"]
            },
            "binary_operator_spaces": {
                "operators": {
                    "=>": "align_single_space_minimal"
                }
            },
            "trim_array_spaces": false,
            "new_with_braces": {
                "anonymous_class": false
            }
        }
    }

    This is a simple config for our Pint command and will simplify null returns and define an equal indentation for arrays. You can check all PHP-CS-Fixer options here!

    READ MORE:

  • Top 8 Free and Paid Resources for Learning Laravel

    Introduction

    No matter if you’re brand new to Laravel or have been using it for years, there’s always something new to learn. The framework and its ecosystem are constantly evolving and growing to improve the overall developer experience. So, it can be quite important to keep up to date with the latest changes so that you don’t fall behind.

    It’s also likely that you’ve run into a coding problem once or twice and needed to reach out to people online for a bit of advice and help. Let’s be honest, as developers we spend quite a lot of time searching online on a daily basis looking things up. Whether it be to jog our memory on a certain algorithm or to look at possible ways of tackling new pieces of code.

    The list below shows you 8 different places you can go online to give help you learn Laravel, keep up to date with it and also ask community members questions:

    Laracasts (Free and Paid)

    Laracasts is an online platform that has over 1700 lessons that you can use to learn about Laravel and other web programming related topics. The great thing about Laracasts is that it doesn’t focus solely on Laravel; it also has lessons based around tooling, testing and different programming languages. For example, there is a series of lessons based around getting your IDE (integrated development environment) or text editor, such as PHPStorm or Visual Studio Code, set up to make your development experience more productive.

    At the time of writing this article, some of the lessons on Laracasts are free and you can view them without having to spend any money at all! However, I would strongly recommend signing up for a paid account, which is $15/month, so that you can get full access to all of the tutorials.

    Another great thing about the Laracasts are it’s forums and the helpful community. If you ever have any questions or an issue that you can’t figure out, you can post it on to the forum. A large majority of the time, someone will reply to you with an answer that helps you solve your problem.

    Laravel News (Free)

    Laravel News is the official Laravel news source. They post new articles, tutorials and tips on a daily-basis as well as provide a newsletter that is sent out regularly. These articles always have useful information about different topics or new Laravel packages that you can use within your code.

    Although Laravel News doesn’t have a forum like Laracasts, the newsletter and podcast that they provide are extremely beneficial at keeping you up to date with the latest goings-on in the Laravel space.

    As a side note, I’ve actually had two of my Laravel packages that I’ve built in the past (Laravel Exchange Rates and Laravel Executor) featured on the Laravel News website. If you’d like to check them out, the articles were: Laravel Exchange Rates API Package and Simplify Installing and Updating your App With Laravel Executor.

    Laravel Documentation (Free)

    One of the most useful resources for helping you learn how to use Laravel is the official Laravel documentation. The documentation is really detailed and covers a large amount of the framework that you would touch when working on projects.

    Typically, huge amounts of documentation can feel overwhelming and can feel like being bombarded with too much information at once. However, I personally feel like the Laravel documentation does a really good job of splitting things out and making it easy to understand. Even after working with Laravel for years, I still always have the documentation open in a tab in my web browser just in case I need to quickly brush up on a topic.

    Top tip: For any of you that use DuckDuckGo as your search engine, you can search for “!laravel” and it will take you straight to the Laravel documentation.

    Udemy (Paid)

    Udemy is a video platform that’s similar to Laracasts. It sells online video courses that you can use to learn about a range of topics. However, they have a section that is dedicated to Laravel and learning how to use it; ranging from beginner to advanced courses.

    I’ve never personally used Udemy myself, but I know other developers that I work with that swear by it and find it extremely useful.

    Stack Overflow (Free)

    If you’ve ever done any type of software or web development, chances are you, you probably visit Stack Overflow on a daily basis. But if you’re just starting out as a developer, you might not have heard of it yet.

    Stack Overflow is an online question-and-answer site for developers. As an example, say if you have a question about something or have a bug in your code, you could post your question on Stack Overflow and someone would try and answer it for you. However, the chances are that if you’ve got a problem, someone else has already had it, posted the question and got an answer that solved their issue. So, Stack Overflow can be a great resource that contains almost instant answers for any problems that you might run into.

    If you need to ask a question though because it doesn’t already exist there, the community is usually really quick at answering.

    GitHub (Free)

    This resource is slightly different to some of the others above and might be a little more suitable for more experienced developers rather than any novices. There are countless Laravel projects and packages that you can find on public GitHub repositories. So, this means that there are a lot of places that you can look at to get ideas for development.

    As an example, when I first started writing Laravel packages, I wasn’t too sure on where to start. So, after reading through the Laravel documentation, I also checked out how other packages had been written. I looked at some of the official Laravel packages, such as Telescope, and also looked at how some of the Spatie packages were written. Being able to look at real-life examples of code can sometimes be more valuable than just looking at documentation that explains something. It gives you an insight and context into how things are actually done in practice.

    As a small side note as well, once you feel that you have enough experience with Laravel, you could maybe start contributing to open-source projects. This can be a little bit daunting at first but can feel extremely rewarding when your first pull request is accepted. When you make your pull request, the maintainers of the project will review your changes and additions to check that they’re okay to pull in. It’s usually during this stage that you get feedback on any changes you might need to make to get the pull request approved and merged. This feedback can really help you grow as a developer.

    Reddit (Free)

    Reddit is one of my personal favorite resources for keeping up to date with the latest Laravel and PHP topics. The r/laravel and r/php subreddits are made up of large communities of developers who can answer questions that you might have.

    I have asked questions on Reddit many times in the past for suggestions on how to tackle issues and have always been able to find an answer. The r/laravel subreddit also has a weekly “No Stupid Questions” thread that you can use to comment on and ask questions. Just remember though, if you’re asking any questions in any of the subreddits that you follow their rules; otherwise your post will get deleted.

    If you don’t want to post anything or ask any questions, the two subreddits can also be really helpful for keeping up to date with the latest news on the ecosystem.

    Other Laravel Developers (Free and Paid)

    One resource for learning Laravel that developers often overlook is possibly one of the most valuable… other developers. Sometimes, it can be really easy to sit and stare at a problem for a few hours without getting anywhere with it. Usually when this happens, it can be best to get an opinion from someone else who is looking at the problem from a different perspective. For this reason, it can be really useful to have other developers as friends or as someone you can contact.

    If you only have a quick question, quite a lot of developers will probably be happy to help you out and lend a helping hand (I know I would!). But, obviously, you have to remember that other people also have things they need to do and won’t want to be spending too much time helping you out for free. So, if you do contact a developer for help, try not to do it too often as it might discourage them from wanting to help you.

    Sometimes, you might also want to pay a more experienced developer to have a chat for an hour or two to go over some topics. Like I mentioned earlier, looking at documentation can give you an idea of how something is done, but speaking to someone can help you understand the “why”. Speaking to senior developers can be extremely helpful because it’s likely that if you run into a problem that they’ve already experienced something similar themselves and know any pitfalls that you should to try to avoid.

    If you have any questions about anything Laravel related or need any Laravel web development doing, you can always feel free to contact me and have a chat.

    Originally published at https://ashallendesign.co.uk.

    Source: https://ashallendesign-uk.medium.com/top-8-free-and-paid-resources-for-learning-laravel-4927b0174cab

  • 6 Crazy Front-End Portfolios You Should Check Out

    6 Crazy Front-End Portfolios You Should Check Out

    Image for post
    Photo by Matthieu Comoy on Unsplash

    One of the toughest websites a web developer can make is a portfolio site showcasing all of the projects, experience, and skills.

    Not that building a portfolio site is programmatically challenging but because it is a place that potential employers will use to evaluate your work.

    Questions like “What projects to show first?” and “Should I add a photo of myself?” are just some of the many questions that come to mind when building a personal portfolio.

    Most web developers have built projects that aren’t unique like movie ratings or a calculator app.

    Therefore, one of the most differentiating factors for you can be building a highly unique portfolio site to showcase all these projects as well as any other past work.

    However, if you are looking to create a new project just for your portfolio, you can check my recent article on some of the most unique APIs.7 Free APIs That Nobody Is Talking AboutCreate unique and interesting apps using these APIsmedium.com

    Below are 6 highly unique portfolio websites you should definitely check out:

    1. Bruno Simon

    Bruno Simon is a creative developer and his portfolio is not a typical website that you’d come to expect.

    This is by far the most unique and interactive portfolio on this list.

    Bruno has created a uniquely immersive site, in which you can navigate using a car.

    The site is incredibly detailed and objects are moveable as well.

    As he states, he has used Three.js for the WebGL rendering.

    In fact, Bruno is on Medium and you can check his descriptive blog on the portfolio site.

    2. Ilya Kulbachny

    Ilya Kulbachnny’s site is one of the cleanest yet unique websites.

    Even though he has primarily used a black and white color scheme, he has worked on making the text large while adding a smooth scroll animation.

    Moreover, you can see that at the top of the page, the text “creative director” is also animated and he has used a personal photo of his as a background.

    Using a personal picture of yourself is important if you want to connect with your audience or you are a freelancer.

    Nonetheless, adding a personal picture won’t hurt and Ilya’s site demonstrates how he has used his personal picture which also has animate on scroll property.

    3. Abhishek Jha

    Abhishek’s portfolio follows the same color palette as the one above but his use of text, as well as the same animation on a scroll, gives it a unique touch.

    Another immediate takeaway is that he has replaced the default scrollbar with his own and also the cursor icon changes when you scroll over images.

    By placing the same text with different styles below one another and making the image overlap these texts is an interesting approach that, when used correctly, can be used to lay emphasis on particular texts.

    Not many people know but you can actually customize the scrollbar directly from your CSS file.

    /* width */
    ::-webkit-scrollbar {
    width: 10px;
    }

    /* Track */
    ::-webkit-scrollbar-track {
    background: #f1f1f1;
    }

    /* Handle */
    ::-webkit-scrollbar-thumb {
    background: #000;
    }

    /* Handle on hover */
    ::-webkit-scrollbar-thumb:hover {
    background: #355;
    }

    You can find more on this here.

    4. Robby Leonardi

    Much like Bruno Simon’s portfolio, this is also an interactive game. However, Bruno’s site included 3D graphics and a car to navigate, while this is a 2D game.

    Robby’s portfolio reminded me of the beloved Mario game.

    Robby Leonardi also has a portfolio site for illustrations and the same graphic and theme have made their way to it as well.

    He has done an outstanding job in making these sites and it’s rather out-of-box thinking.

    The background of his illustration portfolio as well as all the images used blend in perfectly, as well as showcases his finest works at the same time.

    5. Jacek Jeznach

    Another outstanding portfolio you should check out is by Jacek Jeznach.

    By using a very TikTok-like color palette and simple animations, he put together an enthralling website.

    The theme even extends to the map on the contacts page.

    He has even added background sound that you can easily toggle on and off.

    If you look closely you can even see that key HTML tags are present at the start and end of the webpage which is a neat addition to this site.

    This website is a great example of combining vibrant colors with a dark background and how to bring about an aspect of uniformity.

    6. Damian Watracz

    Damian’s site is a great example that giving attention to detail can drastically transform the site.

    This website utilizes a simple black and white color palette primarily.

    By combining simple animations, custom loading circles as well as the apt personal photo, Damian has managed to put together a very polished and professional website.

    One of the things I really liked about his site is that when you hover over the items in the menu, the background changes to reflect the link address page which is a thoughtful addition.

    Moreover, the pagination on this page is not common and really blends with the website.

    Another useful takeaway from this site is that the small yet notable contact button on the bottom left side of the page. It is a helpful shortcut that does not get in the way.

    Final thoughts

    Building a personal portfolio can be quite challenging.

    The main reason I have put together this list is to show that each portfolio site is unique and great in its own manner.

    There is no definite way you can go about while building sites like these.

    The only thing to keep in mind is to give your best and add your own personal touch to the site.

    If you enjoyed or felt inspired after reading this article, do check out my article on design inspirations.

  • 8 VSCode Extensions Every Developer Must Have

    Vedant Bhushan7 days ago

    These are awesome extensions! Maybe you could add tabnine as well.

    2

    2 replies

    Reply

    Jacob Bankston

    Jacob Bankston3 days ago

    Definitely picked up Turbo Console Log, and had a few of the others already! Great list overall.I would recommend adding indent-rainbow, it colorizes the indentations of lines to make your code more readable.

    1

    1 reply

    Reply

    Sylvain Pont

    Sylvain Pont7 days ago (edited)

    TCL is Amazing, thank you for that.Some remarks:Project manager seems to be a LOT more used than Projects. Whould you explain why you chose the later?VSCode now ships with Sync Settings. I used to use Settings sync extension but the VSCode one is…...

    Read More1 reply

    5 min read

    VS Code is one of the most popular and widely used code editor. It comes packed with lots of features that are free in comparison to other editors. You can download extensions on VS code, which add another dimension of incredible features.

    I have listed some of my favorite VS code extensions, without which I cannot live.

    Please note that there is no ranking involved. Each extension is impressive in itself. The last one and the first are equal.

    I am sure you will leave with a new extension that will make your work easier.

    1. Turbo Console Log

    Turbo console log is a killer extension when coming to the debugging part. This extension makes debugging easier by automating the process of writing meaningful log messages.

    You insert meaningful log message automatically with two steps:

    • Selecting the variable which is the subject of the debugging
    • Pressing ctrl + alt + L

    2. Import cost

    Speed is essential for your website. If your page or app can’t load quickly, it is the same as no page.

    This extension displays your import’s size. This way, you get to know how much you will be downloading and figure out why your application is sluggish.

    With this extension, you can decide if you should write a function or import the whole bundle.

    3. Prettier

    This extension is for everyone, be it If you code in python, JavaScript, or any other language.

    It makes your code, as the name suggests, prettier.

    I am terrible at giving equal lines and spacing and tab. As a result, my code looks just like some noodle pasta.

    With prettier, as soon as you press command+S, you will experience the magic. All your code will get correctly and equally spaced, and proper line spaces. Your code will look beautiful.

    No-One will ever identify how messy you are 😐.

    4. Bracket pair colorizer

    How many times it happens that when editing JavaScript code, you have trouble finding the closing brackets. It is painful to use the finger to trace the opening and closing brackets. Stop wasting your time and use this extension.

    Your opening and closing brackets are colored the same; it is easier this way.

    This extension is a must-have for those who have spent time with python because python doesn’t require brackets; this will help the transition.

    Image for post

    5. Live share

    Live share is a fantastic extension. With it, I can code with my friends, colleagues.

    Whenever I am stuck with a problem, I can pull over my friend to help me.

    What this extension does is that it gives remote control of your VS code editor, the opened files. With that, another person can change my code and save it—no need to struggle over the phone anymore or wait to meet your friend to get help.

    One of the features you get with this is that — You get to code in real-time. You get to know who is typing and what it is that they are entering. It makes coding just like messaging, which we all love. Thanks to VS code and live share. Besides, it also gives access to localhost, your terminal.

    Live share is one of the best features of VS code, in my opinion, and the reason I recommend it to everyone. I haven’t seen anything as good as it and free to use. Mind-blowing!

    Bonus: You can download the live share audio extension, which adds audio calling capabilities to Live Share. I love this and especially in the pandemic when everything has gone remote.

    6. Projects

    If you are working on several projects at a time, then switching between folders is hard. You have to navigate to the required folder. And if you switch between quite often, then it is hell.

    One use I find with this extension is that it can work as your favorite tab. E.g. Someone may store custom CSS and bootstrap in a folder and use this extension to navigate in between quickly.

    Image for post

    7. Settings Sync

    As the name suggests, setting sync extension stores all your setting backup in GitHub. This way, you can have the same settings for your multiple devices or new devices. Any changes made can be seamlessly synchronized.

    It allows you to sync pretty much everything you customize on VS Code to Github, from settings to keyboard shortcuts to other VS Code extensions.

    8. JavaScript (ES6) Code Snippets

    VS Code comes with built-in JS IntelliSense, but JS Code Snippetsenhances that experience further by adding premade JavaScript snippets, which contain the most commonly used snippets. No more repeating of code endlessly.

    The extension supports JS, TypeScript, JS React, TS React, HTML, and Vue.

    Image for post

    I hope you enjoyed reading and I provided value to you. If you find extensions that I have missed and you find it amazing, mention it in response.

    Thank You 🙌

    Ali Haider

    Over 5 years of obsession with technology || Writer and developer. I love making new friends, why don’t we be friends?

  • 7 Free APIs That Nobody Is Talking About

    7 Free APIs That Nobody Is Talking About

    Ethan O’Sullivan2 months ago

    APIs are vital tools in the success of any app.

    I agree, I would run into issues trying to use an XML feed because of it's formatting. So I developed an API that converts XML to JSON, check it out:https://medium.com/p/b09734329bc9

    5

    Reply

    Bizzabe83Bizzabe832 months ago

    Many times we just want to focus on the frontend

    Good read

    10

    Reply

    Alex Mireles

    Alex Mireles2 months ago

    Isn't 90% of this list on every beginner API?

    1

    Reply

    Chris Hornberger

    Chris Hornberger2 months ago

    Also, your comment about “everyone using the same APIs...” being a bad thing is just silly. What that does is create uniformity and standards. Oy.

    Reply

    { rxluz }

    { rxluz }2 months ago

    Wow, that’s handy APIs! The glyph and recipe I’ll use in some future project for sure, one suggestion to add to your excellent list is Unplash, I use it before to allow users to search high-quality and free for use images, others to check the weather and result of matches are quite useful as well.

    Anurag KanoriaNov 23, 2020 · 6 min read

    Nothing excites me more than finding an out of the ordinary API.

    Many times we just want to focus on the frontend but also need interesting, dynamic data to display.

    This is where public APIs come into play. API is an acronym for Application Programming Interface.

    The core benefit of using it is that it allows one program to interact with other programs.

    Using public APIs allows you to focus on the frontend and things that matter without worrying so much about the database and the backend.

    Below are 7 less-talked about public and free APIs.

    1. Evil Insult Generator

    How many times have you tried to insult your best friend? Now you have got a helping hand!

    As the API name suggests, the goal is to offer some of the evilest insults.

    You can create an app centered around this API or combine this API with other excellent APIs provided below like implementing the generated insults in meme templates.

    The API is extremely simple to use. You just need to visit a URL and you get the desired JSON output without even signing up for a key.

    Sample output of the API is provided below:

    {
    "number":"117",
    "language":"en",
    "insult":"Some cause happiness wherever they go; others, whenever they go.",
    "created":"2020-11-22 23:00:15",
    "shown":"45712",
    "createdby":"",
    "active":"1",
    "comment":"http:\/\/www.mirror.co.uk\/news\/weird-news\/worlds-20-most-bizarre-insults-7171396"
    }

    You get the other properties as well such as the time it was created, the language, any comment as well as the views.

    2. Movies and TV API

    TMDb is a famous API, but do you know there are other API that provides insights from specific shows and movies?

    Below are some of the APIs you can use to develop apps featuring your favorite show:

    1. Breaking Bad API
    2. API of Ice And Fire
    3. Harry Potter API
    4. YouTube API (for embedding YouTube functionalities)
    5. The Lord of the Rings API

    Like the API above, you can get started with some of the APIs without even signing up for a key.

    Not only this, using non-copyright images, you can truly create a great fan app for your beloved shows.

    Below is a sample output from the Breaking Bad API which you can get here.

    It doesn’t require a key however has a rate limit of 10,000 requests per day.

    {
    [
    {
    "quote_id":1,
    "quote":"I am not in danger, Skyler. I am the danger!",
    "author":"Walter White",
    "series":"Breaking Bad"
    },
    {
    "quote_id":2,
    "quote":"Stay out of my territory.",
    "author":"Walter White",
    "series":"Breaking Bad"
    },
    {
    "quote_id":3,
    "quote":"IFT",
    "author":"Skyler White",
    "series":"Breaking Bad"
    }
    .....
    ]
    }

    It returns a JSON containing an array of objects with quotes, the author of the quotes, and an ID.

    You can mix these dedicated APIs with YouTube API to create an ultimate app for the fans of these shows.

    3. Mapbox

    Mapbox provides precise location information and fully-fledged tools to developers.

    You get instant access to dynamic, live-updating maps which you can even further customize!

    If you have a project geared towards location and maps, this is a must-know API.

    However, it is worth mentioning that you have to sign up for free to get a unique access token.

    Using this token you can use the amazing services offered by this API.

    Not only this, you can use Mapbox with libraries such as the Leaflet.js library and create beautiful, mobile-friendly maps.

    I have discussed this and much more in my recent article covering the basics of Mapbox and Leaflet.js.Add Interactive Maps to Your WebsiteWithout using Google Maps!medium.com

    4. NASA API

    NASA provides a fabulous updated database of space-related information.

    Using this API, one can create mesmerizing and educational apps and websites.

    You get access to various different kinds of data from the Astronomy Picture of the Day all the way to the pictures captured by the Mars Rover.

    You can browse the entire list here.

    You can also retrieve NASA’s patents, software, and technology spinoff descriptions which you can use to build a patent portfolio.

    This API is really diverse and offers a wide variety of data. You can even access the NASA Image and Video library using it.

    Below is a sample query of the pictures captured by Curiosity on Mars.

    {
    "photos":[
    {
    "id":102693,
    "sol":1000,
    "camera":{
    "id":20,
    "name":"FHAZ",
    "rover_id":5,
    "full_name":"Front Hazard Avoidance Camera"
    },
    "img_src":"http://mars.jpl.nasa.gov/msl-raw-images/proj/msl/redops/ods/surface/sol/01000/opgs/edr/fcam/FLB_486265257EDR_F0481570FHAZ00323M_.JPG",
    "earth_date":"2015-05-30",
    "rover":{
    "id":5,
    "name":"Curiosity",
    "landing_date":"2012-08-06",
    "launch_date":"2011-11-26",
    "status":"active"
    }
    },
    .....
    ]
    }

    5. GIF Search

    https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F3o7TKr2xg9OWcU8DWo%2Ftwitter%2Fiframe&display_name=Giphy&url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2F3o7TKr2xg9OWcU8DWo%2Fgiphy.gif&image=https%3A%2F%2Fi.giphy.com%2Fmedia%2F3o7TKr2xg9OWcU8DWo%2Fgiphy.gif&key=a19fcc184b9711e1b4764040d3dc5c07&type=text%2Fhtml&schema=giphySource: GIPHY

    We all love using and creating GIFs but did you know you can incorporate the GIFs in your next app for free using GIPHY?

    GIPHY is the largest GIF and sticker library in the world right now and using their official API you can leverage the vast collection to produce unique apps for free.

    Using the search endpoints, users can get the most relevant GIFs based on their query.

    You also get access to analytics and other tools which will enable you to create a personalized user experience.

    The most used feature, however, for me was the translate endpoint which converts words and phrases to the perfect GIF or Sticker. You can specify the weirdness level on a scale of 0–10.

    Note that you have to provide proper attribution by displaying “Powered By GIPHY” wherever the API is utilized.

    Below is a sample output of this API:

    {data: GIF Object[]pagination: Pagination Objectmeta: Meta Object}

    6. Favourite Quotes API

    As the name suggests, this API provides you with a thoughtful quotes collection.

    You can use these quotes to show on the landing page of your website or on the splash screen of your app to produce a rich user experience.

    You also get the ability to create and manage users and sessions via this API. However, there exists a rate limit of 30 requests in a 20-second interval per session.

    This API also has endpoints to filter, vote, list, update, and delete quotes.

    Below is the output for the Quote of the Day endpoint.

    {
    "qotd_date":"2020-11-23T00:00:00.000+00:00",
    "quote":{
    "id":29463,
    "dialogue":false,
    "private":false,
    "tags":[
    "great"
    ],
    "url":"https://favqs.com/quotes/walt-whitman/29463-the-great-cit-",
    "favorites_count":1,
    "upvotes_count":2,
    "downvotes_count":0,
    "author":"Walt Whitman",
    "author_permalink":"walt-whitman",
    "body":"The great city is that which has the greatest man or woman: if it be a few ragged huts, it is still the greatest city in the whole world."
    }
    }

    7. Edamam Nutrition and Recipe Analysis API

    Edamam generously provides access to a database of over 700,000 food items and 1.7 million+ nutritionally analyzed recipes.

    This API is great if you want to showcase your frontend skills as you can add high-quality pictures of food alongside the recipe of that food provided by this API.

    The free plan can’t be used commercially however it provides a comprehensive set of features such as Natural Language Processing support and 200 recipes per month.

    You can find the full details regarding different plans offered here.

    The users can simply type the ingredients and get the nutritional analysis which can help them eat smarter and better.

    You can check this cool feature here in the demo of this API.

    They have other APIs as well which can be used in conjunction with the rest to create a one-stop food app.

    They have added a new diet filter specifically geared towards the ongoing pandemic which leverages scientific publications about nutrients and foods to enhance immunity.

    Final Thoughts

    APIs are vital tools in the success of any app.

    Using third-party, public API allows developers to focus on things that matter while conveniently adding robust functionality to their app through these APIs.

    However, using the same API as everybody else not only creates unnecessary competition but also doesn’t provide any real value.

    Leveraging unique and flexible APIs can lead to the creation of some incredibly beautiful projects that you can showcase in your professional portfolio.

  • Laravel: Adding those missing helpers you always wanted

    One of the things I like from any PHP project is having global helpers. You know, those functions you can call anywhere and remove or save you many lines or verbosity into one, maybe two, while allocating in one place any logic.

    $expected = from($this)->do('foo');

    The problem with Laravel itself is that sometimes is not enough with the helpers it includes. The ones included are mostly quick access to Services (like cache()) or Factories (like response()), and some that help you having an expected result (like data_get).

    For example, let’s say we want a function be called multiple times but sleep between executions, like we would need to avoid rate limiting for an external API. Without a helper, we will have to resort to create a Class and put the logic inside a public static method, and hopefully remember where it is located.

    class Logics
    {
    public static function logic_sleep($times, $sleep, $callback)
    {
    // Run and sleep between calls.
    }
    }Logics::sleep(4, 10, function() {
    // ...
    });

    Using this technique makes your global not so globally. Since this is one of many thing I need in my projects, I decided to create a package with more global helpers:

    Larahelp

    Those helpers you always wanted

    The main idea of a global helper, at least to me, is to have a piece of code that offers simplicityreadability and flexibility. Think about them as small swiss knives that you may put in your pocket.

    For example, the above can become its own global function, and we can call it literally anywhere.

    public function handle()
    {
    logic_sleep(10, 5, function () {
    $this->uploadRecords();
    });
    }

    The helper is very simple to operate, but we won’t know what the hell it does behind the scenes unless we dig into the source code, which is fair. In any case, having a global function of one or two words makes the whole code more readable. And since it’s our own helper, we can call it anything we want.

    How to add your own helpers

    But that’s is only one of the many helpers I decided to create for things I use a lot.

    To add global helpers to your project, you can simply add a PHP file with the global functions you want anywhere in your project (preferably inside your PSR-4 root folder) and tell Composer to load it.

    You are free to add how many files you want. I decided to separate them into categories like I did for my package to avoid having a wall of text full of functions.

    "autoload": {
    "psr-4": {
    "App\\": "app"
    },
    "files": [
    "app/Helpers/datetime.php",
    "app/Helpers/filesystem.php",
    "app/Helpers/http.php",
    "app/Helpers/objects.php",
    "app/Helpers/services.php"
    ]
    },

    I’m opened to suggestions too, so give it a go if you think it may be useful for you:

    DarkGhostHunter/Larahelp

    Supercharge your Laravel projects with more than 35 useful global helpers.

    github.com

  • Laravel localization and multi-language functionality in web

    Laravel localization and multi-language functionality in web

    MAKE USE OF LARAVEL FEATURES AND BEST PACKAGES FOR LOCALIZATION

    Laravel localization and multi-language functionality in web

    A step by step guide to implement multi-language functionality in your web projects

    Laravel made it so easy to implement a multi-language website. You can implement it with Laravel localization and just some tricks. Also, there is plenty of Laravel translation packages which you can use in your project. In this post, I will explain how to implement multi-language functionality.

    Creating a multi-language website requires two steps. Firstly, you need to detect user local language setting and change it bu user choice. Secondly, you need to translate messages and strings into user local language, in which we use Laravel localization.

    DETECTING AND SETTING USER LOCALE

    In order to detect user language setting, we need to create a language middleware. this middleware checks for locale setting in the user session. If there was no locale setting, the middleware sets a default locale setting. Then, it sets system locale by the user session setting.

    if (is_null(session('locale'))) {
        session(['locale'=> "en"]);
    }
    app()->setLocale(session('locale'));

    Setting locale is enough for Laravel localization to work. After that, we need a simple function To change the system language. This function gets a locale string and sets the user locale session.

    public function change_lang($lang) {
        if (in_array($lang,['en','tr','fa'])) {
            session(['locale'=> $lang]);
        }
        return back();
    }

    In order to make sure the given string is a locale string, we check the language string against an array of locales.

    Any route to that function, like a drop down to select language will work perfectly and will show your website multi-language functionality for users. So they can easily choose their languages.

    Using Laravel localization to translate strings

    Every string that needed to be translated must be in Laravel lang directive or __ function. For example, you can manage all message strings with inside messages.

    @lang('messages.successful_login')

    In addition, you can find more useful information about localization like how to put variables inside translation strings in Laravel documentation.

    Laravel Langman package is one of the useful packages for translation. In order to translate strings, every time you updated views with new strings, you just need to run Langman sync command:
    php artisan langman:sync

    Laravel Langman has a lot more commands that would help you in your Laravel project localization. Reading through its documentation will add a lot.

    Although this method is easy and enough, I realized that for SEO purposes and to share localized links to your website, you better consider concatenating user locale in your projects routes. Then, you can check user locale from the query string and the rest is just as same as I explained in this post.

    Keep in touch and share your ideas about Laravel localization and how you implement multi-language functionality in your web projects. What other methods and Laravel packages do you use in your multi-language projects?

    Also, you can read my other post about Laravel authorization and user’s permission management in Laravel.

    If you find this multi-language functionality method useful in Laravel and you may want to implement this on your Laravel projects, share your ideas with me. Follow me on Twitter, Let’s connect on LinkedIn and give me a visit to amiryousefi.com

  • Laravel authorization and roles permission management

    EASY AND FLEXIBLE USERS PERMISSIONS MANAGEMENT

    Laravel authorization and roles permission management

    a simple guide for a flexible authentication and authorization

    Inmany web projects, we have different user roles interacting with the system. Each role has its own permission. Every feature of the system can be enabled or disabled for these roles. We can define users permissions in our codes and check if they are authorized to do the requested action or not. A better way, mostly in more flexible systems, is to create a role and authorization management system. I’ll explain how to implement a Laravel authorization system and define users permission based on their roles.

    In this post, firstly we manage users in groups we called roles. Every role has different permissions. In order to avoid permissions conflict, we assume each user has only one role. Secondly, Laravel authorization implemented by middleware. This middleware checks for the user’s role permission and authorizes user requests.

    CREATING ROLES AND PERMISSIONS

    In order to implement Laravel authorization, we will create roles and permissions table. To assign a role for users, we create a roles table. The migration for roles table is as simple as this:

    Schema::create(‘roles’, function (Blueprint $table) {
        $table->increments(‘id’);
        $table->string(‘name’);
        $table->string(‘description’)->nullable();
        $table->timestamps();
    });

    We have an ID and name for roles. All users will be managed in these roles. There is also a description field, because you may need a short note on roles to describe each role for yourself.

    After that, we add a foreign key, role_id, in the user table. Adding this field to the default user model helps us for Laravel authorization.

    $table->unsignedInteger(‘role_id’)->index();
    $table->foreign(‘role_id’)->references(‘id’)->on(‘roles’);

    Now let’s talk about the permissions table. Every request leads to a method of a controller. So we store a list of all methods and their controller’s name in the permissions table. Later, we explain how we gather this list and how we check users authorization in Laravel by this permissions table.

    Schema::create(‘permissions’, function (Blueprint $table) {
        $table->increments(‘id’);
        $table->string(‘name’)->nullable();
        $table->string(‘key’)->nullable();
        $table->string(‘controller’);
        $table->string(‘method’);
        $table->timestamps();
    });

    Finally, a relationship created between roles and permission.

    Schema::create(‘permission_role’, function (Blueprint $table) {
        $table->unsignedInteger(‘permission_id’);
        $table->unsignedInteger(‘role_id’);$table->foreign(‘permission_id’)
            ->references(‘id’)
            ->on(‘permissions’)
            ->onDelete(‘cascade’);$table->foreign(‘role_id’)
            ->references(‘id’)
            ->on(‘roles’)
            ->onDelete(‘cascade’);$table->primary([‘permission_id’, ‘role_id’]);
    });

    We created a complete users->roles->permissions architecture. After that, an access list will be stored in these tables. So, we can easily implement Laravel authorization by checking requests against this list.

    Read Laravel migration documentation for further information about creating tables.

    CREATING AN ACCESS LIST FOR USER PERMISSIONS

    The whole purpose of this post is about being dynamic. Especially, in systems with a different type of roles. We need to create a list of permissions in the system. Also, this list must be updated as the system developed. List of controllers and methods is a good representation of all permissions in the system. Every route is leading to a method of a controller. So, it’s a good idea to make a list of permissions using the routes list.

    In order to do that, I used a Laravel database seeder. Firstly, let’s write a role seeder. It creates basic roles we need and stores them in the roles table. Running this artisan command will create RolesSeeder for you:

    php artisan make:seeder RolesTableSeeder

    Inside this RolesTableSeeder, we create our basic roles:

    DB::table(‘roles’)->insert([
        [‘name’ => ‘admin’],
        [‘name’ => ‘operator’],
        [‘name’ => ‘customer’],
    ]);

    You can add as many roles as you need. Also, you can create new roles from your website whenever you need a new one.

    The second step is to create an authorization list for each role. we create another Laravel seeder in which populate permissions table:

    php artisan make:seeder PermissionTableSeeder

    Firstly, we get all routes list. Then, We check up with the database if the permission already stored. After that, if this permission is not in the table already, we insert new permissions in the permissions table. After all, we attach all permissions to the admin role.

    $permission_ids = []; // an empty array of stored permission IDs
    // iterate though all routes
    foreach (Route::getRoutes()->getRoutes() as $key => $route) {
        // get route action
        $action = $route->getActionname(); // separating controller and method
        $_action = explode(‘@’, $action);
    
        $controller = $_action[0];
        $method = end($_action);
    
        // check if this permission is already exists
        $permission_check = Permission::where(
            [‘controller’ => $controller, ’method’ => $method]
        )->first();
        if (!$permission_check) {
            $permission = new Permission;
            $permission->controller = $controller;
            $permission->method = $method;
            $permission->save();
    
            // add stored permission id in array
            $permission_ids[] = $permission->id;
        }
    } // find admin role.
    $admin_role = Role::where(‘name’, ’admin’)->first(); // atache all permissions to admin role
    $admin_role->permissions()->attach($permission_ids);

    LARAVEL AUTHORIZATION USING MIDDLEWARE

    Every request in Laravel goes through middleware. Knowing that creating RolesAuth middleware will do Laravel authorization. You can create the middleware manually or by an artisan command:

    php artisan make:middleware RolesAuth

    Inside this middleware, we get all permissions for logged in user. Then, we check if the requested action is in the permissions list. If requested action can’t be found in permissions list, a 403 error response returns.

    // get user role permissions
    $role = Role::findOrFail(auth()->user()->role_id);
    $permissions = $role->permissions; // get requested action
    $actionName = class_basename($request->route()->getActionname()); // check if requested action is in permissions list
    foreach ($permissions as $permission) {
        $_namespaces_chunks = explode(‘\’, $permission->controller);
        $controller = end($_namespaces_chunks);
        if ($actionName == $controller . ‘@’ . $permission->method) {
            // authorized request
            return $next($request);
        }
    } // none authorized request
    return response(‘Unauthorized Action’, 403);

    Finally, you can register this middleware in Laravel and use it according to your requirements.

    I started publishing my experience about Laravel development, here you can see my post about Laravel localization. Comment your questions about this post or any other Laravel development questions in this area.

    Update 2020:
    Now you can use my Laravel permission package build based this article. It just got better, cleaner, and easier to understand.
    https://github.com/amiryousefi/laravel-permission