<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Patrick Lusaya</title>
    <description>The latest articles on DEV Community by Patrick Lusaya (@patricklusaya).</description>
    <link>https://dev.to/patricklusaya</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F995428%2F21a94a42-7246-40a1-8e37-e092cff514c2.jpeg</url>
      <title>DEV Community: Patrick Lusaya</title>
      <link>https://dev.to/patricklusaya</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/patricklusaya"/>
    <language>en</language>
    <item>
      <title>How to migrate to modular Firebase SDK: A quick guide</title>
      <dc:creator>Patrick Lusaya</dc:creator>
      <pubDate>Sat, 27 Jul 2024 09:39:42 +0000</pubDate>
      <link>https://dev.to/patricklusaya/how-to-migrate-to-modular-firebase-sdk-a-quick-guide-10ac</link>
      <guid>https://dev.to/patricklusaya/how-to-migrate-to-modular-firebase-sdk-a-quick-guide-10ac</guid>
      <description>&lt;p&gt;Imagine you’re packing for a trip. Instead of throwing everything from your closet into your suitcase, you only pack what you need for the journey. Not only does this make your suitcase lighter, but it also means you’re more organized and can find things easily.&lt;/p&gt;

&lt;p&gt;Well, Firebase has done something similar with their new update! They’ve introduced a new way to use their tools that’s all about packing only what you need. This new method is called "modular Firebase," and it’s all about making your app faster and easier to manage.&lt;/p&gt;

&lt;p&gt;In the past, using Firebase was a bit like taking everything from your closet – it worked, but it wasn’t always the most efficient. Now, with Firebase version 9 and later, you can pick and choose exactly what parts of Firebase you need, making your app lighter and quicker.&lt;/p&gt;

&lt;p&gt;Hey, follow me on &lt;a href="https://x.com/patisocialnet" rel="noopener noreferrer"&gt;twitter&lt;/a&gt;, I'll help you with something ... I promise&lt;/p&gt;

&lt;p&gt;In this article, i’ll show you how to switch from the old way of using Firebase to the new modular way&lt;/p&gt;

&lt;p&gt;1.&lt;strong&gt;Initialize Firebase&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Just like you wouldn’t pack your whole closet, you only import the Firebase parts you need.Create a file called &lt;code&gt;firebaseConfiguration&lt;/code&gt;, paste the following code imports the required Firebase modules, configure Firebase with your project's settings, initialize Firebase and its services, and check if Firebase is already initialized in your app.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { initializeApp, getApp, getApps } from 'firebase/app';
import { initializeAuth, getReactNativePersistence } from 'firebase/auth/react-native';
import { getFirestore } from 'firebase/firestore';
import { getStorage } from 'firebase/storage';
import AsyncStorage from '@react-native-async-storage/async-storage';

const firebaseConfig = {
    apiKey: "yourApiKey",
    authDomain: "yourAuthDomain",
    projectId: "yourProjectID",
    storageBucket: "yourStorageBucket",
    messagingSenderId: "yourMessagingSenderID",
    appId: "yourAppID",
    measurementId: "yourMeasurementID"
};

const app = initializeApp(firebaseConfig);
const auth = initializeAuth(app, {
    persistence: getReactNativePersistence(AsyncStorage)
});
const db = getFirestore(app);
const storage = getStorage(app);

const isFirebaseInitialized = () =&amp;gt; {
    const apps = getApps();
    if (apps.length === 0) {
        return false;
    }
    const app = getApp();
    const config = app.options;
    return !!config.projectId;
};

export { auth, db, storage,isFirebaseInitialized };
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We have exported auth, db , storage and isFirebaseInitialized so we can use them wherever we need in our app.&lt;/p&gt;

&lt;p&gt;2.&lt;strong&gt;Use the Exported Modules&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;In our app's entry point, we'll start by checking if Firebase is properly initialized using our isFirebaseInitialized function. If Firebase is not initialized correctly, we’ll log a message indicating the issue. Otherwise, we’ll proceed with rendering our main app component.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { View, Text } from 'react-native';
import React from 'react';
import { isFirebaseInitialized } from './firebaseConfiguration';

const App = () =&amp;gt; {
  if (!isFirebaseInitialized()) {
    console.log('Firebase is not initialized with a valid projectId.');
    return null;
  }

  return (
    &amp;lt;View&amp;gt;
      &amp;lt;Text&amp;gt;App&amp;lt;/Text&amp;gt;

    &amp;lt;/View&amp;gt;
  );
};

export default App;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;3.&lt;strong&gt;Modular firebase in action.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Now, let's see modular Firebase in action by fetching, creating, updating, and deleting data.&lt;/p&gt;

&lt;p&gt;Before modular Firebase, you might have imported everything from Firebase like this:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;import * as firebase from 'firebase';&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;While this worked perfectly, it wasn't the best approach because it loaded the entire Firebase library, including parts you might not need. This made your app's bundle size larger and could slow down its performance.&lt;/p&gt;

&lt;p&gt;Let's compare two fetch operations, one using the Previous Firebase SDK and the other using the new modular firebase SDK&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Previous Firebase SDK&lt;/strong&gt;&lt;br&gt;
In the previous Firebase SDK, you would import everything from Firebase, which could lead to larger bundle sizes and slower performance.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import firebase from "firebase";

const fetchData = async () =&amp;gt; {
  const querySnapshot = await 
  firebase.firestore().collection('yourCollectionName').get();
  querySnapshot.forEach((doc) =&amp;gt; {
    console.log(`${doc.id} =&amp;gt; ${doc.data()}`);
  });
};

fetchData();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Modular firebase sdk&lt;/strong&gt;&lt;br&gt;
With modular Firebase, we only import the specific modules we need at any given moment. This is more efficient and helps keep our app lightweight and fast.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { collection, getDocs } from 'firebase/firestore';
import { db } from './firebaseConfiguration';

const fetchData = async () =&amp;gt; {
  const querySnapshot = await getDocs(collection(db, 'yourCollectionName'));
  querySnapshot.forEach((doc) =&amp;gt; {
    console.log(`${doc.id} =&amp;gt; ${doc.data()}`);
  });
};

fetchData();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Instead of loading the entire Firebase library, we have just imported the modules that we needed, collection and getDocs.&lt;/p&gt;

&lt;p&gt;By importing only the necessary modules, we keep our code clean and efficient. This modular approach makes our app faster and easier to manage, especially as it grows in complexity. Now, let’s take a look at the complete CRUD operations using both the previous Firebase SDK and the new modular Firebase SDK.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Create Data&lt;br&gt;
Previous SDK&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import firebase from "firebase";
const createData = async () =&amp;gt; {
  try {
    const docRef = await 
      firabase.firestore().collection('yourCollectionName').add({
      field1: 'value1',
      field2: 'value2'
    });
    console.log('Document written with ID: ', docRef.id);
  } catch (e) {
    console.error('Error adding document: ', e);
  }
};

createData();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Modular firebase&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { collection, addDoc } from 'firebase/firestore';
import { db } from './firebaseConfiguration';

const createData = async () =&amp;gt; {
  try {
    const docRef = await addDoc(collection(db, 'yourCollectionName'), {
      field1: 'value1',
      field2: 'value2'
    });
    console.log('Document written with ID: ', docRef.id);
  } catch (e) {
    console.error('Error adding document: ', e);
  }
};

createData();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Update Data&lt;br&gt;
Previous Firebase SDK&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import firebase from "firebase";

const updateData = async (id) =&amp;gt; {
  const docRef = 
  firabase.firestore().collection('yourCollectionName').doc(id);
  try {
    await docRef.update({
      field1: 'newValue1'
    });
    console.log('Document updated');
  } catch (e) {
    console.error('Error updating document: ', e);
  }
};

updateData('yourDocumentId');
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Modular Firebase SDK&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { doc, updateDoc } from 'firebase/firestore';

const updateData = async (id) =&amp;gt; {
  const docRef = doc(db, 'yourCollectionName', id);
  try {
    await updateDoc(docRef, {
      field1: 'newValue1'
    });
    console.log('Document updated');
  } catch (e) {
    console.error('Error updating document: ', e);
  }
};

updateData('yourDocumentId');
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Delete Data&lt;br&gt;
Previous Firebase SDK&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import firebase from "firebase";
const deleteData = async (id) =&amp;gt; {
  const docRef = 
  firabase.firestore().collection('yourCollectionName').doc(id);
  try {
    await docRef.delete();
    console.log('Document deleted');
  } catch (e) {
    console.error('Error deleting document: ', e);
  }
};

deleteData('yourDocumentId');
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Modular Firebase SDK&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { doc, deleteDoc } from 'firebase/firestore';

const deleteData = async (id) =&amp;gt; {
  const docRef = doc(db, 'yourCollectionName', id);
  try {
    await deleteDoc(docRef);
    console.log('Document deleted');
  } catch (e) {
    console.error('Error deleting document: ', e);
  }
};

deleteData('yourDocumentId');
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Overall Arrangement and Syntax&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;collection(db, 'yourCollectionName')&lt;/code&gt;: Used to refer to a collection in Firestore.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;doc(db, 'yourCollectionName', 'yourDocumentId')&lt;/code&gt;: Used to refer to a specific document within a collection.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Functions like &lt;code&gt;getDocs&lt;/code&gt;, &lt;code&gt;addDoc&lt;/code&gt;, &lt;code&gt;updateDoc&lt;/code&gt;, and &lt;code&gt;deleteDoc&lt;/code&gt;: These perform the actual operations on the data.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Pros of Modular Firebase&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Smaller Bundle Size:&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;With modular imports, you only include the parts of Firebase you actually use, rather than the entire library.This reduces your app’s bundle size, leading to faster load times and better performance.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Improved Performance:&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;By importing only what you need, you minimize the amount of code that the JavaScript engine has to process. This can result in faster execution and reduced memory usage.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Tree-Shaking Support:&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The modular approach supports tree-shaking, which is a technique to eliminate unused code during the build process.This further optimizes your app’s performance and reduces the final bundle size.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Cons of Modular Firebase&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;More Verbose Imports:&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;You need to import each function or module individually.This can make the import statements longer and potentially more cumbersome, though it provides clearer insights into what’s used.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Migration Effort:&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Transitioning from the previous SDK to the modular SDK involves updating existing code and ensuring compatibility. This migration process can be time-consuming, especially for large projects with extensive use of Firebase.&lt;/p&gt;

