<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Sydney Kibanga on Medium]]></title>
        <description><![CDATA[Stories by Sydney Kibanga on Medium]]></description>
        <link>https://medium.com/@sydneykb38?source=rss-981ab579d610------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*P2yFkW3RVt78bw7p</url>
            <title>Stories by Sydney Kibanga on Medium</title>
            <link>https://medium.com/@sydneykb38?source=rss-981ab579d610------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 08:45:08 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sydneykb38/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[How to use Cron Jobs with Laravel]]></title>
            <link>https://medium.com/@sydneykb38/how-to-use-cron-jobs-with-laravel-ae4804053300?source=rss-981ab579d610------2</link>
            <guid isPermaLink="false">https://medium.com/p/ae4804053300</guid>
            <dc:creator><![CDATA[Sydney Kibanga]]></dc:creator>
            <pubDate>Wed, 07 Sep 2022 07:18:35 GMT</pubDate>
            <atom:updated>2022-09-07T07:18:35.361Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to use Cron Jobs with Laravel?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/283/1*PqJ-jKrzD6hPeOEehKJ85w.png" /></figure><p><strong>What is Cronjob :</strong></p><p>A Cronjob is Unix command for scheduling jobs to be executed in specific time and specific interval. For example we can schedule a task in the server that executes some scripts that sends out daily/weekly reports from our website. Mainly we are using the cron jobs to cleanup the databases, send the emails , execute time consuming tasks ….etc. If i want to delete some files from my database which is older than a month, I can simply do that using Cron Job. Cron job will not work with with windows based machines or servers as it will only work on unix based machines.</p><p>Cron has a configuration file called Crontable also known as Crontab which is used to manage the scheduling.These crontab consists of different Cronjobs and each CronJob is associated with a specific task. Cron Job mainly consists of two parts, a Cron expression and a shell command to be run.</p><p>The format of the Cron Scheduler is like this</p><ul><li>* * * * command/to /run</li><li>ie, minute, hour, day, month, day of the weak in the place of * in the same order.</li></ul><p>where :</p><ul><li>Minute (0–59)</li><li>Hour (0–23)</li><li>Day of month (1–31)</li><li>Month (1–12)</li><li>Day of the week (0–6 starting on Sunday-0)</li></ul><p>When any entity is replaced with asterisk then the CronJob have to perform for each minute or day or weak or month or day of the weak according to where asterisk is placed.</p><p><strong>CronJob Samples :</strong></p><ul><li>Every hour on the 5th minute of the hour.</li></ul><p>5 * * * * command-to — run</p><ul><li>Every hour on the 5th minute of the hour on mondays only.</li></ul><p>5 * * * 1 command-to- run</p><ul><li>You can also run the cron job at an interval of time, let’s say every 10 minutes. For that you need to give this format (asterisk divide by number):</li></ul><p>*/10 * * * * command- to — run</p><p><strong>Task Scheduling in laravel:</strong></p><p>Normally for scheduling tasks/ cronjobs you must SSH into your server to add the Cron entries. The command scheduler feature in Laravel allows you to easily and expressively define your command schedule within Laravel itself, and only a single Cron entry is needed on your server for running the laravel task scheduler in each minute.</p><p>Laravel’s task schedule is defined in the schedule method inside the</p><p>app/Console/Kernel.php file. We can define as much as tasks inside this method. Following is the only Cron entry you need to add to your server, which will call the Laravel command scheduler every minute.</p><pre>* * * * * php /path/to/artisan schedule:run &gt;&gt; /dev/null 2&gt;&amp;1</pre><p>This cronjob will initiate laravel task scheduler to run the tasks inside the schedule method.</p><p><strong>Command Scheduling in Laravel :</strong></p><p>To schedule the commands we use the Laravel task scheduler.The tasks were defined inside the schedule method of the kernel class. By using the command method we can add as many artisan commands we want. By using the schedule method we can schedule all the commands. There are different schedule frequencies we can apply on the commands according to the need. Some examples are listed here below.</p><p>— If one task is supposed to run once a day , then we can use the daily() method.</p><pre>Protected function schedule(Schedule $schedule)<br>{<br>$schedule-&gt;command(‘sms:gudmorning’)-&gt;daily();<br>}<br> --    If we want to run task every hour every day.<br>$schedule-&gt;command(‘Task’)<br>-&gt;hourly();</pre><p>— If we want to run task every day at 10.30.</p><pre>$schedule-&gt;command(‘Task’)<br>-&gt;dailyAt(‘10.30’);</pre><p>— If we want to run a task every week.</p><pre>$schedule-&gt;command(‘Task’)<br>-&gt;weekly( );</pre><p>— If we want to run it every month.</p><pre>$schedule-&gt;command(‘Task’)<br>-&gt;monthly( );</pre><p>— It also provides some schedule constraints. If we want we can combine the above methods to perform some action.</p><pre>$schedule-&gt;command(‘Task’)<br>-&gt;weekly( );<br>-&gt;mondays();<br>-&gt;at(10.30);</pre><p><strong>Scheduling Closure calls :</strong></p><p>If we want to schedule a Closure to be called every day at midnight and within the Closure we will execute a database query to clear a table</p><pre>protected function schedule(Schedule $schedule)<br>   {<br>       $schedule-&gt;call(function () {<br>           DB::table(&#39;recent_users&#39;)-&gt;delete();<br>       })-&gt;daily();<br>   }</pre><p><strong>Scheduling exec commands :</strong></p><p>we can use the exec command to issue a command to the operating system.</p><pre>$schedule-&gt;exec(&#39;node /home/forge/script.js&#39;)-&gt;daily();</pre><p><strong>Schedule Options available in Laravel :</strong></p><p>The different type of schedules we can assign to our tasks are,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/641/1*p6Tc17HQWe08hVAAWjARcw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/641/1*ntnhBs4BqIIOSTQe7JwGlw.png" /></figure><p><strong>Conclusion:</strong></p><p>Laravel Task scheduler made the cronjob setup easier without SSH into your server to add the Cron entries. The Laravel command scheduler helps us to expressively define the command schedule within Laravel and only a single Cron entry is needed on your server.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ae4804053300" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Redis and Memcached in Caching]]></title>
            <link>https://medium.com/@sydneykb38/redis-and-memcached-in-caching-f93fc905378e?source=rss-981ab579d610------2</link>
            <guid isPermaLink="false">https://medium.com/p/f93fc905378e</guid>
            <dc:creator><![CDATA[Sydney Kibanga]]></dc:creator>
            <pubDate>Mon, 05 Sep 2022 06:50:02 GMT</pubDate>
            <atom:updated>2022-09-05T06:50:02.830Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/279/1*l7TM4EcyHdDSQN_N2Wo5Bg.jpeg" /></figure><h3>Caching</h3><p>The cache is temporary storage where data is stored so that in the future data can be accessed faster. So, caching is the process of storing data in Cache. Redis and memcached are good choices for implementing a highly available in-memory cache to decrease data access latency with disk or SSD, high throughput and ease the load of the database and application. Web page caching, Database query results caching, persistent session caching and caching of frequently used objects such as images, files, and metadata are popular examples of caching solutions with Redis.</p><h3>Redis Overview.</h3><p>Redis is a fast in-memory database and cache, open source under a BSD license, written in C and optimized for speed. Redis’ name comes from “<strong>RE</strong>mote <strong>DI</strong>ctionary <strong>S</strong>erver”.</p><p>Redis is often called a data structure server because its core data types are similar to those found in programming languages like strings, lists, dictionaries (or hashes), sets, and sorted sets. It also provides many other data structures and features for approximate counting, geolocation, and stream processing.</p><p>Of the NoSQL databases Redis’ various data structures take it closest to the native data structures programmers most commonly use inside applications and algorithms. This ease of use makes it ideal for rapid development and fast applications, as core data structures are easily shared between processes and services.</p><p>By default Redis stores data in memory, with periodic disk persistence as a default. As Redis persists data to disk it can serve as a classical database for many use cases as well as a cache. When full, Redis will return an error to a client, but it can be configured as a cache to eject older and less important data as new data comes in. In both cases the size of available memory is the main constraint on its use.</p><h3>Memcached Overview.</h3><p>memcached is a high performance, distributed memory object caching system. It is an in-memory key-value store for small chunks of arbitrary data (strings, objects) from results of database or API calls. Items are made up of a key, expiration time, optional flags and raw data. It does not understand data structures: you must upload data that is pre-serialized.</p><p>memcached is made up of:</p><ul><li>client software, which is given a list of available memcached servers</li><li>a client-based hashing algorithm, which chooses the server based on the key</li><li>server software, which stores keys and values into an internal hash table. Servers are unaware of each other; there is no synchronization</li><li>server algorithms, which determine when to expire and evict old data</li></ul><p>Most applications benefits from caching, unless the application is very write heavy (thus the cache is invalidated all the time).</p><h3>Benefits of Redis</h3><ol><li><strong>Redis allows storing key and value pairs as large as 512 MB</strong>. You can have huge keys and values of objects as big as 512 MB, which means that Redis will support up to 1GB of data for a single entry.</li><li><strong>Redis uses its own hashing mechanism called Redis Hashing</strong>. Redis stores data in the form of a key and a map, i.e. string fields and string values.</li><li><strong><em>Redis offers data replication</em></strong>. Replication is the process of setting up master-slave cache nodes. The slave nodes always listen to the master node, which means that when the master node is updated, slaves will automatically be updated, as well. Redis can also update slaves asynchronously.</li><li><strong><em>The Redis cache can withstand failures and provide uninterrupted service</em></strong><em>. </em>Since Redis can be used to set up efficient replication, at any point in time, the cache service will be up-and-running — even if any of the slave nodes are down. However, the nodes are resilient and will overcome the failure and continue providing service.</li><li><strong><em>Redis has clients in all the popular programming languages</em></strong>. Redis has client APIs developed in all the popular languages such as C, Ruby, Java, JavaScript, and Python. A full list of languages that Redis supports can be found on the <a href="https://en.wikipedia.org/wiki/Redis">Redis Wikipedia page</a>.</li><li><strong><em>Redis offers a pub/sub messaging system</em></strong><em>. </em>You can develop a high-performing messaging application using the Redis pub/sub mechanism using any language of your choice.</li><li><strong><em>Redis allows inserting huge amounts of data into its cache very easily</em></strong><em>. </em>Sometimes, it is required to load millions of pieces of data into the cache within a short period of time. This can be done easily using mass insertion, a feature supported by Redis.</li><li><strong><em>Redis can be installed in Raspberry Pi and ARM devices</em></strong><em>. </em>Redis has a small memory footprint and it can be installed in Raspberry Pi to enable IoT-based applications.</li><li><strong>Redis protocol makes it simple to implement a client</strong>. A<em> </em>Redis client communicates with its server using RESP (Redis Serialization Protocol). This protocol is simple to implement and is human-readable.</li><li><strong><em>Redis support transactions</em></strong><em>. </em>Redis supports transactions, which means that commands can be executed as a queue instead of executing one at a time. Typically, commands after MULTI will be added to a queue and once EXEC is issued, all the commands saved in the queue will be executed at once.</li></ol><h3>Benefits of Memcached</h3><ol><li>Extremely fast response times thanks to the in-memory key-value store</li><li>Multi-thread architecture enables vertical scaling of computing capacity</li><li>Sophisticated open-source solution with a publicly available datastore</li><li>Easy to use and flexible in terms of application development</li><li>Supports open data formats and most common clients and programming languages</li></ol><h3>What Is Different About Redis and Memcached?</h3><p>There are a number of key differences between Redis and Memcached which need to be mentioned. These differences are very specific around how Redis and Memcached handle the data they are caching, and how they are able to deal with it at scale.</p><h3>Data Types:</h3><p>When storing data, Redis stores data as <a href="https://redis.io/topics/data-types"><strong>specific data types</strong></a>, whereas Memcached only stores data as strings. Because of this, Redis can change data in place without having to re-upload the entire data value. This reduces network overhead. Below I cover the different types of data that Redis can handle.</p><h3>String</h3><p>Strings are a basic value to store data. Redis strings are binary safe, which means that strings can store something like a small image. String values can be up to 512MB in length.</p><h3>List</h3><p>Redis Lists are a way to store unordered data, which can then be accessed by index. Redis implements what is known as a <em>Linked List </em>which is a slightly different way of implementing lists than an <em>Array. </em>What this means is that Redis is extremely fast and consistent when adding or removing a value from the start or end of a list.</p><h3>Hash</h3><p>Hashes, or dictionaries as they are known in some languages, allow for the storage of tightly related data in a series of fields with their own key value relationships. Although it is very similar to common data structures in programming languages it is important to note there isn’t always a 1:1 mapping as Redis’ version is fairly “flat” (e.g. a Python dictionary can be nested and hold different types of objects and cannot be stored into a Redis Hash easily if it has these properties).</p><h3>Set</h3><p>Sets are unordered collections of unique items. Sets can add, remove, and test for the existence of members. The benefit of a set over a list is that a set does not allow duplicates, meaning that for data where you are just storing a unique key, if it does not exist, you can just add the key and know that it will be unique within the set.</p><h3>Sorted Set</h3><p>Sorted sets are an expansion of the Redis set, where they are a collection of unique strings. However each member of the Redis sorted set is given a score to help order the set. Sorted sets also allow for accessing ranges based on the score given by Redis.</p><h3>Persistence:</h3><p>Redis allows for <a href="https://redis.io/topics/persistence"><strong><em>persistence to disk</em></strong></a>, meaning that the data in Redis’ database can be stored and recovered in the event of the Redis server crashing or being rebooted. Whilst memory is fantastic for speed, it does have the caveat that if the server goes down, the data on the memory is lost. Redis’ persistence is not 100% data safe, depending on the type of persistence used there may be between a few seconds and several minutes of changed data, but the persistence is better than none at all. Memcached does not have the ability to persist to disk natively. Instaclustr enables persistence as default, ensuring that even a new cluster can recover from an outage, with nodes restarting with a “warm cache”. There are two different ways to persist data in Redis:</p><h3>Data Length:</h3><p>Redis data keys and strings can be up to <a href="https://redis.io/topics/data-types-intro#:~:text=The%20maximum%20allowed%20key%20size%20is%20512%20MB."><strong>512 MB (megabytes) in length</strong></a> although strings of this size are generally not recommended for performance reasons. As they are binary safe, you can also store any kind of data, even a JPEG image. Memcached supports a key of only 250 bytes and values are capped at 1MB by default (but this can be increased by changing settings). If you have larger data objects, Redis can be a better choice than trying to work around these limits.</p><h3>Data Eviction Policies:</h3><p>As memory is finite on servers, stale data in a cache must be automatically ‘evicted’ from the memory to make way for new data. This is handled through a process called data eviction. Both Redis and Memcached have ways of handling this, however they aren’t always the same. A common way to evict data is called<em> Least Recently Used</em> — evicting the data that hasn’t been hit recently. If the data is hit, it is noted, meaning it won’t be a candidate for eviction. This is the <a href="https://memcached.org/blog/modern-lru/"><strong>only way that Memcached works</strong></a>. However, <a href="https://docs.redislabs.com/latest/rs/administering/database-operations/eviction-policy/"><strong>Redis offers a number of other ways</strong></a> to deal with data eviction, such as <em>No Eviction</em> where Redis just lets the memory fill up and then not take any more keys, and Volatile TTL (<em>Time to Live</em>), where Redis will attempt to remove keys with a set TTL first, in an attempt to preserve data not annotated with a TTL that was meant to persist for longer.</p><h3>Replication:</h3><p>Replication is a way in which to copy data from one instance to another creating a <em>Replica</em>. The intention is to ensure a duplicate copy of data is kept within another instance, in the event the master instance experiences an outage. <a href="https://redis.io/topics/replication"><strong>Redis supports replication natively</strong></a> and is able to replicate in a master to follower fashion. Redis instances can also have more than one replica for added redundancy. Memcached does not support replication without third party software.</p><h3>Clustering:</h3><p>Clustering is a way of ensuring high availability of a service by creating a number of instances and connecting them together to form a <em>cluster</em>. Creating clusters can sometimes be difficult to set up and manage when the software is not designed for it. As a solution for <a href="https://www.instaclustr.com/redis-java-clients-and-client-side-caching/"><strong>scalable caching</strong></a>, Redis offers Redis Cluster, which enables clustering features for Redis.</p><p>There are many <a href="https://info.instaclustr.com/the-advantages-of-redis-as-an-in-memory-database-for-low-latency-applications.html"><strong>benefits to using Redis</strong></a> in a cluster rather than just as a standalone instance:</p><h3>Performance</h3><p>Redis will experience improved performance as load from clients are spread across multiple clusters. Cluster aware drivers understand which node the data is on and connect directly do that node.</p><h3>Availability</h3><p>Using a combination of replication along with clustering allows for high availability for applications. Redis Cluster can be set up with a selection of master instances, and connected replicas. If a single master goes offline in the cluster, it can failover, and the replica will be automatically promoted to master in the cluster. When the failed instance comes online again, it will automatically sync as the replica for the new master. Replicas can be kept in separate racks for redundancy.</p><h3>Pricing and Scalability</h3><p>As Redis is memory intensive, clustering allows for horizontal scalability, where load is spread over multiple instances with smaller memory footprints, rather than a single instance with a lot of memory. In a traditional server application instance, to get better performance from the application, you could increase the system resources via vertical scaling. At some point though the system will be limited by either availability of technology to increase the size of the server or, the more likely scenario, it is no longer cost effective to increase the machine resources. The main alternative to this is called horizontal scaling, where servers with smaller resources are grouped together in a cluster. The cluster will have the same or better performance as vertical scaling at a smaller cost. Horizontal scaling can be particularly important for Redis, as memory is very expensive as the size increases.</p><h3>Multithreading:</h3><p>Memcached formerly had the advantage over Redis in multithreading speed. This meant that in certain situations, Memcached could outperform Redis. However, as of Redis 6, multithreading is supported in Redis and because of this should see an improvement in multithreaded workloads.</p><p><strong>Memcached vs Redis — Features Compared:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/0*rB8iEn9Shgokg_ot.jpg" /></figure><h3>When to Use Memcached:</h3><p>Memcached is, by design, very simple to set up and use. If you had an extremely simple application on only a few servers, and only required simple string interpretation for your application, then Memcached may be the correct choice for you. However, even with small workloads, it may be worth the little extra effort to set up Redis, as it has the option for expandability later on.</p><h3>When to Use Redis:</h3><p>Redis is a very well rounded, mature product, with active ongoing development. It has a bunch of features and really gives the option for expandability into the future. You should be using Redis when:</p><ul><li>You need access to a wider set of data structures and stream processing capability.</li><li>The ability to modify and change keys and values in place is required.</li><li>Custom data eviction policies are required (for example, needing to keep keys with a longer Time to Live, even if the system is out of memory).</li><li>You need to persist your data to disk for backups and warm restarts.</li><li>You need to have high availability or scalability of your application, through the use of replicas and clustering.</li></ul><h3>Conclusion:</h3><p>Memcached was one of the first popular open source memory caching solutions and works well for basic key value workloads. However, if you are working in the enterprise, or are just looking for a more modern, feature rich and actively developed product, Redis is the best solution.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f93fc905378e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Testing Laravel APIs Using PHPUnit]]></title>
            <link>https://medium.com/@sydneykb38/testing-laravel-apis-using-phpunit-7370a7bf3e91?source=rss-981ab579d610------2</link>
            <guid isPermaLink="false">https://medium.com/p/7370a7bf3e91</guid>
            <dc:creator><![CDATA[Sydney Kibanga]]></dc:creator>
            <pubDate>Fri, 26 Aug 2022 06:09:02 GMT</pubDate>
            <atom:updated>2022-09-12T06:02:47.129Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/512/0*eXRm-BJF3B1DWPyB.png" /></figure><p>As a software engineer who is considering taking development a little step further (and you should be doing that), test-driven development, often referred to as TDD, is one of the best practices you can add to your arsenal. To expressively test your applications, Laravel comes installed with <a href="https://phpunit.de/">PHPUnit</a>, a testing framework for PHP. It contains convenient helper methods useful for creating and running test scripts specifically written for different units within your application.</p><h3>Importance of Testing</h3><h4>a. Helps in saving money</h4><p>The testing of software has a wide array of benefits. The <strong>cost-effectiveness</strong> of the project happens to be one of the top reasons why companies go for <a href="https://www.indiumsoftware.com/software-testing-services/"><strong>software testing Services</strong></a>.</p><p>The testing of software comprises of a bunch of projects. In case you find any bug in the early phases, fixing them costs a reduced amount of money.Hence, it is a prerequisite that you should get the testing done in no time. As you hire <strong>quality analysts or testers</strong> who have an ample amount of experience and have gone through technical education for the projects, they are the investments and the project is going to reap the benefits.</p><h4>b. Security</h4><p>It is another crucial point why <strong>software testing</strong> should be taken into consideration.</p><p>It is considered to be the most <strong>vulnerable</strong> and sensitive part. There are a bunch of situations in which the information and details of the users are stolen and they are used for the benefits.</p><p>It is considered to be the reason why people look for the well tested and reliable products.</p><p>As a specific product undergoes testing, the user can be ensured that they are going to receive a reliable product. The personal details of the user can be safe. Users can receive products that are free from <strong>vulnerability</strong> with the aid of software testing.</p><h4>c.Quality of the product</h4><p>For ensuring that the specific product comes to life, it should work in accordance with the following.</p><p>Following the needs of the product is a prerequisite as it is helpful in getting the prerequisite results.</p><p>Products should be serving the user in one way or the other. It is a must that it is going to bring the value, as per the promise.</p><p>Hence, it should function in a complete manner for ensuring an effective customer experience. It is also necessary to check the <strong>compatibility</strong> of the device.</p><p>For instance, in case, you are planning to launch an application, it is a must to check the compatibility of the same in a wide array of <strong>operating systems</strong> and <strong>devices</strong>.</p><h4>d. Satisfaction of the customer</h4><p>The primary objective of the owner of the products is offering the best satisfaction of the customers.</p><p>The reasons why it is necessary to opt for <strong>software testing</strong> is due to the fact that it offers the prerequisite and perfect user experience.</p><p>As you opt for the best project in the saturated project, you will be capable of earning the reputation of reliable clients.</p><p>Thus, you are going to reap long-term benefits by opting for <strong>software testing</strong>. Earning the trust of the client is certainly not an easy task, primarily in case the product is found to be functioning and glitching every time or the other.</p><p>You yourself have used a lot of products and you surely had several horrible experiences owing to which you might have deleted the application.</p><p>The market is really saturated in the present days.</p><p>The first impression is really important and if you fail to give the same, users are going to find another product which will accomplish all the requirements.</p><h4>e. Enhancing the development process</h4><p>With the aid of <strong>Quality Assurance</strong>, you can find a wide array of scenarios and errors, for the reproduction of the error.</p><p>It is really simple and the developers need to fix the same in no time. In addition to this, <strong>software testers</strong> should be working with the development team parallelly, which is useful in the acceleration of the development procedure.</p><h4>f. Easy while adding new features</h4><p>The more interconnected and older the code, the more difficult it is to change. Tests counteract this calcification tendency by allowing developers to confidently add new features. As a new developer, changing older parts of your codebase can be terrifying, but with tests, you’ll at least know if you’ve broken anything important. This helps in making your software stand ahead in the market, and beat the competition.</p><h4>g. Determining the performance of the software</h4><p>If you find software or application that has low or reduced performance, you will find that it brings your reputation down in the market.</p><p>Users are not going to trust any people. There are chances that the reputation of your organization is going to suffer.</p><p>In accordance with the experts, it is not that important. However, in case, you introduce any software in the market without <strong>software testing</strong> and after this, the performance of the software does not meet the expectation or requirements of the clients, convincing people will be a hassle.</p><h3>1.setting up laravel</h3><ul><li>Create a laravel project by running the following command on your terminal.</li></ul><pre>composer create-project laravel/laravel myApp</pre><ul><li>Move into the project directory by running the following command on your terminal.</li></ul><pre>cd myApp</pre><ul><li>Next supply your database credentials in your <strong>.env</strong> file and create a database for use with your application.</li></ul><pre>DB_CONNECTION=mysql<br>DB_HOST=127.0.0.1<br>DB_PORT=3306<br>DB_DATABASE=db_name<br>DB_USERNAME=root<br>DB_PASSWORD=</pre><h3>2.Create model and migration for product</h3><pre>php artisan make:model Product -m</pre><p>In this step, we will create a <strong>Laravel test model</strong>. The above command will create the model App/Models/Product.php and migration file database\migrations\2021_07_18_113413_create_products_table.php</p><p><strong>Update Model </strong>App/Models/Product.php</p><pre>&lt;?php</pre><pre>namespace App\Models;</pre><pre>use Illuminate\Database\Eloquent\Factories\HasFactory;<br>use Illuminate\Database\Eloquent\Model;</pre><pre>class Product extends Model<br>{<br>    use HasFactory;</pre><pre>    protected $fillable = [&#39;name&#39;, &#39;price&#39;, &#39;desc&#39;];<br>}</pre><p>Now update the migration file: database\migrations\2021_07_18_113413_create_products_table.php</p><pre>&lt;?php</pre><pre>use Illuminate\Database\Migrations\Migration;<br>use Illuminate\Database\Schema\Blueprint;<br>use Illuminate\Support\Facades\Schema;</pre><pre>class CreateProductsTable extends Migration<br>{<br>    /**<br>     * Run the migrations.<br>     *<br>     * @return void<br>     */<br>    public function up()<br>    {<br>        Schema::create(&#39;products&#39;, function (Blueprint $table) {<br>            $table-&gt;id();<br>            $table-&gt;string(&#39;name&#39;);<br>            $table-&gt;string(&#39;price&#39;);<br>            $table-&gt;string(&#39;desc&#39;);<br>            $table-&gt;timestamps();<br>        });<br>    }</pre><pre>    /**<br>     * Reverse the migrations.<br>     *<br>     * @return void<br>     */<br>    public function down()<br>    {<br>        Schema::dropIfExists(&#39;products&#39;);<br>    }<br>}</pre><p>Now run the migration to migrate products table</p><pre>php artisan migrate</pre><p>This will create a table named “products” in the database.</p><h3>3.Creating the Product Controller</h3><pre>php artisan make:controller API/ProductController --api --model=Product</pre><p>The command above will generate an API resource controller that does not include the create and edit view since we are only building APIs</p><p>Open app/Http/Controllers/API/ProductController.php and update the code is given below:</p><pre>&lt;?php</pre><pre>namespace App\Http\Controllers\API;</pre><pre>use App\Http\Controllers\Controller;<br>use App\Models\Product;<br>use Illuminate\Http\Request;<br>use App\Http\Resources\ProductResource;<br>use Validator;</pre><pre>class ProductController extends Controller<br>{<br>    /**<br>     * Display a listing of the resource.<br>     *<br>     * @return \Illuminate\Http\Response<br>     */<br>    public function index()<br>    {<br>        $products = Product::all();<br>        return response([&#39;products&#39; =&gt;     ProductResource::collection($products)]);<br>    }</pre><pre>    /**<br>     * Store a newly created resource in storage.<br>     *<br>     * @param  \Illuminate\Http\Request  $request<br>     * @return \Illuminate\Http\Response<br>     */<br>    public function store(Request $request)<br>    {<br>        $data = $request-&gt;all();</pre><pre>        $validator = Validator::make($data, [<br>            &#39;name&#39; =&gt; &#39;required|max:255&#39;,<br>            &#39;price&#39; =&gt; &#39;required|max:255&#39;,<br>            &#39;desc&#39; =&gt; &#39;required|max:255&#39;,<br>        ]);</pre><pre>        if($validator-&gt;fails()){<br>            return response([&#39;error&#39; =&gt; $validator-&gt;errors(), &#39;Validation Error&#39;]);<br>        }</pre><pre>        $product = Product::create($data);</pre><pre>        return response([&#39;product&#39; =&gt; new ProductResource($product), &#39;message&#39; =&gt; &#39;Product created successfully&#39;]);<br>    }</pre><pre>    /**<br>     * Display the specified resource.<br>     *<br>     * @param  \App\Models\Product  $product<br>     * @return \Illuminate\Http\Response<br>     */<br>    public function show(Product $product)<br>    {<br>        return response([&#39;product&#39; =&gt; new ProductResource($product)]);<br>    }</pre><pre>    /**<br>     * Update the specified resource in storage.<br>     *<br>     * @param  \Illuminate\Http\Request  $request<br>     * @param  \App\Models\Product  $product<br>     * @return \Illuminate\Http\Response<br>     */<br>    public function update(Request $request, Product $product)<br>    {<br>        $data = $request-&gt;all();</pre><pre>        $validator = Validator::make($data, [<br>            &#39;name&#39; =&gt; &#39;required|max:255&#39;,<br>            &#39;price&#39; =&gt; &#39;required|max:255&#39;,<br>            &#39;desc&#39; =&gt; &#39;required|max:255&#39;,<br>        ]);</pre><pre>        if($validator-&gt;fails()){<br>            return response([&#39;error&#39; =&gt; $validator-&gt;errors(), &#39;Validation Error&#39;]);<br>        }</pre><pre>        $product-&gt;update($data);</pre><pre>        return response([&#39;product&#39; =&gt; new ProductResource($product), &#39;message&#39; =&gt; &#39;Product updated successfully&#39;]);<br>    }</pre><pre>    /**<br>     * Remove the specified resource from storage.<br>     *<br>     * @param  \App\Models\Product  $product<br>     * @return \Illuminate\Http\Response<br>     */<br>    public function destroy(Product $product)<br>    {<br>        $product-&gt;delete();</pre><pre>        return response([&#39;message&#39; =&gt; &#39;Product deleted successfully&#39;]);<br>    }<br>}</pre><h3>4. Create a Resource</h3><p>Laravel Eloquent resources allow you to convert your models and collections into JSON format. It works as a data transformation layer between the database and the controllers. This helps provide a uniform interface that can be used wherever you need it within your application. Let’s create one for the Product model by using the following command:</p><pre>php artisan make:resource ProductResource</pre><p>This will create a new resource file named ProductResource.php within the app/Http/Resources directory. Open this file and update the below code:</p><pre>&lt;?php</pre><pre>namespace App\Http\Resources;</pre><pre>use Illuminate\Http\Resources\Json\JsonResource;</pre><pre>class ProductResource extends JsonResource<br>{<br>    /**<br>     * Transform the resource into an array.<br>     *<br>     * @param  \Illuminate\Http\Request  $request<br>     * @return array<br>     */<br>    public function toArray($request)<br>    {<br>        return parent::toArray($request);<br>    }<br>}</pre><h3>5. Update Routes File</h3><p>To complete the set up of the endpoints for the methods created within our controllers, update the routes.api.php file with the following contents:</p><pre>&lt;?php</pre><pre>use Illuminate\Http\Request;<br>use Illuminate\Support\Facades\Route;<br>use App\Http\Controllers\API\ProductController;</pre><pre>/*<br>|--------------------------------------------------------------------------<br>| API Routes<br>|--------------------------------------------------------------------------<br>|<br>| Here is where you can register API routes for your application. These<br>| routes are loaded by the RouteServiceProvider within a group which<br>| is assigned the &quot;API&quot; middleware group. Enjoy building your API!<br>|<br>*/</pre><pre>Route::apiResource(&#39;/product&#39;, ProductController::class);</pre><p><strong>Run the Application</strong></p><pre>php artisan serve</pre><h3>6. Generate test classes for ProductTest</h3><pre>php artisan make:test ProductTest</pre><p>This will create the file under the tests/Feature directory; open this file update command below.</p><pre>&lt;?php</pre><pre>namespace Tests\Feature;</pre><pre>use Illuminate\Foundation\Testing\RefreshDatabase;<br>use Illuminate\Foundation\Testing\WithFaker;<br>use Tests\TestCase;<br>use App\Models\Product;<br>use App\Models\User;</pre><pre>class ProductTest extends TestCase<br>{</pre><pre>    /**<br>     * test create product.<br>     *<br>     * @return void<br>     */<br>    public function test_create_product()<br>    {<br>        <br>        $response = $this-&gt;json(&#39;POST&#39;,&#39;api/product&#39;,[<br>            &#39;name&#39; =&gt; &#39;Test product&#39;,<br>            &#39;price&#39; =&gt; &#39;1234&#39;,<br>            &#39;desc&#39; =&gt; &#39;test-desc&#39;<br>        ]);</pre><pre>       $response-&gt;assertStatus(200);<br>    }</pre><pre>    /**<br>     * test update product.<br>     *<br>     * @return void<br>     */<br>    public function test_update_product()<br>    {<br>        $response = $this-&gt;json(&#39;PUT&#39;,&#39;api/product/1&#39;,[<br>            &#39;name&#39; =&gt; &#39;Test product111&#39;,<br>            &#39;price&#39; =&gt; &#39;12345&#39;,<br>            &#39;desc&#39; =&gt; &#39;test-desc&#39;<br>        ]);</pre><pre>        $response-&gt;assertStatus(200);<br>    }</pre><pre>    /**<br>     * test find product.<br>     *<br>     * @return void<br>     */<br>    public function test_find_product()<br>    {<br>        $response = $this-&gt;json(&#39;GET&#39;,&#39;api/product/1&#39;);</pre><pre>        $response-&gt;assertStatus(200);<br>    }</pre><pre>    /**<br>     * test get all products.<br>     *<br>     * @return void<br>     */<br>    public function test_get_all_product()<br>    {<br>        $response = $this-&gt;json(&#39;GET&#39;,&#39;api/product&#39;);</pre><pre>        $response-&gt;assertStatus(200);<br>    }</pre><pre>    /**<br>     * test delete products.<br>     *<br>     * @return void<br>     */<br>    public function test_delete_product()<br>    { <br>        $response = $this-&gt;json(&#39;DELETE&#39;,&#39;api/product/1&#39;);</pre><pre>        $response-&gt;assertStatus(200);<br>    }<br>}</pre><p><strong>Test it into the terminal</strong></p><pre>php artisan test</pre><h3>Conclusion</h3><p>we’ve created a Laravel API and Testing with PHPUnit. To find out more about how to use laravel and phpunit, you can check out here <a href="https://laravel.com/docs/9.x/testing">https://laravel.com/docs/9.x/testing</a> .</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7370a7bf3e91" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[REST API Authentication and Access-control in Laravel using Passport]]></title>
            <link>https://medium.com/@sydneykb38/rest-api-authentication-and-access-control-in-laravel-using-passport-fd84fcd03ecd?source=rss-981ab579d610------2</link>
            <guid isPermaLink="false">https://medium.com/p/fd84fcd03ecd</guid>
            <dc:creator><![CDATA[Sydney Kibanga]]></dc:creator>
            <pubDate>Thu, 25 Aug 2022 09:16:13 GMT</pubDate>
            <atom:updated>2022-08-25T09:16:13.748Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3_7q354mTTlzbT_OMsDu9A.png" /></figure><p><strong>Introduction: </strong>Laravel is the fastest growing PHP framework and is used by thousands of developers around the globe to rapidly build robust web applications.</p><p>Laravel attempts to take the pain out of development by easing common tasks used in the majority of web projects, such as authentication, routing, sessions, and caching. Laravel aims to make the development process a pleasing one for the developer without sacrificing application functionality.</p><p><strong>What is Laravel Passport?</strong></p><p>Laravel Passport is an OAuth 2.0 server implementation for API authentication using Laravel. Since tokens are generally used in API authentication, Laravel Passport provides an easy and secure way to implement token authorization on an OAuth 2.0 server.</p><p><strong>Resources: </strong>The following resources were used in this tutorial.</p><ul><li>Laravel 9</li><li>Xampp server</li></ul><h3>1.setting up laravel</h3><ul><li>Create a laravel project by running the following command on your terminal.</li></ul><pre>composer create-project laravel/laravel myApp</pre><ul><li>Move into the project directory by running the following command on your terminal.</li></ul><pre>cd myApp</pre><ul><li>Next supply your database credentials in your <strong>.env</strong> file and create a database for use with your application.</li></ul><pre>DB_CONNECTION=mysql<br>DB_HOST=127.0.0.1<br>DB_PORT=3306<br>DB_DATABASE=db_name<br>DB_USERNAME=root<br>DB_PASSWORD=</pre><h3>2.setting up laravel-passport</h3><ul><li>To get started with Passport in laravel, via the terminal hit the following command on your terminal.</li></ul><pre>composer require laravel/passport</pre><ul><li>Passport’s <a href="https://laravel.com/docs/9.x/providers">service provider</a> registers its own database migration directory, so you should migrate your database after installing the package. The Passport migrations will create the tables your application needs to store OAuth2 clients and access tokens:</li></ul><pre>php artisan passport:install</pre><ul><li>After running the passport:install command, add the Laravel\Passport\HasApiTokens trait to your App\Models\User model. This trait will provide a few helper methods to your model which allow you to inspect the authenticated user&#39;s token and scopes. If your model is already using the Laravel\Sanctum\HasApiTokens trait, you may remove that trait:</li></ul><pre>&lt;?php<br>namespace App\Models;<br>use Illuminate\Database\Eloquent\Factories\HasFactory;<br>use Illuminate\Foundation\Auth\User as Authenticatable;<br>use Illuminate\Notifications\Notifiable;<br>use Laravel\Passport\HasApiTokens;<br>class User extends Authenticatable<br>{</pre><pre>use HasApiTokens, HasFactory, Notifiable;</pre><pre>}</pre><ul><li>Next, you should call the Passport::routes method within the boot method of your App\Providers\AuthServiceProvider. This method will register the routes necessary to issue access tokens and revoke access tokens, clients, and personal access tokens:</li></ul><pre>&lt;?php<br>namespace App\Providers;<br>use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;</pre><pre>use Illuminate\Support\Facades\Gate;</pre><pre>use Laravel\Passport\Passport;<br>class AuthServiceProvider extends ServiceProvider</pre><pre>{</pre><pre>/**</pre><pre>* The policy mappings for the application.</pre><pre>*</pre><pre>* @var array</pre><pre>*/</pre><pre>protected $policies = [</pre><pre>&#39;App\Models\Model&#39; =&gt; &#39;App\Policies\ModelPolicy&#39;,</pre><pre>];</pre><pre>/**</pre><pre>* Register any authentication / authorization services.</pre><pre>*</pre><pre>* @return void</pre><pre>*/</pre><pre>public function boot()</pre><pre>{</pre><pre>$this-&gt;registerPolicies();</pre><pre>if (! $this-&gt;app-&gt;routesAreCached()) {</pre><pre>Passport::routes();</pre><pre>}</pre><pre>}</pre><pre>}</pre><ul><li>Finally, in your application’s config/auth.php configuration file, you should define an api authentication guard and set the driver option to passport. This will instruct your application to use Passport&#39;s TokenGuard when authenticating incoming API requests:</li></ul><pre>&#39;guards&#39; =&gt; [<br>&#39;web&#39; =&gt; [<br>&#39;driver&#39; =&gt; &#39;session&#39;,<br>&#39;provider&#39; =&gt; &#39;users&#39;,<br>],</pre><pre>&#39;api&#39; =&gt; [<br>&#39;driver&#39; =&gt; &#39;passport&#39;,<br>&#39;provider&#39; =&gt; &#39;users&#39;,<br>],<br>],</pre><ul><li>Passport’s <a href="https://laravel.com/docs/9.x/providers">service provider</a> registers its own database migration directory, so you should migrate your database after installing the package. The Passport migrations will create the tables your application needs to store OAuth2 clients and access tokens:</li></ul><h3>3.Creating our controllers</h3><ul><li>This controller will enable users be able to register, login, and use our application.</li></ul><pre>php artisan make:controller Auth/AuthController</pre><ul><li>You can find the newly created controller in app/Http/Controllers/Auth. Let’s proceed to creating the register and login methods we need:</li></ul><pre>&lt;?php<br>namespace App\Http\Controllers\Auth;<br>use App\Http\Controllers\Controller;<br>use Illuminate\Support\Facades\Hash;<br>use Illuminate\Http\Request;<br>use Illuminate\Support\Str;<br>use App\Models\User;<br>use Validator;<br>use Auth;<br>class AuthController extends Controller<br>{</pre><pre>public function login(Request $request)<br>{<br>$validator = Validator::make($request-&gt;all(), [<br>&#39;email&#39; =&gt; &#39;required&#39;,<br>&#39;password&#39; =&gt; &#39;required&#39;<br>]);</pre><pre>if ($validator-&gt;fails()) {<br>return response()-&gt;json([<br>&#39;code&#39; =&gt; 404,<br>&#39;error&#39; =&gt; $validator-&gt;errors()<br>]);<br>}</pre><pre>if(Auth::attempt([&#39;email&#39;=&gt;$request-&gt;email, &#39;password&#39;=&gt;$request-&gt;password])) {<br>$user = Auth::user();<br>$this-&gt;scope = $user-&gt;role;<br>$token = $user-&gt;createToken($user-&gt;email.&#39;-&#39;.now(), [$this-&gt;scope]);<br>return response()-&gt;json([<br>&#39;token&#39; =&gt; $token-&gt;accessToken,<br>&#39;code&#39; =&gt; 200<br>]);</pre><pre>}else {</pre><pre>return response()-&gt;json([<br>&#39;message&#39; =&gt; &#39;Invalid email or password&#39;,<br>&#39;code&#39;  =&gt; 403<br>]);<br>}</pre><pre>public function register(Request $request){<br>$validator = Validator::make($request-&gt;all(), [<br>&#39;full_name&#39; =&gt; &#39;required&#39;,<br>&#39;phone_no&#39; =&gt; &#39;required&#39;,<br>&#39;email&#39; =&gt; &#39;required|email|unique:users&#39;,<br>&#39;password&#39; =&gt; &#39;required&#39;,<br>&#39;role&#39; =&gt; &#39;required&#39;,<br>]);</pre><pre>if ($validator-&gt;fails()) {<br>return response()-&gt;json([<br>&#39;code&#39; =&gt; 404,<br>&#39;error&#39; =&gt; $validator-&gt;errors()]);<br>}</pre><pre>$user =[<br>&#39;full_name&#39; =&gt; $request-&gt;full_name,<br>&#39;phone_no&#39; =&gt; $request-&gt;phone_no,<br>&#39;email&#39; =&gt; $request-&gt;email,<br>&#39;password&#39; =&gt;bcrypt($request-&gt;password),<br>&#39;role&#39; =&gt; $request-&gt;role,<br>];</pre><pre>$user = User::create($user);</pre><pre>$token = $user-&gt;createToken(&#39;iPF&#39;)-&gt;accessToken;<br>return response([ &#39;message&#39; =&gt;  &#39;registered successfully&#39;,&#39; token&#39; =&gt; $token,]);<br>}</pre><pre>}</pre><h3>4.Modifing users table.</h3><ul><li>Go to database/migrations then look for create_users_table add the following code on up() function.</li></ul><pre>Schema::create(&#39;users&#39;, function (Blueprint $table) {<br>$table-&gt;id();<br>$table-&gt;string(&#39;full_name&#39;);<br>$table-&gt;string(&#39;phone_no&#39;);<br>$table-&gt;string(&#39;email&#39;)-&gt;unique();<br>$table-&gt;string(&#39;password&#39;);<br>$table-&gt;string(&#39;role&#39;);<br>$table-&gt;timestamps();<br>});</pre><ul><li>Go to the terminal and hit the below command to create tables.</li></ul><pre>php artisan migrate</pre><h3>4.Define User Permission Through Role</h3><ul><li>The first step is defining the role of particular users. We are going to use 3 different permission i.e. <strong>admin</strong>, <strong>staff </strong>and <strong>finance</strong>. These roles help to authenticate the user for desired actions</li><li>Now create the UsersTableSeeder class through make:seed command and use the Users and Role factory into it.</li></ul><pre>php artisan make:seed UsersTableSeeder</pre><h3><strong>Step a:</strong></h3><pre>class UserTableSeeder extends Seeder<br>{</pre><pre>public function run()</pre><pre>{</pre><pre>return [<br>&#39;full_name&#39; =&gt; &#39;name&#39;,<br>&#39;email&#39; =&gt; &#39;example@gmail.com&#39;,<br>&#39;phone_no&#39; =&gt; 0740100005,<br>&#39;password&#39; =&gt; &#39;$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi&#39;, // password<br>&#39;role&#39; =&gt; &#39;admin&#39;,<br>];<br>}<br>}</pre><p>Now attach the UsersTableSeeder in DatabaseSeeder class</p><pre>public function run()<br>{<br>$this-&gt;call(UserTableSeeder::class);<br>}</pre><p>And run the db:seed command to add the data to the database.</p><pre>php artisan db:seed</pre><p>Repeat step a: by setting different roles i.e. admin, finance and staff</p><h3>5.Create Middleware to Attach Permission as Scope</h3><pre>php artisan make:middleware CheckRole</pre><pre>public function handle(Request $request, Closure $next)<br>{<br>$userRole = $request-&gt;user()-&gt;role;<br>if ($userRole) {</pre><pre>// Set scope as admin/finance/staff based on user role<br>$request-&gt;request-&gt;add([<br>‘scope’ =&gt; $userRole<br>]);<br>} </pre><pre>return $next($request);</pre><pre>}</pre><p>Now attach our <strong>ChecRole</strong> middleware to karnel.php file.</p><pre>protected $routeMiddleware = [<br>&#39;auth&#39; =&gt; \App\Http\Middleware\Authenticate::class,<br>...<br>&#39;role&#39; =&gt; \App\Http\Middleware\CheckRole::class,<br>&#39;scopes&#39; =&gt; \Laravel\Passport\Http\Middleware\CheckScopes::class,<br>&#39;scope&#39; =&gt; \Laravel\Passport\Http\Middleware\CheckForAnyScope::class,</pre><pre>];</pre><p>Now open the api.php file and attach the role middleware to the authenticated routes.</p><pre>Route::post(&#39;/login&#39;,[AuthController::class,&#39;login&#39;]);</pre><pre>Route::middleware([&#39;auth:api&#39;, &#39;role&#39;])-&gt;group(function() {<br>Route::middleware([&#39;scope:admin&#39;])-&gt;group(function () {</pre><pre>   Route::post(&#39;/register&#39;,[AuthController::class,&#39;register&#39;]);</pre><pre>});</pre><pre>Route::middleware([&#39;scope:admin,staff&#39;])-&gt;group(function () {</pre><pre>});</pre><pre>Route::middleware([&#39;scope:admin,finance&#39;])-&gt;group(function () {</pre><pre>});</pre><pre>});</pre><h3>6.Define Scopes in Service Provider</h3><p>Now time to define the Scopes in the AuthServiceProvider class. Make sure you have installed the Laravel Passport. I have created a separate post to <a href="https://webomnizz.com/rest-api-and-passport-authentication-with-laravel/">generate the access token with Laravel Passport</a> that you can check for the detailed description.</p><p>Open the AuthServiceProvider.php file from <strong>/app/Providers</strong> directory and define the scopes and the default scope.</p><pre>public function boot()<br>{<br>$this-&gt;registerPolicies();<br>if (! $this-&gt;app-&gt;routesAreCached()) {<br>Passport::routes();<br>Passport::tokensCan([<br>&#39;admin&#39; =&gt; &#39;has all access&#39;,<br>&#39;staff&#39; =&gt; &#39;send/view request&#39;,<br>&#39;finance&#39; =&gt; &#39;budget/accept request&#39;<br>]);<br>}<br>}</pre><h3><strong>7.we have check on the following routes in </strong><strong>api.php file.</strong></h3><ul><li><strong>POST /api/login</strong>— login in the system.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dRr6Elz89JXlzmT9iXcfdg.png" /></figure><ul><li>use the token to access other routes in the system.</li><li>when trying to register a user and not an admin an error has to popup since only admin scope is allowed to register a user.</li><li>In order to perfom <strong>POST /api/register</strong>— register in the system, Then you need to token on Authorization and choose Bearer token</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DfEt81JwjUXBONn8IfzjBg.png" /></figure><ul><li>Now add a user by providing json on the body as shown</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*akvRvFNs_4uHKjVCRPsorg.png" /></figure><h3>Conclusion</h3><p>we’ve created a REST API and secured it with Laravel Passport. To find out more about how to use Passport, you can check out the <a href="https://laravel.com/docs/8.x/passport">official documentation</a> here.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fd84fcd03ecd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Basic understanding of authentication and access-control.]]></title>
            <link>https://medium.com/@sydneykb38/basic-understanding-of-authentication-and-access-control-that-is-used-in-ipf-fund-request-app-5874b513965f?source=rss-981ab579d610------2</link>
            <guid isPermaLink="false">https://medium.com/p/5874b513965f</guid>
            <dc:creator><![CDATA[Sydney Kibanga]]></dc:creator>
            <pubDate>Wed, 10 Aug 2022 11:33:13 GMT</pubDate>
            <atom:updated>2022-08-10T12:14:44.884Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/318/1*y4sqY6dAAwaRq8H_jO97MQ.jpeg" /></figure><h3>Authentication</h3><ul><li>Authentication is used by a server when the server needs to know exactly who is accessing their information or site.</li><li>Authentication is used by a client when the client needs to know that the server is system it claims to be.</li><li>In authentication, the user or computer has to prove its identity to the server or client.</li><li>Authentication does not determine what tasks the individual can do or what files the individual can see. Authentication merely identifies and verifies who the person or system is.</li></ul><h3>Access-control</h3><ul><li>Access control is a process by which a server determines if the client has permission to use a resource or access a file.</li><li>Access control is usually coupled with authentication so that the server has some concept of who the client is that is requesting access.</li><li>The type of authentication required for access control may vary; passwords may be required in some cases but not in others.</li><li>In some cases, if there is no Access control; any user may be use a resource or access a file simply by asking for it. Most of the web pages on the Internet require no authentication or Access control.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5874b513965f" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>