&lt;p&gt;That's pretty much it , adios !&lt;/p&gt;

&lt;p&gt;Follow me on &lt;a href="https://x.com/patisocialnet" rel="noopener noreferrer"&gt;twitter&lt;/a&gt;, for more contents like these&lt;/p&gt;

</description>
      <category>firebase</category>
      <category>reactnative</category>
    </item>
    <item>
      <title>How to setup Redux in React Js</title>
      <dc:creator>Patrick Lusaya</dc:creator>
      <pubDate>Fri, 19 Jul 2024 17:04:30 +0000</pubDate>
      <link>https://dev.to/patricklusaya/how-to-setup-redux-in-react-js-5age</link>
      <guid>https://dev.to/patricklusaya/how-to-setup-redux-in-react-js-5age</guid>
      <description>&lt;p&gt;Hello devs! This is a quick and to-the-point tutorial on how to set up Redux in React.&lt;/p&gt;

&lt;p&gt;Given that you've landed on this article, you probably already know the significance of Redux in state management and why it's a vital tool for managing state in your applications.&lt;/p&gt;

&lt;p&gt;Follow me on &lt;a href="https://x.com/patisocialnet" rel="noopener noreferrer"&gt;twitter&lt;/a&gt;, I'll help you out with something ... I promise.&lt;/p&gt;

&lt;p&gt;ALSO&lt;/p&gt;

&lt;p&gt;You could check this tutorial on &lt;a href="https://youtu.be/SR8gpAvDb2I?si=tujZrGUHSm4sKRKc" rel="noopener noreferrer"&gt;youtube&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;There's so many ways to do this and here's the way we are gonna go. &lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;On your project's root directory, Run the following command to install the necessary dependencies, &lt;code&gt;npm install react-redux reduxjs/toolkit&lt;/code&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Open your project's &lt;code&gt;index.js&lt;/code&gt; file and wrap the &lt;code&gt;&amp;lt;App/&amp;gt;&lt;/code&gt; with &lt;code&gt;Provider&lt;/code&gt; from &lt;code&gt;react-redux&lt;/code&gt;&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Code:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt; const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
      &amp;lt;Provider&amp;gt;
          &amp;lt;App /&amp;gt;
      &amp;lt;/Provider&amp;gt;
);

reportWebVitals();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;&amp;lt;Provider&amp;gt;&lt;/code&gt;: Wraps the application in the Redux Provider component, making the Redux store available to all components within the app.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;&amp;lt;App /&amp;gt;&lt;/code&gt;: The main application component that contains the rest of the React components.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Create a redux store on the Provider you've just added
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const store = configureStore({
  reducer: Reducer,
});

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
      &amp;lt;Provider store={store}&amp;gt;
          &amp;lt;App /&amp;gt;
      &amp;lt;/Provider&amp;gt;
);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Code Explanation:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const store = configureStore({
  reducer: Reducer,
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here, we are creating a Redux store using the configureStore function from the @reduxjs/toolkit package. The configureStore function simplifies the setup process and comes with sensible defaults. We pass an object with a reducer property to configureStore, specifying the root reducer (Reducer) which handles state updates.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;We have declared the root reducer named &lt;code&gt;Reducer&lt;/code&gt; but , we have not created one. Do so by creating a &lt;code&gt;store.js&lt;/code&gt; file from root directory.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Sample code in the index.js:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { combineReducers } from 'redux';

//-&amp;gt; reducers imports
import AppReducer from "./AppReducer"
import PostReducer from "./PostReducer"

export default combineReducers({

    app: AppReducer,
    posts:PostReducer


});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Explanaation:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;combineReducers&lt;/code&gt;: This function from Redux is used to combine multiple reducers into a single root reducer. Each reducer manages its slice of the application state.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;AppReducer&lt;/code&gt; and &lt;code&gt;PostsReducer&lt;/code&gt;: These are example reducers imported from their respective files. Each reducer handles state updates for different parts of the application.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;app&lt;/code&gt;and &lt;code&gt;posts&lt;/code&gt;: These keys represent different slices of the state managed by AppReducer and PostsReducer respectively.&lt;/p&gt;

&lt;p&gt;From here, all state updates managed by AppReducer can be accessed in your components using the app key, while updates managed by PostsReducer can be accessed using the posts key&lt;/p&gt;

&lt;p&gt;Complete index.js code:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';

//redux import
import { configureStore } from '@reduxjs/toolkit';
import { Provider } from 'react-redux';

//reducer import
import Reducer from './reducers';

//router import
import {BrowserRouter} from "react-router-dom";

const store = configureStore({
  reducer: Reducer,
});


const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(

  // Remove BrowserRouter tags if you dont want to use Routing
    &amp;lt;BrowserRouter&amp;gt;
      &amp;lt;Provider store={store}&amp;gt;
          &amp;lt;App /&amp;gt;
      &amp;lt;/Provider&amp;gt;
    &amp;lt;/BrowserRouter&amp;gt;
);

reportWebVitals();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Complete store.js code:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { combineReducers } from 'redux';

//-&amp;gt; reducers imports
import AppReducer from "./AppReducer"
import PostsReducer from "./PostsReducer"

export default combineReducers({

    app: AppReducer,
    posts:PostsReducer


});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Sample Structure of &lt;code&gt;PostReducer.js&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import {FETCH_POSTS_SUCCESS,} from "../actions/Types";

const INITIAL_STATE = {
    fetchedPosts:[]
};

const PostReducer = (state = INITIAL_STATE, action) =&amp;gt; {

    switch (action.type) {

        case FETCH_POSTS_SUCCESS:

        return {...state, fetchedPosts: action.payload,};


        default:
            return state;
    }
};

export default PostReducer;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;And just like that you're done setting up redux. &lt;/p&gt;

&lt;p&gt;You could check this tutorial on &lt;a href="https://youtu.be/SR8gpAvDb2I?si=tujZrGUHSm4sKRKc" rel="noopener noreferrer"&gt;youtube&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;If, I've just saved your day follow me on &lt;a href="https://x.com/patisocialnet" rel="noopener noreferrer"&gt;twitter&lt;/a&gt; and I'll save you another&lt;/p&gt;

&lt;p&gt;Adios !&lt;/p&gt;

</description>
      <category>webdev</category>
      <category>redux</category>
      <category>react</category>
    </item>
    <item>
      <title>How to intergrate BEEM Sms API with React</title>
      <dc:creator>Patrick Lusaya</dc:creator>
      <pubDate>Wed, 17 Jul 2024 14:41:58 +0000</pubDate>
      <link>https://dev.to/patricklusaya/how-to-intergrate-beem-sms-api-with-react-443m</link>
      <guid>https://dev.to/patricklusaya/how-to-intergrate-beem-sms-api-with-react-443m</guid>
      <description>&lt;p&gt;Hello Devs,&lt;/p&gt;

&lt;p&gt;After facing some challenges while integrating the &lt;a href="https://login.beem.africa/!#/register?ref_name=lusayapatrick@gmail.com" rel="noopener noreferrer"&gt;BEEM&lt;/a&gt; SMS API with React.js, I finally succeeded and thought, why not share my experience to help others who might be attempting the same task?&lt;/p&gt;

&lt;p&gt;In this article, I'll guide you through the process step-by-step to make your integration smooth and straightforward.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://login.beem.africa/!#/register?ref_name=lusayapatrick@gmail.com" rel="noopener noreferrer"&gt;BEEM&lt;/a&gt; SMS API is a REST based API that supports sending sms as well as receiving delivery status reports. It currently only operates across Africa.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Getting Hands Dirty.&lt;/strong&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;Visit the &lt;a href="https://login.beem.africa/!#/register?ref_name=lusayapatrick@gmail.com" rel="noopener noreferrer"&gt;BEEM&lt;/a&gt; website, sign up, and if everything goes well, you will be redirected to the dashboard.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Once you have signed up, you automatically receive 10 SMS credits. If you need more (which you probably will), simply click on "Purchase SMS" in the sidebar.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Enter the desired quantity of messages in the "Purchase Quantity" field, then click the "Next" button. Select your preferred payment method, complete the payment process, and once the transaction is confirmed, you'll receive an email from BEEM. Your SMS credits will then be updated and displayed on the dashboard.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Generate your API key by clicking on "API Setup" in the sidebar. If you don't have an autogenerated key, click the "Create" button to generate one.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Scroll down the sidebar and click on "API Docs" to understand how things operate. In the documentation, scroll further down to "Sample Scripts" to find a POST script for sending SMS&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Now that we are all setup, create a react project by running the command &lt;code&gt;npx create-react-app my-app&lt;/code&gt;. Open &lt;code&gt;App.js&lt;/code&gt; and on your component's &lt;code&gt;return()&lt;/code&gt; paste this:&lt;br&gt;
&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;return (
   &amp;lt;div className="App"&amp;gt;
     &amp;lt;div className="App"&amp;gt;
      &amp;lt;header className="App-header"&amp;gt;
        &amp;lt;img src={logo} className="App-logo" alt="logo" /&amp;gt;

        &amp;lt;button style={{width: 100, height: 50}} onClick= 
           {sendMessage}&amp;gt;Send Message&amp;lt;/button&amp;gt;
      &amp;lt;/header&amp;gt;
    &amp;lt;/div&amp;gt;

   &amp;lt;/div&amp;gt;
  );

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ol&gt;
&lt;li&gt;When the button is clicked, it will trigger the sendMessage method. Paste the following code to implement the sendMessage method
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const sendMessage = async () =&amp;gt; {
    const API_KEYY = "your api key";
    const SECRET_KEY = "your secret key";
    const CONTENT_TYPE = "application/json";
    const SOURCE_ADDR ="INFO"; //This is a default SENDER ID you are 
    assigned to on signup , you can later change it
    const url = 'https://api.beem.africa/v1/send';

    fetch(url, {
      method: "POST",
      headers: {
        "Content-Type": CONTENT_TYPE,
        Authorization: "Basic " + btoa(API_KEYY + ":" + SECRET_KEY),
      },
      body: JSON.stringify({
        source_addr: SOURCE_ADDR,
        schedule_time: "",
        encoding: 0,
        message: "Hello World",
        recipients: [
          {
            recipient_id: 1,
            dest_addr: "25465943782",
          },

        ],
      }),
    })
      .then((response) =&amp;gt; response.json())
      .then((data) =&amp;gt; console.log(data))
      .catch((error) =&amp;gt; console.error(error));
  }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;*&lt;em&gt;What the code does *&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;This code defines a function sendMessage that sends an SMS message using the BEEM SMS API. It sets up the necessary parameters such as API_KEYY, SECRET_KEY, CONTENT_TYPE, and SOURCE_ADDR (which is a default sender ID assigned to you on signup but can be changed later).&lt;/p&gt;

&lt;p&gt;Once the request is sent, it handles the response by converting it to JSON and logging the data to the console. Any errors that occur during the request are caught and logged to the console as well&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;On clicking Send Message, Voila your message is sent. The SMS will be sent from a default name(INFO), that you can change by simply going on the dashboard's sidebar and click "Sender Names" under the "Campaign" link. Apply for a sender name, after the application is approved you can now use that as your sender name/SOURCE_ADDR/SENDER ID&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Note&lt;/strong&gt;:If you are using the sender ID "INFO", please note that you can only send messages successfully to some limited mobile networks. The message will be sent, but it may not be delivered to the recipient. To ensure successful delivery, consider applying for a sender ID/sender name&lt;/p&gt;

&lt;p&gt;That's it, adios !&lt;/p&gt;

</description>
    </item>
    <item>
      <title>How To Setup Laravel on Windows with XAMPP: Quick Guide</title>
      <dc:creator>Patrick Lusaya</dc:creator>
      <pubDate>Wed, 24 Jan 2024 12:25:23 +0000</pubDate>
      <link>https://dev.to/patricklusaya/how-to-setup-laravel-on-windows-with-xampp-quick-guide-16ng</link>
      <guid>https://dev.to/patricklusaya/how-to-setup-laravel-on-windows-with-xampp-quick-guide-16ng</guid>
      <description>&lt;p&gt;Welcome back to Laravel! Whether you're a beginner or a seasoned developer who's forgotten the basic setup, this quick guide will help you set up Laravel on Windows using XAMPP.&lt;/p&gt;

&lt;p&gt;Follow me on &lt;a href="https://x.com/patisocialnet" rel="noopener noreferrer"&gt;twitter&lt;/a&gt;, I'll help you out with something ... I promise.&lt;/p&gt;

&lt;p&gt;Lets get started &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 1: Install PHP&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;First, you'll need PHP installed on your system. Laravel, being a PHP framework, requires PHP to function. You can download PHP from the official PHP &lt;a href="https://www.php.net/downloads" rel="noopener noreferrer"&gt;website&lt;/a&gt;.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Click on the Windows Download&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fpo6uwyrdb1kol5y3iuhp.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fpo6uwyrdb1kol5y3iuhp.png" alt="PHP Download Image" width="800" height="381"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;On the page where you are redirected, choose the thread-safe option and click on the zip link to download it.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fgqi9ggjo85mjesjs2cmx.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fgqi9ggjo85mjesjs2cmx.png" alt="redirected page" width="800" height="398"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Once the zip file has been downloaded, extract it and copy the extracted folder into your program files folder located at
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Local disk(C) -&amp;gt; Program files
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;Now after pasting the folder, copy the its address.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ffq9zvv1jkgr5hqfiy9dd.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ffq9zvv1jkgr5hqfiy9dd.png" alt="copy address" width="800" height="416"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;On the start menu search for "Edit the system environment variables". Press enter to open it. A new window will appear then click on the "Environment Variables: button.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fqjq65lr20y7wzv8d6tmm.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fqjq65lr20y7wzv8d6tmm.png" alt="click environment" width="800" height="414"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Another new window will appear and on the System Variables section, double-click on the Path to open up a new screen.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fuafl3k4ltaisnc9hy1cr.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fuafl3k4ltaisnc9hy1cr.png" alt="new pop up window" width="800" height="421"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;On that new screen, click on the new button. A field will appear. Paste the address copied previously and press OK on all screens to save your changes.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Feeau3rimkoohlp6l70ks.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Feeau3rimkoohlp6l70ks.png" alt="click the new button" width="800" height="415"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;To check if PHP is installed successfully, go to the start menu and open your terminal by typing cmd.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;On the terminal type, &lt;code&gt;php -v&lt;/code&gt; and press Enter to see the version of PHP installed.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F9e4jfwkrwmc39tz9cd7b.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F9e4jfwkrwmc39tz9cd7b.png" alt="check php version" width="658" height="219"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 2: Install Composer&lt;/strong&gt;&lt;br&gt;
Composer is a dependency management tool for PHP which is required to install any PHP package/library you might want to use. Here's how to install it.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Visit &lt;a href="https://getcomposer.org/" rel="noopener noreferrer"&gt;https://getcomposer.org/&lt;/a&gt; and click on the DOWNLOAD button.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F2xgrkk1idcmt2w2dkuk4.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F2xgrkk1idcmt2w2dkuk4.png" alt="download composer" width="800" height="403"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;You will be redirected to the download page where you will have to click on the Composer-Setup.exe to download Composer on your machine.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F0bmmq5y8zrghol98p0jz.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F0bmmq5y8zrghol98p0jz.png" alt="redirected page" width="800" height="378"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;After the download is complete, Open the setup and select "install for all users"&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;For the next pop-up screens that appear click YES to allow installation then choose the installation type and press NEXT.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Select the command-line PHP path you want to use, check the box to add the PHP path, and click NEXT.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;If you want to use a proxy, check the box and enter the proxy URL and if not proceed by clicking NEXT.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;If everything seems okay, click the INSTALL button.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Read the information that follows after installation and click NEXT.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Finally, click the FINISH button to complete the installation.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Open your terminal and type "composer" to check if the installation was successful. If it was you will see the composer version and other composer commands&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fo2lm972x6yt0i3cp8sn1.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fo2lm972x6yt0i3cp8sn1.png" alt="check if composer is installed" width="800" height="408"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 3: Install XAMPP&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Visit &lt;a href="https://www.apachefriends.org/index.html" rel="noopener noreferrer"&gt;here&lt;/a&gt; and click on the Xampp for Windows link to start the download.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fv18685ydiofdteid7602.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fv18685ydiofdteid7602.png" alt="xampp install" width="800" height="374"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Select MySQL, FileZilla ftp server, PHP, phpMyAdmin or you can just leave the default options and click the Next button.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;In order to configure the htdocs folder for our apps, select the root directory path. Consider "C:\xampp."&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;To enable the XAMPP modules from the Windows firewall, click the Allow access button.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Click the XAMPP Setup wizard's Finish button after the installation is complete.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;To start Xampp, go over to the start menu and type "xampp" then press enter to open it.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fcogi49hqw0huxqvs1kkw.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fcogi49hqw0huxqvs1kkw.png" alt="open xampp" width="668" height="423"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;To start the server, press the start button for Apache and Mysql, then the admin button of Mysql to open phpMyAdmin.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Now that you have PHP, Composer, and XAMPP installed, you can create a new Laravel project.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Since you are using xampp, the laravel project you are going to create should be within the xampp's htdocs folder found at
&lt;/li&gt;
&lt;/ul&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;C:\xampp\htdocs
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Open the terminal at that location (
&lt;/li&gt;
&lt;/ul&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;C:\xampp\htdocs
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;) and run the command &lt;code&gt;composer global require "laravel/installer"&lt;/code&gt; to install laravel &lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Foesolbctcvqsc21gq5zm.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Foesolbctcvqsc21gq5zm.png" alt="install laravel " width="508" height="142"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Then run &lt;code&gt;laravel new my_app&lt;/code&gt; on the same path (&lt;code&gt;C:\xampp\htdocs&lt;/code&gt;)  to create a project called "my_app"&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Configure .env File for XAMPP&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Edit the .env file in your Laravel project and set up your database connection:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=your_database_name
DB_USERNAME=root
DB_PASSWORD=
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Replace your_database_name with the actual database name.&lt;/p&gt;

&lt;p&gt;The default XAMPP MySQL username is root, and the password is usually empty.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Now open your browser and paste in &lt;code&gt;http://localhost/my-app/public&lt;/code&gt;
&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;If everything went well you will be redirected to the welcome view&lt;/p&gt;

&lt;p&gt;That's it! You've now successfully set up Laravel on Windows using XAMPP. &lt;/p&gt;

&lt;p&gt;If, I've just saved your day follow me on &lt;a href="https://x.com/patisocialnet" rel="noopener noreferrer"&gt;twitter&lt;/a&gt; and I'll save you another&lt;/p&gt;

&lt;p&gt;Happy coding!&lt;/p&gt;

</description>
      <category>laravel</category>
      <category>xampp</category>
      <category>windows</category>
    </item>
    <item>
      <title>How to Implement Role-Based Authentication in Laravel with Sanctum: A Step-by-Step Guide</title>
      <dc:creator>Patrick Lusaya</dc:creator>
      <pubDate>Thu, 13 Apr 2023 06:35:15 +0000</pubDate>
      <link>https://dev.to/patricklusaya/how-to-implement-role-based-authentication-in-laravel-with-sanctum-a-step-by-step-guide-4pbk</link>
      <guid>https://dev.to/patricklusaya/how-to-implement-role-based-authentication-in-laravel-with-sanctum-a-step-by-step-guide-4pbk</guid>
      <description>&lt;p&gt;Role-based authentication is a crucial aspect of web application development, especially when it comes to managing user access to different parts of the system. In Laravel, Sanctum is a popular package for implementing API authentication, including role-based access control. This guide will provide a step-by-step approach to implement role-based authentication in Laravel using Sanctum. &lt;/p&gt;

&lt;p&gt;Our API will have users with two types of roles: &lt;code&gt;admin&lt;/code&gt; and &lt;code&gt;moderator&lt;/code&gt;. Admin will create moderators and Moderators will basically perform all other operations that may be needed.&lt;/p&gt;

&lt;p&gt;Follow me on &lt;a href="https://x.com/patisocialnet" rel="noopener noreferrer"&gt;twitter&lt;/a&gt;, I'll help you out with something ... I promise.&lt;/p&gt;

&lt;p&gt;Lets get started !&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 1: Setting up our project.&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Create a laravel project by running the command &lt;code&gt;composer create-project laravel/laravel myProjectName&lt;/code&gt; anywhere you want to create your project.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;After that create your database in any type of database management system of your choice then head over to &lt;code&gt;.env&lt;/code&gt; file of your project and configure the following &lt;br&gt;
:&lt;br&gt;
&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;DB_CONNECTION=pgsql //fill according to your database
DB_HOST=127.0.0.1
DB_PORT=5432 //fill according to your database
DB_DATABASE=databaseName
DB_USERNAME=yourUsername
DB_PASSWORD=yourPassword
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;Now, install sanctum to your project by running the command &lt;code&gt;composer require laravel/sanctum&lt;/code&gt; on  your project's root directory.&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Next, you should publish the Sanctum configuration and migration files using the command &lt;code&gt;php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider"&lt;/code&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;After that, you should replace Sanctum's middleware of your api middleware group within your application's &lt;code&gt;app/Http/Kernel.php&lt;/code&gt; file with:&lt;br&gt;
&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;'api' =&amp;gt; [
    \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
    \Illuminate\Routing\Middleware\ThrottleRequests::class.':api',
    \Illuminate\Routing\Middleware\SubstituteBindings::class,
],
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Finally, run &lt;code&gt;php artisan migrate&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 2: Create users table and User Model&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;In your migrations folder open the migration file &lt;code&gt;create_users_table&lt;/code&gt; and on the up function replace the existing code with:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Schema::create('users', function (Blueprint $table) {
            $table-&amp;gt;id();
            $table-&amp;gt;string('username')-&amp;gt;unique();
            $table-&amp;gt;string('email')-&amp;gt;unique();
            $table-&amp;gt;timestamp('email_verified_at')-&amp;gt;nullable();
            $table-&amp;gt;string('password');
            $table-&amp;gt;rememberToken();
            $table-&amp;gt;enum('role', [ 'admin', 'moderator'])-&amp;gt;default('admin');
            $table-&amp;gt;timestamps();
        });
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;&lt;p&gt;What this does is it creates a users table with the columns username, email, password, role and others as described in the function.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;$table-&amp;gt;enum('role', [ 'admin', 'moderator'])-&amp;gt;default('admin')&lt;/code&gt;; - This adds a "role" column to the "users" table with an enumerated data type and a default value of "admin". The "role" column can only contain values of "admin" or "moderator". Now, what we are doing here is that if the the registration request won't have a role in it then by default that user will have a role of admin.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Run &lt;code&gt;php artisan migrate&lt;/code&gt; to create the users table.&lt;/p&gt;

&lt;p&gt;Then,create a User model with fillable fields: In Laravel, you can create a User model by running the &lt;code&gt;php artisan make:model User&lt;/code&gt; command in the terminal. Once you've done that, you can define the model's fillable fields by adding the following code to the model file:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;protected $fillable = [
    'username',
    'email',
    'password',
    'role'
];
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Step 3: Create a middleware to check roles of users.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;A middleware simply sits between the server and your request, it checks to see if you're allowed to access that information or perform that action.&lt;/p&gt;

&lt;p&gt;We will create a &lt;code&gt;checkRole&lt;/code&gt; middleware by running the command &lt;code&gt;php artisan make:middleware checkRole&lt;/code&gt;.&lt;br&gt;
Once that is done open the middleware and paste the following code :&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public function handle(Request $request, Closure $next, ...$roles)
    {

        $user = $request-&amp;gt;user();

        if (! $user || ! in_array($user-&amp;gt;role, $roles)) {
            abort(403, 'Unauthorized');
        }

        return $next($request);

    }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;&lt;p&gt;What this does is it checks if the authenticated user has a role that is allowed to access a certain route. If the user does not have the required role, it aborts the request and returns a 403 (Forbidden) error message. Otherwise, it passes the request to the next middleware in the chain.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Now register the middleware you just created by adding it in the array of &lt;code&gt;routeMiddleware&lt;/code&gt; in your &lt;code&gt;kernel.php&lt;/code&gt; as &lt;code&gt;'restrictRole' =&amp;gt; &lt;br&gt;
\App\Http\Middleware\CheckRole::class,&lt;/code&gt;&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Step 4: Create Authentication Controller&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;This controller will handle our registration and login logic.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;But remember, since only admin can create moderators, Then the registration endpoint must be protected because we don't want other users to assign roles to themselves. Therefore we will create an initial default admin who can then create other admins and moderators.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;To do this we need to create a seeder called defaultAdmin  by running the command &lt;code&gt;php artisan make:seeder defaultAdmin&lt;/code&gt;. Once that is done open the file and paste the following code to create a default initial user:&lt;br&gt;
&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public function run()
    {
        User::create(
            [
            'username' =&amp;gt; 'admin',
            'email' =&amp;gt; 'admin@jf.com',
            'password' =&amp;gt; bcrypt('password'),
            'role' =&amp;gt; 'admin',
            ]
            );
    }

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Now you can proceed creating the Authentication controller by running &lt;code&gt;php artisan make:controller AuthController&lt;br&gt;
&lt;/code&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Open the file and paste the following code to handle registration and login&lt;br&gt;
:&lt;br&gt;
&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public function register( Request $request){
        $data = $request-&amp;gt;validate([
            'username' =&amp;gt; 'required|unique:users',
            'email' =&amp;gt; 'required|unique:users',
            'password' =&amp;gt; 'required|confirmed',
            'role' =&amp;gt; 'in:admin,moderator',
        ]);

        // Set default role to 'admin' if not provided in the request
        $userData = array_merge($data, ['role' =&amp;gt; $data['role'] ?? 'admin']);


        // Mass assign the validated request data to a new instance of the User model
        $user = User::create($userData);
        $token = $user-&amp;gt;createToken('my-token')-&amp;gt;plainTextToken;

        return response()-&amp;gt;json([
            'token' =&amp;gt;$token,
            'Type' =&amp;gt; 'Bearer'
        ]);
    }

    public function login(Request $request)
    {
        $fields = $request-&amp;gt;validate([
            'username' =&amp;gt; 'required',
            'password' =&amp;gt; 'required',
        ]);

        $user = User::where('username', $fields['username'])-&amp;gt;first();

        if (!$user || !Hash::check($fields['password'], $user-&amp;gt;password)) {
            return response([
                'message' =&amp;gt; 'Wrong credentials'
            ]);
        }

        $token = $user-&amp;gt;createToken('my-token')-&amp;gt;plainTextToken;

        return response()-&amp;gt;json([
            'token' =&amp;gt; $token,
            'Type' =&amp;gt; 'Bearer',
            'role' =&amp;gt; $user-&amp;gt;role // include user role in response
        ]);
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Code Explanation&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;The register function first uses the validate method of the request object to validate the input data against some rules defined in an array.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;If the validation passes, the function continues by merging the validated data with a default value for the role field, if not provided in the request.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;The function then creates a new instance of the User model with the validated and merged data, using the create method, which performs a mass assignment of the input data to the new user object.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;After creating the user, the function generates an access token for the user using the &lt;code&gt;createToken&lt;/code&gt; method of the user object, and returns a JSON response containing the token and its type. The token can be used by the client to authenticate subsequent requests to protected routes on the server&lt;br&gt;
.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;The login function first validates the input data (the username and password fields) using the validate method of the request object. The function then retrieves a user instance from the database based on the provided username. If the user doesn't exist or the password is incorrect, it returns a response with the message "Wrong credentials".&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;If the user exists and the password is correct, the function generates an access token for the user using the&lt;code&gt;createToken&lt;/code&gt; method of the user object and returns a JSON response containing the token, its type, and the user's role. The token can be used by the client to authenticate subsequent requests to protected routes on the server.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Step 5: Create routes&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Open &lt;code&gt;api/routes.api&lt;/code&gt; file and paste the following code&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;//public route
Route::post('/auth/login', [AuthController::class, 'login']);
//protected route
Route::group(['middleware' =&amp;gt; ['auth:sanctum']], function(){
 Route::post('/auth/register', [AuthController::class, 'register'])-&amp;gt;middleware('restrictRole:admin');
Route::get('/users', [PostController::class, 'show'])-&amp;gt;middleware('restrictRole:admin');
Route::put('/users/{id}', [PostController::class, 'update'])-&amp;gt;middleware('restrictRole:moderator');
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;&lt;p&gt;You may notice we have added two more routes, a &lt;code&gt;GET&lt;/code&gt;request to users and a &lt;code&gt;PUT&lt;/code&gt; request to users. We want only admin to have access to the endpoint that gets users and only moderators to have access to the endpoint that updates users.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Now, as you have seen in the above code all these routes have been placed within a single function and under one group. A route group allows you to group several routes together and apply the same middleware, namespace, prefix, or other common attributes to them.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;In the provided code, &lt;code&gt;Route::group&lt;/code&gt; is a function that creates a new route group with middleware. The middleware in this case is &lt;code&gt;auth:sanctum&lt;/code&gt;, which indicates that any route within this group requires authentication using the Sanctum middleware.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;In the protected routes we have used the &lt;code&gt;-&amp;gt;middleware()&lt;/code&gt; method which assigns middleware to a specific route in Laravel. In the provided code,we have assigned to the route our custom  &lt;code&gt;restrictRole&lt;/code&gt; middleware which we created and registered to the &lt;code&gt;routeMiddleware&lt;/code&gt; array of the &lt;code&gt;kernel.php&lt;/code&gt; file.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;It checks if the authenticated user has any of the specified roles. If the user has one of the specified roles, the request continues to the route's controller or closure. If the user does not have any of the specified roles, the middleware will return a response indicating that the user is not authorized to access the route.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Since all this is clear now lets head over to our &lt;code&gt;AuthController&lt;/code&gt; and add functions &lt;code&gt;show&lt;/code&gt; and &lt;code&gt;update&lt;/code&gt; which have been used by the last two routes.&lt;br&gt;
In your &lt;code&gt;AuthController&lt;/code&gt; add this code:&lt;br&gt;
&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// You could basically write some functional code here to 
// perform these operations
public function show(){
return " All users are shown here";
}

public function update(Request $request , $id){
return " All updates on users are done here";
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;From here an admin could see all users and moderators could update them by their id.
Since we already have one default admin, you can now login and register other users(admin/moderators) and try to access the restricted endpoints.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Here is a sample registration and login requests.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;{
"username":"James",
"email": "jamie@gmail.com",
"password": "123456",
"password_confirmation": "123456",
"role" : "moderator",
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Login request&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;{
"username": "James",
"password": "123456"
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here you will create a moderator and after login the user can access the routes which he has authority to.&lt;/p&gt;

&lt;p&gt;That's all for today. Hope you got something from this one . Enjoy !!&lt;/p&gt;

</description>
      <category>api</category>
      <category>laravel</category>
      <category>webdev</category>
      <category>backend</category>
    </item>
    <item>
      <title>How to use Lordicon: The Best Animated Icon Library</title>
      <dc:creator>Patrick Lusaya</dc:creator>
      <pubDate>Thu, 06 Apr 2023 12:02:51 +0000</pubDate>
      <link>https://dev.to/patricklusaya/discovering-the-best-animated-icon-library-to-use-for-your-next-project-a-deep-dive-into-lordicon-3jb2</link>
      <guid>https://dev.to/patricklusaya/discovering-the-best-animated-icon-library-to-use-for-your-next-project-a-deep-dive-into-lordicon-3jb2</guid>
      <description>&lt;p&gt;As a developer, I understand the importance of icons in creating visually appealing and user-friendly websites and applications. However, with the multitude of icon libraries available, choosing the right one for my coding projects has always been a challenge. Every library comes with its unique features, styles, and customizations, and selecting the wrong one can result in a poor user experience or a project that doesn't meet the desired outcome. &lt;/p&gt;

&lt;p&gt;If you've ever faced this dilemma, then you know how time-consuming and frustrating the process of choosing an icon library can be. But fear not! In this article, I'll share my experience using Lordicon, a versatile and widely used icon library, to help you make an informed decision for your next coding project.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fsu753y3n9jd7yybtcsvb.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fsu753y3n9jd7yybtcsvb.gif" alt="Animated Icon By Lordicon" width="400" height="400"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;code&gt;Lordicon&lt;/code&gt; is a library of well-crafted animated icons that are ready for use in various digital products, presentations, or videos. With thousands of free and premium icons available in six different styles, Lordicon offers a wide range of options to suit various design needs.&lt;/p&gt;

&lt;p&gt;What i like most about this library is that it has a lot of customization options that allows you to adjust colors, stroke width, animation speed and many other to match your project's specific design requirements.&lt;/p&gt;

&lt;p&gt;Icons are of six styles. &lt;code&gt;Wired lineal, wired flat, wired outline, wired gradient, system outline and system solid&lt;/code&gt;. The Wired styles offer a more modern, sleek appearance, while the System styles have a more traditional, familiar look that may suit some projects better.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fokjazx899d9zkfzrx5j7.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fokjazx899d9zkfzrx5j7.jpg" alt="Image description" width="800" height="210"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fivku7pw9cb2953h78ba2.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fivku7pw9cb2953h78ba2.jpg" alt="Image description" width="800" height="190"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Its pretty simple to get an animated icon here, simply click on the Icons link, then select the type of style you want to use. At the top left you can select either premium or free icons.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fx2gjuvziy0bcytcsro8r.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fx2gjuvziy0bcytcsro8r.jpg" alt="Image description" width="800" height="372"&gt;&lt;/a&gt; &lt;/p&gt;

&lt;p&gt;Once you have selected an icon, you can modify it according to the many options available. With Lordicon's customization options, you can select the size you want, the type of animation motion, and the colors, scale, stroke width, and media type that fit your specific design needs. This level of customization allows you to create icons that truly match the aesthetic and functional requirements of your project.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fft30bh7xjmevfrg5syrk.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fft30bh7xjmevfrg5syrk.jpg" alt="Image description" width="800" height="308"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Customization is a key feature of the library, and it extends to the animation of the icons as well. When you select an animation format, you can further customize it by choosing to set a background color or leave it transparent, adjusting the size of the animation, and selecting the delay between animation loops.&lt;/p&gt;

&lt;p&gt;This level of control over the animation ensures that you can create the perfect animated icon for your project, and that it fits seamlessly into your website or app's design. Moreover, the customization process is simple and easy to use, even for those who are not animation experts.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fqcewyfqzcndcpdv06az8.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fqcewyfqzcndcpdv06az8.jpg" alt="Image description" width="755" height="447"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;By clicking the download button you will have your well crafted animated icon.&lt;/p&gt;

&lt;p&gt;In conclusion, Lordicon provides a versatile tool for designers, developers, and content creators alike. Whether you are looking to spruce up your website, create engaging presentations, or add a professional touch to your videos, Lordicon is a fantastic choice. So why not give Lordicon a try and see how it can take your design to the next level?&lt;/p&gt;

&lt;p&gt;Thank you for reading, and I hope you found this article helpful in understanding the many features and benefits of Lordicon. Have a great day!&lt;/p&gt;

</description>
      <category>icons</category>
      <category>ux</category>
      <category>animations</category>
      <category>design</category>
    </item>
    <item>
      <title>Create a Laravel CRUD Restful API and Secure it with Sanctum</title>
      <dc:creator>Patrick Lusaya</dc:creator>
      <pubDate>Sun, 02 Apr 2023 11:17:47 +0000</pubDate>
      <link>https://dev.to/patricklusaya/create-a-laravel-crud-restful-api-and-secure-it-with-sanctum-3p2j</link>
      <guid>https://dev.to/patricklusaya/create-a-laravel-crud-restful-api-and-secure-it-with-sanctum-3p2j</guid>
      <description>&lt;p&gt;&lt;strong&gt;Introducton&lt;/strong&gt;&lt;br&gt;
Laravel is a popular PHP framework that allows developers to build web applications quickly and efficiently. One of the most common use cases for Laravel is to create a RESTful API that can be used to communicate with other applications or services. In this tutorial, we'll show you how to build a Laravel CRUD RESTful API and secure it with Sanctum.&lt;/p&gt;

&lt;p&gt;Sanctum is a Laravel package that provides a simple way to authenticate API requests using tokens. It works by creating a token for each authenticated user, which can then be used to make subsequent requests to the API. This makes it easy to secure your API and ensure that only authorized users have access to sensitive data. In this tutorial, we'll use Sanctum to secure our Laravel API and protect it from unauthorized access.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Prerequisites&lt;/strong&gt;&lt;br&gt;
Before we start, make sure you have the following:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Laravel installed on your machine&lt;/li&gt;
&lt;li&gt;A basic understanding of Laravel&lt;/li&gt;
&lt;li&gt;A code editor of your choice&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Step 1: Set Up Laravel&lt;/strong&gt;&lt;br&gt;
First, we'll create a new Laravel project. Open your terminal or command prompt and enter the following command: &lt;code&gt;composer create-project laravel/laravel my-api&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 2: Set Up Database&lt;/strong&gt;&lt;br&gt;
Next, we need to set up our database. In this tutorial i will be using PostgreSql but you can use any database that you are comfortable with. Head over to your database console and create a database by writing the command &lt;code&gt;CREATE DATABASE laravelapi&lt;/code&gt;. Open the .env file in the root of your project and update the following lines with your database credentials:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;DB_CONNECTION=pgsql //fill according to your database
DB_HOST=127.0.0.1
DB_PORT=5432 // //fill according to your database
DB_DATABASE=laravelapi
DB_USERNAME=yourusername
DB_PASSWORD=yourpassword
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Step 4: Create the Model and Migration&lt;/strong&gt;&lt;br&gt;
In Laravel, a model is a class that represents a database table. It provides an easy way to interact with the database by providing methods for querying and manipulating the table data.&lt;/p&gt;

&lt;p&gt;A migration, on the other hand, is a PHP file that defines the changes to be made to the database schema. It provides a simple way to create, update or delete database tables, columns, indexes, and other database-related entities.&lt;/p&gt;

&lt;p&gt;So, we will create a &lt;code&gt;Product&lt;/code&gt; Model and its migration. The migration file contains the necessary code to create the Product table with the &lt;code&gt;id&lt;/code&gt;, &lt;code&gt;name&lt;/code&gt;, &lt;code&gt;description&lt;/code&gt;, &lt;code&gt;slug&lt;/code&gt; ,&lt;code&gt;price&lt;/code&gt;and &lt;code&gt;timestamps&lt;/code&gt; columns.&lt;/p&gt;

&lt;p&gt;To do this, write the following command on your project root directory: &lt;code&gt;php artisan make:model Product --migration&lt;/code&gt;. Now head over to the database/migration folder and open up the file  &lt;code&gt;create_products_table&lt;/code&gt;. Now inside this file you will notice the &lt;code&gt;up&lt;/code&gt; and &lt;code&gt;down&lt;/code&gt; functions.&lt;/p&gt;

&lt;p&gt;When we run a migration using the &lt;code&gt;php artisan migrate&lt;/code&gt; command, Laravel will execute the up function to apply the changes defined in the migration. If we need to undo those changes later, we can run the &lt;code&gt;php artisan migrate:rollback&lt;/code&gt; command, which will execute the down function to undo the changes made by the migration.&lt;/p&gt;

&lt;p&gt;Inside, the up function add the code:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Schema::create('products', function (Blueprint $table) {
            $table-&amp;gt;id();
            $table-&amp;gt;string('name');
            $table-&amp;gt;string('description')-&amp;gt;nullable();
            $table-&amp;gt;string('slug');
            $table-&amp;gt;decimal('price', 5,2);
            $table-&amp;gt;timestamps();
        });
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here's a breakdown of what each line does:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;Schema::create('products', function (Blueprint $table)&lt;/code&gt; starts the process of creating a new database table called products. The function (Blueprint $table) is a callback that defines the columns and their data types.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;$table-&amp;gt;id();&lt;/code&gt; creates an auto-incrementing id column, which serves as the primary key for the products table.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;$table-&amp;gt;string('name')&lt;/code&gt;; creates a name column of type string.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;$table-&amp;gt;string('description')-&amp;gt;nullable()&lt;/code&gt;; creates a description column of type string that can be nullable (i.e. it can have a null value).&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;$table-&amp;gt;string('slug')&lt;/code&gt;; creates a slug column of type string.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;$table-&amp;gt;decimal('price', 5,2)&lt;/code&gt;; creates a price column of type decimal with 5 total digits and 2 decimal places.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;$table-&amp;gt;timestamps()&lt;/code&gt;; creates two columns, created_at and updated_at, which are used to track the creation and modification timestamps of each row in the products table.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Overall, this code creates a products table with five columns: id, name, description, slug, and price, along with the two timestamp columns.&lt;/p&gt;

&lt;p&gt;On Your Product Model class add this code:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;protected $fillable = [
    'name',
    'slug',
     'price',
     'description'
    ];
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In Laravel, the &lt;code&gt;$fillable&lt;/code&gt; property is used to specify which attributes of a model are allowed to be mass-assigned. Mass assignment is a convenient way to create or update multiple model instances at once using an array of data.&lt;/p&gt;

&lt;p&gt;By setting these attributes in the &lt;code&gt;$fillable&lt;/code&gt; array, we're telling Laravel that it's safe to mass-assign these attributes using an array of data. This is an important security measure that prevents malicious users from assigning arbitrary attributes to our model, which could potentially compromise our application.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 5: Create the Controller&lt;/strong&gt;&lt;br&gt;
Next, let's create a controller to handle our API requests. The primary responsibility of a controller is to receive requests from the client and perform the necessary actions to generate a response. This includes retrieving data from the database, processing data, and rendering views. Run the following command to create a controller : &lt;code&gt;php artisan make:controller ProductController&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 6: Add API Methods to the Controller&lt;/strong&gt;&lt;br&gt;
Now, let's add the methods to the controller that will handle the CRUD operations for our API. Open the ProductController.php file and add the following code:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;* @return \Illuminate\Http\Response
     */
    public function index()
    {
        return Product::all();
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This &lt;code&gt;index&lt;/code&gt; function  uses the predefined method  &lt;code&gt;all()&lt;/code&gt; onto the &lt;code&gt;Product&lt;/code&gt; Model to find all products&lt;/p&gt;

&lt;p&gt;Then, add this code:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;* @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {

        $request -&amp;gt; validate(
           [ 'name' =&amp;gt; 'required',  'slug' =&amp;gt; 'required',
             'description' =&amp;gt; 'required' ,  'price' =&amp;gt; 
             'required'
           ]
        );
        return Products::create($request-&amp;gt;all());
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here, the &lt;code&gt;store&lt;/code&gt; method provides a way to create a new product in the database based on input data from the client, while also validating the input data to ensure that it meets certain requirements.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;public function store(Request $request)&lt;/code&gt;: This is the method definition. The public keyword indicates that the method can be accessed from outside the class, and store is the name of the method. The $request parameter is an instance of the Request class, which contains data from the HTTP request.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;$request -&amp;gt; validate([ 'name' =&amp;gt; 'required', 'slug' =&amp;gt; 'required', 'description' =&amp;gt; 'required' , 'price' =&amp;gt; 'required' ]);&lt;/code&gt;: This line uses the validate method on the $request object to validate the input data from the client. In this case, the validation rules require the name, slug, description, and price fields to be present and not empty.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;return Products::create($request-&amp;gt;all());&lt;/code&gt;: This line creates a new product in the database using the create method on the Products model. The create method creates a new instance of the Products model using the input data from the client, and saves it to the database. The all() method on the $request object returns an array of all input data from the client.&lt;/p&gt;

&lt;p&gt;After that, add the following code to find Product by Id, Delete Product by ID and Update Product by ID:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;* @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        return Products::find($id);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)

    {
        $product = Products::find($id);
        $product-&amp;gt;update($request-&amp;gt;all());
        return $product;
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
       return Products::destroy($id);
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The &lt;code&gt;show&lt;/code&gt; function retrieves a product by its ID, the &lt;code&gt;update&lt;/code&gt; function updates a product by its ID, and the &lt;code&gt;destroy&lt;/code&gt; function deletes a product by its ID. Each of these functions returns an HTTP response that can be handled by a client-side application or another API.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 6: Create the public API Routes&lt;/strong&gt;&lt;br&gt;
Now, let's create the routes for our API. Open the routes/api.php file and add the following code:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;//these are public routes
Route:: get('/products',[ProductController::class,'index']);
Route:: get('/products/{id}',[ProductController::class,'show']);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The first line defines a &lt;code&gt;GET&lt;/code&gt; route for the &lt;code&gt;index&lt;/code&gt;method of the &lt;code&gt;ProductController&lt;/code&gt; class. This route is accessible at the "/products" endpoint and will return a list of all products. &lt;/p&gt;

&lt;p&gt;The second  line defines a GET route for the "show" method of the &lt;code&gt;ProductController&lt;/code&gt; class that expects an "id" parameter. This route is accessible at the "/products/{id}" endpoint and will return a single product with the specified ID.&lt;/p&gt;

&lt;p&gt;Now, to secure some of our endpoint we will use &lt;code&gt;Sanctum&lt;/code&gt;. We want that for a user to create, update and delete a product he must be authenticated. Before anything else lets do a quick setup  of Sanctum in your project.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Install laravel Sanctum via composer using the command: &lt;code&gt;composer require laravel/sanctum&lt;/code&gt;
&lt;/li&gt;
&lt;li&gt;Next, you should publish the Sanctum configuration and migration files using the command: &lt;code&gt;php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider"&lt;/code&gt;. This will create a table create_accesss_tokens in your database.&lt;/li&gt;
&lt;li&gt;Migrate using the command &lt;code&gt;php artisan migrate&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;Now,you should add Sanctum's middleware to your api middleware group within your application's &lt;code&gt;app/Http/Kernel.php&lt;/code&gt; file: Within the &lt;code&gt;middlewareGroups&lt;/code&gt; array replace the second element of the array with following code :
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt; 'api' =&amp;gt; [
            \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
            \Illuminate\Routing\Middleware\ThrottleRequests::class.':api',
           \Illuminate\Routing\Middleware\SubstituteBindings::class,
         ],
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Step 7: Create User Model and Migration&lt;/strong&gt; &lt;br&gt;
We need to have users who can be authenticated before accessing the  secure endpoints. On your project's root directory run the command: &lt;code&gt;php artisan make:model User --migration&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Head over the migration folder, open the create_users_table file, and within its up function paste the following code:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Schema::create('users', function (Blueprint $table) {
            $table-&amp;gt;id();
            $table-&amp;gt;string('name');
            $table-&amp;gt;string('email')-&amp;gt;unique();
            $table-&amp;gt;timestamp('email_verified_at')-&amp;gt;nullable();
            $table-&amp;gt;string('password');
            $table-&amp;gt;rememberToken();
            $table-&amp;gt;timestamps();
        });
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This will create a users table with columns id, name, email, password, tokens and timestamps.&lt;br&gt;
Now within the User Model class add :&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;protected $fillable = [
        'name',
        'email',
        'password',
    ];
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Then run the command &lt;code&gt;php artisan migrate&lt;/code&gt; to create the users table in your database.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 8: Create AuthController&lt;/strong&gt;&lt;br&gt;
The Authcontroller will handle the login, register and logout logic.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Register logic
To register user add the following code in your controller:
&lt;/li&gt;
&lt;/ul&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public function register(Request $request)
    {
$fields= $request-&amp;gt;validate(
    [
        'name'=&amp;gt; 'required |string',
        'email' =&amp;gt; 'required |unique:users',
        'password'=&amp;gt; 'required|confirmed'
    ]
    );
    $user = User::create([
        'name'=&amp;gt;$fields['name'],
        'email'=&amp;gt;$fields['email'],
        'password'=&amp;gt; bcrypt($fields['password'])
    ]);
    $token = $user-&amp;gt;createToken('mytoken')-&amp;gt;plainTextToken;
    $response =  [
        'user'=&amp;gt; $user,
        'token'=&amp;gt;$token

    ];
    return response($response, 201);

    }

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;Code Explanation&lt;br&gt;
The register function accepts a HTTP request object as a parameter, which is used to validate the user's input fields. The method then creates a new user in the database with the validated input fields and hashes the user's password using the bcrypt function. &lt;/p&gt;

&lt;p&gt;The user is then assigned a token using Laravel's built-in Sanctum package, which is returned along with the user's details in a response object with a status code of 201.&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;createToken&lt;/code&gt; method is called on the authenticated user object and takes a string argument that serves as a name for the token. In this case, the name is &lt;code&gt;mytoken&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;plainTextToken&lt;/code&gt; method is then called on the returned token object to retrieve the plain text version of the token. This token can be used for subsequent requests that require user authentication.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Login Logic
This almost the same as register only that some few things differ. Add the following code to your &lt;code&gt;AuthController&lt;/code&gt;:
&lt;/li&gt;
&lt;/ul&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public function login(Request $request)
    {
$fields= $request-&amp;gt;validate(
    [

        'email' =&amp;gt; 'required ',
        'password'=&amp;gt; 'required'
    ]
    );
    $user = User::where('email', $fields['email'])-&amp;gt;first();

    if (!$user|| !Hash::check($fields['password'], $user-&amp;gt;password)) {

        return response(
            [
                'message' =&amp;gt; 'Bad creds'
            ]
            );
        # code...
    }
    $token = $user-&amp;gt;createToken('mytoken')-&amp;gt;plainTextToken;
    $response =  [
        'user'=&amp;gt; $user,
        'token'=&amp;gt;$token

    ];
    return response($response, 201);

    }

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;Code Explanation &lt;br&gt;
The function It takes in a POST request with the email and password fields validated. It then checks if a user with the provided email exists in the database and whether the password provided matches the hashed password in the database using the Hash facade provided by Laravel.&lt;/p&gt;

&lt;p&gt;If the user is not found or the password doesn't match, it returns a response with a message indicating bad credentials. If the user is found and the password matches, it generates a token for the user and returns a response with the user details and the token. The token can be used to authenticate subsequent requests to the server.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Logout Logic
Add:
&lt;/li&gt;
&lt;/ul&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public function logout(Request $request){
        $request-&amp;gt;user()-&amp;gt;token()-&amp;gt;delete();
       return [
        'message' =&amp;gt; 'logged out'
       ];
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;This retrieves the authenticated user using $request-&amp;gt;user() and then deletes the user's token using the delete() method&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 9: Created the protected API Routes&lt;/strong&gt;&lt;br&gt;
A user must be authenticated to access these routes. Add the following code to &lt;code&gt;routes.api.php&lt;/code&gt; file:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// protected routes
Route::group(['middleware'=&amp;gt; ['auth:sanctum']], function(){
    Route::post('/products',[ProductController::class,'store']);
    Route::put('/products/{id}',[ProductController::class,'update']);
    Route::delete('/products/{id}',[ProductController::class,'destroy']);
    Route::post('/logout',[AuthController::class,'logout']);

});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;Route::group()&lt;/code&gt; is a function that allows you to group multiple routes that share a common middleware. In this case, the middleware specified is &lt;code&gt;auth:sanctum&lt;/code&gt;, which is used to protect the routes in the group and restrict access to authenticated users only.&lt;/p&gt;

&lt;p&gt;When a user tries to access any route within the group, the &lt;code&gt;auth:sanctum&lt;/code&gt; middleware will check if the user is authenticated by checking for the presence of a valid access token. If the user is not authenticated, they will be redirected to the login page or will receive an HTTP 401 Unauthorized status code.&lt;/p&gt;

&lt;p&gt;By wrapping a set of routes within a &lt;code&gt;Route::group()&lt;/code&gt;function with the specified middleware, it ensures that those routes are only accessible to authenticated users who have a valid access token.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 10: Test your endpoints with &lt;code&gt;postman&lt;/code&gt;&lt;/strong&gt;&lt;br&gt;
Head over to &lt;a href="//postman.com"&gt;Postman&lt;/a&gt; and test your endpoints. But first start your server by using the command  &lt;code&gt;php artisan serve&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Since, there are no products in our database, lets first register a user to do so.&lt;br&gt;
Use the endpoint &lt;code&gt;http://localhost:8000/api/register&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fc3rv8e2l04vwswursm00.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fc3rv8e2l04vwswursm00.jpg" alt="Post request to register user " width="800" height="344"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fpy9qa54r6fawlqdjsrpn.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fpy9qa54r6fawlqdjsrpn.jpg" alt="Response" width="800" height="263"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;To Login use the endpoint &lt;code&gt;http://localhost:8000/api/login&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ftp5x7kc6u4eikjcxmvw2.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ftp5x7kc6u4eikjcxmvw2.jpg" alt="Image description" width="800" height="316"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The response will have an authentication token that will be used to access protected routes.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ftlfauzytw34i22l01yud.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ftlfauzytw34i22l01yud.jpg" alt="Image description" width="800" height="282"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Access protected routes after Authentication&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fyn12g55k2jy96g9njp5o.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fyn12g55k2jy96g9njp5o.jpg" alt="Image description" width="800" height="346"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Access protected routes without Authentication&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fz43hjpuyqk6oky84amca.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fz43hjpuyqk6oky84amca.jpg" alt="Image description" width="800" height="172"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Up to that point you can perform all the CRUD operations using the RESTful API you just created .&lt;/p&gt;

&lt;p&gt;Here is a complete code of all we have done &lt;/p&gt;

&lt;p&gt;&lt;code&gt;Product Model&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Product extends Model
{
    use HasFactory;
    protected $fillable = [
    'name',
    'slug',
     'price',
     'description'
    ];
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;User Model&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;?php

namespace App\Models;

// use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;

class User extends Authenticatable
{
    use HasApiTokens, HasFactory, Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array&amp;lt;int, string&amp;gt;
     */
    protected $fillable = [
        'name',
        'email',
        'password',
    ];

    /**
     * The attributes that should be hidden for serialization.
     *
     * @var array&amp;lt;int, string&amp;gt;
     */
    protected $hidden = [
        'password',
        'remember_token',
    ];

    /**
     * The attributes that should be cast.
     *
     * @var array&amp;lt;string, string&amp;gt;
     */
    protected $casts = [
        'email_verified_at' =&amp;gt; 'datetime',
    ];
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;ProductController&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;?php

namespace App\Http\Controllers;

use App\Models\Products;
use Illuminate\Http\Request;

class ProductController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        return Products::all();
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {

        $request -&amp;gt; validate(
           [ 'name' =&amp;gt; 'required',  'slug' =&amp;gt; 'required',
           'description' =&amp;gt; 'required' ,  'price' =&amp;gt; 'required'
           ]
        );
        return Products::create($request-&amp;gt;all());
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        return Products::find($id);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)

    {
        $product = Products::find($id);
        $product-&amp;gt;update($request-&amp;gt;all());
        return $product;
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
       return Products::destroy($id);
    }

}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;AuthController&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;?php

namespace App\Http\Controllers;

use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;

class AuthController extends Controller
{
    public function register(Request $request)
    {
$fields= $request-&amp;gt;validate(
    [
        'name'=&amp;gt; 'required |string',
        'email' =&amp;gt; 'required |unique:users',
        'password'=&amp;gt; 'required|confirmed'
    ]
    );
    $user = User::create([
        'name'=&amp;gt;$fields['name'],
        'email'=&amp;gt;$fields['email'],
        'password'=&amp;gt; bcrypt($fields['password'])
    ]);
    $token = $user-&amp;gt;createToken('mytoken')-&amp;gt;plainTextToken;
    $response =  [
        'user'=&amp;gt; $user,
        'token'=&amp;gt;$token

    ];
    return response($response, 201);

    }

    public function login(Request $request)
    {
$fields= $request-&amp;gt;validate(
    [

        'email' =&amp;gt; 'required ',
        'password'=&amp;gt; 'required'
    ]
    );
    $user = User::where('email', $fields['email'])-&amp;gt;first();

    if (!$user|| !Hash::check($fields['password'], $user-&amp;gt;password)) {

        return response(
            [
                'message' =&amp;gt; 'Bad creds'
            ]
            );
        # code...
    }
    $token = $user-&amp;gt;createToken('mytoken')-&amp;gt;plainTextToken;
    $response =  [
        'user'=&amp;gt; $user,
        'token'=&amp;gt;$token

    ];
    return response($response, 201);

    }

    public function logout(Request $request){
        $request-&amp;gt;user()-&amp;gt;token()-&amp;gt;delete();
        return response(null, 204);
    }
}


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;api.php&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;?php

use App\Http\Controllers\AuthController;
use App\Http\Controllers\ProductController;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use Laravel\Sanctum\Sanctum;

/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/


// Route::resource('products', ProductController::class);

// public routes
Route:: post('/register',[AuthController::class,'register']);
Route:: get('/products',[ProductController::class,'index']);
Route:: get('/products/{id}',[ProductController::class,'show']);
Route:: post('/login',[AuthController::class,'login']);

// protected routes
Route::group(['middleware'=&amp;gt; ['auth:sanctum']], function(){
    Route::post('/products',[ProductController::class,'store']);
    Route::put('/products/{id}',[ProductController::class,'update']);
    Route::delete('/products/{id}',[ProductController::class,'destroy']);
    Route::post('/logout',[AuthController::class,'logout']);

});
Route::middleware('auth:sanctum')-&amp;gt;get('/user', function (Request $request) {
    return $request-&amp;gt;user();
});

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Conclusion&lt;/strong&gt;&lt;br&gt;
In this tutorial, we covered the basics of building a RESTful API with Laravel and Sanctum. We started by setting up our Laravel project and database, creating migration files, and defining our models and controllers. We also discussed how to handle requests and responses, including creating, retrieving, updating, and deleting resources. We explored the use of middleware for authentication and authorization, and how to create and use access tokens with Sanctum. &lt;/p&gt;

&lt;p&gt;Overall, this tutorial provided a solid foundation for building a robust and secure API with Laravel and Sanctum.&lt;/p&gt;

&lt;p&gt;That's all, Enjoy!&lt;/p&gt;

</description>
      <category>laravel</category>
      <category>postgres</category>
      <category>api</category>
      <category>sanctum</category>
    </item>
    <item>
      <title>Create a pie chart using Angular and Springboot</title>
      <dc:creator>Patrick Lusaya</dc:creator>
      <pubDate>Sat, 24 Dec 2022 20:05:38 +0000</pubDate>
      <link>https://dev.to/patricklusaya/create-a-pie-chart-using-angular-and-springboot-1cpa</link>
      <guid>https://dev.to/patricklusaya/create-a-pie-chart-using-angular-and-springboot-1cpa</guid>
      <description>&lt;p&gt;&lt;strong&gt;Introduction&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;In this tutorial, we will learn how to create a pie chart in Angular using the ng2-charts library and retrieve data from a Springboot backend to populate the chart. The pie chart will display the number of patients in a hospital based on a particular visit type.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ff2mvf7irxqm6ddpd0pzs.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ff2mvf7irxqm6ddpd0pzs.jpg" alt="The image"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Prerequisites&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Basic knowledge of Angular and Springboot.&lt;/li&gt;
&lt;li&gt;Node.js and npm installed on your machine.&lt;/li&gt;
&lt;li&gt;Angular CLI installed on your machine.&lt;/li&gt;
&lt;li&gt;A PostgreSQL database set up and configured with Springboot.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Step 1: Set up the Angular project&lt;/strong&gt;&lt;br&gt;
First, let's create a new Angular project using the Angular CLI .Type the command  &lt;code&gt;ng new demoapp&lt;/code&gt; &lt;/p&gt;

&lt;p&gt;Next, install the &lt;code&gt;ng2-charts&lt;/code&gt; and &lt;code&gt;chart js&lt;/code&gt; libraries by running the following command: &lt;code&gt;npm install ng2-charts chart.js --save&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;This will install the latest version of both ng2-charts and Chart.js and save the dependencies in your &lt;code&gt;package.json&lt;/code&gt; file.&lt;/p&gt;

&lt;p&gt;Once the installation is complete, you can import the charts modules in your module where you want to use them. Here's an example of how you can do this:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

import { NgChartsModule } from 'ng2-charts';

@NgModule({
  imports: [
    NgChartsModule
  ],
  // ...
})
export class MyModule {}


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;Step 2: Create the an entity class in your backend.&lt;/strong&gt;&lt;br&gt;
In your backend code, create an entity class called Patient to represent a patient in the database. Here i'm assuming you have already set up your springboot application to any database. The Patient class should have fields for the patient's ID and visit type.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

@Entity
@Table(name = "patients")
public class Patient {
  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  private Long id;
  private String visitType;

  // Getters and setters

}


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;Step 3: Create the repository interface.&lt;/strong&gt;&lt;br&gt;
Next, create a repository interface that extends JpaRepository and define a method to find the number of patients in each visit type.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

public interface PatientRepository extends JpaRepository&amp;lt;Patient, Long&amp;gt; {

    @Query(value = "SELECT visit_type, COUNT(*) as count FROM patients GROUP BY visit_type", nativeQuery = true)
    List&amp;lt;Object[]&amp;gt; countByVisitType();
}


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;&lt;em&gt;Code explanation&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;This is an interface that extends the &lt;code&gt;JpaRepository&lt;/code&gt;interface and defines a custom method called &lt;code&gt;countByVisitType&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;JpaRepository&lt;/code&gt; interface is a Spring Data interface that provides basic CRUD (create, read, update, delete) operations for a given entity type. By extending this interface, the &lt;code&gt;PatientRepository&lt;/code&gt; interface is able to inherit these basic CRUD methods and use them to perform database operations on &lt;code&gt;Patient&lt;/code&gt; objects.&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;countByVisitType&lt;/code&gt; method is a custom method that has been defined in the &lt;code&gt;PatientRepository&lt;/code&gt; interface. It is annotated with &lt;code&gt;@Query&lt;/code&gt;, which allows you to specify a custom query to be executed when the method is called. &lt;/p&gt;

&lt;p&gt;The query in this case is &lt;code&gt;SELECT visit_type, COUNT(*) as count FROM patients GROUP BY visit_type&lt;/code&gt;, which selects the &lt;code&gt;visit_type&lt;/code&gt; column and the &lt;code&gt;count&lt;/code&gt; of patients for each &lt;code&gt;visit_type&lt;/code&gt; (&lt;code&gt;SELECT visit_type, COUNT(*) as count&lt;/code&gt;) from the patients table (FROM patients) and groups the results by &lt;code&gt;visit_type&lt;/code&gt; (GROUP BY visit_type).&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;nativeQuery = true&lt;/code&gt; attribute indicates that the query is a native SQL query rather than a &lt;code&gt;JPQL&lt;/code&gt; (Java Persistence Query Language) query.&lt;/p&gt;

&lt;p&gt;The method is returning a &lt;code&gt;List&amp;lt;Object[]&amp;gt;&lt;/code&gt; object, which is a list of arrays of objects. Each &lt;code&gt;Object[]&lt;/code&gt; object in the list represents a row in the result set returned by the query, with the first element being the &lt;code&gt;visit_type&lt;/code&gt;and the second element being the count of &lt;code&gt;patients&lt;/code&gt; for that type.&lt;/p&gt;

&lt;p&gt;When this method is called, it will execute the specified query and return a list of &lt;code&gt;Object[]&lt;/code&gt; objects representing the results of the query.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 4  Create the controller&lt;/strong&gt;&lt;br&gt;
In the controller, define an endpoint that returns the number of patients in each visit type as a JSON object with the visit type as the key and the number of patients as the value.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

@RestController
@RequestMapping("/api/test")
@AllArgsConstructor
public class TestController {
  @Autowired
    private  final PatientRepository patientRepository;
 @GetMapping("/home")
    public Map&amp;lt;String, BigInteger&amp;gt; countByVisitType() {
        Map&amp;lt;String, BigInteger&amp;gt; result = new HashMap&amp;lt;&amp;gt;();
        List&amp;lt;Object[]&amp;gt; counts = patientRepository.countByVisitType();
        for (Object[] row : counts) {
            result.put((String) row[0], (BigInteger) row[1]);
        }
        return result;
    }}


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;&lt;em&gt;Code explanation&lt;/em&gt; &lt;/p&gt;

&lt;p&gt;&lt;code&gt;@GetMapping("/home")&lt;/code&gt;, which means that it will handle HTTP GET requests to the &lt;code&gt;/home&lt;/code&gt; endpoint.&lt;/p&gt;

&lt;p&gt;The method returns a &lt;code&gt;Map&amp;lt;String, BigInteger&amp;gt;&lt;/code&gt; object, which is a map that maps string keys to &lt;code&gt;BigInteger&lt;/code&gt; values. The keys will represent the different types of visits, and the values will represent the number of patients that have visited for each type.&lt;/p&gt;

&lt;p&gt;The method first creates an empty &lt;code&gt;Map&lt;/code&gt; object called &lt;code&gt;result&lt;/code&gt; and then retrieves a List of &lt;code&gt;Object[]&lt;/code&gt; objects from the &lt;code&gt;patientRepository&lt;/code&gt; object. Each &lt;code&gt;Object[]&lt;/code&gt; object in the list represents a row in the result set returned by the repository's &lt;code&gt;countByVisitType()&lt;/code&gt; method, which is likely a custom method that returns the number of patients that have visited for each type of visit.&lt;/p&gt;

&lt;p&gt;The controller method then iterates over each &lt;code&gt;Object[]&lt;/code&gt; object in the list and adds an entry to the result map by casting the first element of the array to a &lt;code&gt;String&lt;/code&gt; (the type of visit) and the second element to a &lt;code&gt;BigInteger&lt;/code&gt;(the number of patients that have visited for that type of visit). Finally, the method returns the result map.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 5: Create the pie chart component in Angular&lt;/strong&gt;&lt;br&gt;
In the Angular project, create a Home component to display the pie chart.To do this run the command &lt;code&gt;ng g c home&lt;/code&gt; in your angular cli terminal. Then, declare properties &lt;code&gt;pieChartData&lt;/code&gt; and &lt;code&gt;pieChartLabels&lt;/code&gt;:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

export class HomeComponent implements OnInit {
  pieChartData!: ChartData&amp;lt;ChartType, number[], string&amp;gt;;
  pieChartLabels: string[] = [];
}


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;&lt;code&gt;pieChartData&lt;/code&gt;: This is a property of type &lt;code&gt;ChartData&amp;lt;ChartType, number[], string&amp;gt;&lt;/code&gt;, which is a type provided by the &lt;code&gt;Chart.js&lt;/code&gt; library.&lt;br&gt;
&lt;code&gt;ChartData&lt;/code&gt; represents the data for a chart, and is generic type that takes three type arguments:&lt;code&gt;ChartType&lt;/code&gt;(the type of chart), &lt;code&gt;number[]&lt;/code&gt; (the data), and &lt;code&gt;string&lt;/code&gt; (the labels). In this case, &lt;code&gt;pieChartData&lt;/code&gt; will be used to store the data for a pie chart.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;pieChartLabels&lt;/code&gt;: This is an array of strings that will be used to label the slices of the pie chart.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 6: Get the data from the api&lt;/strong&gt;&lt;br&gt;
Use http client to fetch data from your endpoint.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

...
constructor(private http : HttpClient){}
ngOnInIt(): void{
 this.http.get&amp;lt;any&amp;gt;('http://localhost:8080/api/test/home').subscribe(data =&amp;gt; {
    this.pieChartLabels = Object.keys(data);
    this.pieChartData = {
      labels: this.pieChartLabels,
      datasets: [
        {
          data: Object.values(data),
          backgroundColor: ['#FF6384', '#36A2EB', '#FFCE56' , 'grey'],
          hoverBackgroundColor: ['#FF6384', '#36A2EB', '#FFCE56' , 'grey'],
        },
      ],
    };
  });

}


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;The method &lt;code&gt;ngOnInIt&lt;/code&gt; makes an HTTP GET request to the &lt;code&gt;http://localhost:8080/api/test/home&lt;/code&gt; URL using the &lt;code&gt;HttpClient&lt;/code&gt; service, which is a service provided by Angular for making HTTP requests. The response from the server is expected to be an object with &lt;code&gt;string&lt;/code&gt; as keys and &lt;code&gt;BigInteger&lt;/code&gt; as values, and is stored in a variable called &lt;code&gt;data&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;The method then sets the &lt;code&gt;pieChartLabels&lt;/code&gt; property to the keys of the data object using the &lt;code&gt;Object.keys&lt;/code&gt; method, which returns an array of the keys of an object.&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;pieChartData&lt;/code&gt; property is then set to an object with the following structure:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;labels&lt;/code&gt;: An array of strings that will be used to label the slices of the pie chart. This is set to the &lt;code&gt;pieChartLabels&lt;/code&gt; property.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;datasets&lt;/code&gt;: An array of objects that represent the data for the chart. Each object in the array has the following properties:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;data&lt;/code&gt;: An array of numbers that represents the data for the chart. This is set to the values of the data object using the &lt;code&gt;Object.values&lt;/code&gt; method.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;backgroundColor&lt;/code&gt;: An array of strings that represents the background color for each slice of the pie chart.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;hoverBackgroundColor&lt;/code&gt;: An array of strings that represents the background color for each slice of the pie chart when the mouse is hovering over it.&lt;br&gt;
This &lt;code&gt;pieChartData&lt;/code&gt; object is then used to configure and display a pie chart using the Chart.js library.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 7: Display the pie chart in the template&lt;/strong&gt;&lt;br&gt;
Finally, we can display the pie chart in the template by using the baseChart directive from the &lt;code&gt;ng2-charts&lt;/code&gt; library.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

&amp;lt;div style="width: 440px; height: 440px;" &amp;gt;
       &amp;lt;canvas class="pie-chart"  baseChart  
          [data]="pieChartData"
          [labels]="pieChartLabels"
          [type]="'pie'" 
          &amp;gt;  
        &amp;lt;/canvas&amp;gt;
  &amp;lt;/div&amp;gt;


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Now run your springboot application and navigate to the Home component of your demoapp and a piechart will displayed.&lt;/p&gt;

&lt;p&gt;Here is the full HomeComponent class&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

export class HomeComponent implements OnInit {
  pieChartData!: ChartData&amp;lt;ChartType, number[], string&amp;gt;;
  pieChartLabels: string[] = [];
  constructor(private http : HttpClient)   { }
  ngOnInit(): void {
  this.http.get&amp;lt;any&amp;gt;('http://localhost:8080/api/test/home').subscribe(data =&amp;gt; {
    this.pieChartLabels = Object.keys(data); 
    this.pieChartData = {
      labels: this.pieChartLabels,
      datasets: [
        {
          data: Object.values(data),
          backgroundColor: ['#FF6384', '#36A2EB', '#FFCE56' , 'grey'],
          hoverBackgroundColor: ['#FF6384', '#36A2EB', '#FFCE56' , 'grey'],
        },
      ],
    };
  });

  }


  }




&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;Conclusion&lt;/strong&gt;&lt;br&gt;
In this tutorial, we learned how to create a pie chart in Angular using the ng2-charts library and retrieve data from a Springboot backend to populate the chart. We also learned how to create a repository interface and a controller to fetch the data and return it as a JSON object.&lt;/p&gt;

&lt;p&gt;I hope this tutorial was helpful. If you have any questions or comments, please let me know in the comments section below. Happy coding!&lt;/p&gt;

</description>
      <category>springboot</category>
      <category>webdev</category>
      <category>angular</category>
      <category>piechart</category>
    </item>
  </channel>
</rss>
