Category Archives: Blog

Blog

AngularJS User Registration Login Authentication Example

AngularJS User Registration Login Authentication Example

User authentication is very common in modern web application. User authentication is a security mechanism that is used to identify whether a user is someone who he claimed to be and to restrict unauthorized access to member only areas in a web application. In this tutorial we’ll show you how to create simple user registration and login system using angularjs. In our previous articles we have demonstrated you how to create simple user login in angularjs and how to create simple user registration in angularjs.

In this tutorial, we’ll guide you through the complete process of creating a user registration system where users can create an account by providing username, email and password, login and logout using Angularjs. We’ll also show you how you can make some pages accessible only to logged-in users. In this tutorial we will first create user registration form in angularjs, and then we’ll create user authentication or login form in angularjs, as well as a welcome page and a logout script.

Project’s Directory Structure :-

angularjs-user-authentication-registration-login-1

AngularJS Application Layout

Before starting with this tutorial we will create base layout i.e. index.html file where all our application views will be loaded. Let’s create index.html file and put the following code in it –

index.html

AngularJS Application

Every angular application starts from creating a angular module. Module is a container that holds the different parts of your application such as controllers, service, etc. In this step we will create a main javascript file app.js that will hold all the required configuration to run an angularjs application. We will also configure application routes in this file using AngularJS UI Router module. Let’s create app.js file and put the following code in it –

app.js

The app variable is initialized as angular module, notice that we have used ng-app directive in index.html file to bind the angular application to a container in base layout file. Now, we have created an app module and added ngRoute and ngCookies module for application routing and for storing user information in cookies. Here, we are using $routeProvider in config() function to configure our application routing. In routing configuration, every route you specify have a template file and a controller attached to it.

AngularJS Template and Controller

As you can see in routing configuration, every route you specify have a template and controller attached to it. Angularjs Template file holds all html that is being used to display route specific page. The angularjs controller hold the actual business logic attached with the route. In this step we will create separate template and controller files for user registration, login and home page respectively.

User Registration :-

In this step we’ll create a registration form that allows users to create a new account by filling out a web form. User Registration form will have First Name, Last Name, Username and Password along with Register and Cancel buttons. Let’s create a register.html file in your project’s root directory and put the following code in it –

register.html

Now, we’ll create registerController.js file and define our registration controller. Let’s create registerController.js file and put the following code in it –

registerController.js

Here, register() function is invoked when Register button is clicked. The register() function takes the user input and pass it to create() function in UserService. UserService will process the user input and respond back with either success or failure.

User Login :-

In this step we’ll create a simple login form having two input fields ( UserName and Password) along with a login button. Here, user will input their username and password and submit the login form using login button. As the login form is submitted it will call login() function from our login controller(loginController.js) which will further use Authentication Service(AuthenticationService.js) to authenticate user. if the user is authenticated successfully they will be redirected to a user home page using $location service. If authentication fails, the user is notified with an error message.

login.html

In this step we’ll create a simple login form that allows users login using their username and password. Let’s create a login.html file in your project’s root directory and put the following code in it –

Now, we’ll create loginController.js file and define our login controller. Let’s create loginController.js file and put the following code in it –

loginController.js

User Home :-

Once a user is successfully logged in the home page (home.html) will be loaded. Here, we have simple welcome message along with a list of registered users. Let’s create a home.html file in your project’s root directory and put the following code in it –

home.html

Now, we’ll create homeController.js file and define our home page controller. Let’s create homeController.js file and put the following code in it –

homeController.js

This will have loadCurrentUser() and loadAllUsers() functions to display currently logged in user details and to to display a list of all the registered users.

AngularJS Services

In this step, we will define angualrjs service for user authentication and to store and fetch user information form local storage.

Authentication Service :-

Here, we will create a authentication service(authenticationService.js) that will be used to authenticate user with login credentials provided and to set and clear user credentials from angularjs rootScope object. Let’s create authenticationService.js file and put the following code in it –

authenticationService.js

User Service :-

Next, we will create a user service(userService.svc.js) to store and fetch user details from the localStorage object. Let’s create userService.svc.js file and put the following code in it –

userService.svc.js

Fially, we will have css(style.css) file that will hold all the styling rules for our application/ Let’s create a style.css file and put the following code in it –

style.css

Run AngularJS Application

Now start the application server and visit the application to view the output.

Registration Page :-

angularjs-user-authentication-registration-login-2

Login Page :-

angularjs-user-authentication-registration-login-3

Home Page :-

angularjs-user-authentication-registration-login-4

Simple User Login Example in AngularJS

Simple User Login Example in AngularJS

In our previous article, we have learned how to create simple user registration form In AngularJS . Once a user is registered on the website can be obtain login credentials(username and password). In this article, we will learn how to to create simple login form in AngularJS. We will create a simple login page where user input their username and password, if the user is authenticated successfully they will be redirected to a user home page. If authentication fails, the user is notified with an error message.

Project’s Directory Structure :-

angularjs-simple-login-1

AngularJS Application Layout

Before starting with this tutorial we will create base layout i.e. index.html file where all our application views will be loaded. Let’s create index.html file and put the following code in it –

index.html

AngularJS Application

Every angular application starts from creating a angular module. Module is a container that holds the different parts of your application such as controllers, service, etc. In this step we will create a main javascript file app.js that will hold all the required configuration to run an angularjs application. We will also configure application routes in this file using AngularJS UI Router module. Let’s create app.js file and put the following code in it –

app.js

The app variable is initialized as angular module and named as “myApp”, notice that we have used ng-app directive in index.html file to bind the angular application to a container in base layout file. It is important to use the same module name to bind using ng-app directive.

AngularJS Routing

Since we are making a single page application and we don’t want any page refreshes. Here we have used Angular’s UI Routing capabilities to setup single page application.We are using ui.router module for that, notice that we have added ui.router as a part of the parameter passed to our angular module. The ui.router module provides routing, deeplinking services and directives to our angular applications. Here, we are using $urlRouteProvider in app.config to configure our application routing. As you can see in routing configuration, every route you specify have a template file and a controller attached to it.

AngularJS Template

Now, in this step we will create login and home page template files for our angularjs simple login application. Let’s create login.html and home.html files and put the following code in it respectively.

login.html

In login page, we have two input fields ( UserName and Password) with a login button.

home.html

Once a user is successfully logged in the home page (home.html) will be loaded. Here, we have simple welcome message along with a logout button.

AngularJS Controller

As you can see in routing configuration, every route you specify have a controller attached to it. Angularjs controller hold the actual business logic attached with the route. In this step we will create separate controller files for login page and home page. Let’s create loginController.js and homeController.js file and put the following code in it respectively.

loginController.js

homeController.js

AngularJS Services

Here, we will create a simple authentication service that authenticate user with default login credentials. As the user enters login credentials and clicks on the login button we authenticate the user and redirect them to user home page. We store the user data in angularjs scope object and binding it to the variable. If can also authenticate user with their registered credentials in database using a webservice or API that talks to database server. For now we will be creating a simple authentication service that authenticate user with default login credentials. Let’s create a loginService.js and put the following code in it –

loginService.js

Run AngularJS Application

Now start the application server and visit the application to view the output.

Login Page :-

angularjs-simple-login-2

Home Page :-

angularjs-simple-login-3

Simple User Registration Form Example in AngularJS

Simple User Registration Form in AngularJS

User Registration is very basic and common feature in modern web application. It is one of the basic and most important feature for a web application that is used to authenticate or restrict unauthorized access to member only areas and features in a web application. The user is required to register a account using the registration form provided on the application so the username and password is created in order to login in the application.

In this tutorial we’ll create a simple registration using AngularJS. In this tutorial, I’ll guide you through the step by step process to understand the User Registration in an AngularJS platform. This tutorial is comprised of two key components, in the first part we’ll create a user registration form, and in the second part we’ll list all the user.

Project Directory Structure :-

angularjs-simple-user-registration-form-1

Creating the Registration Form In AngularJS

In this step we’ll create a registration form that allows users to create a new account by filling out a web form. User Registration form will have Name, Email, Password and Phone as basic registration fields. Registration form will look like as following –

angularjs-simple-user-registration-form-2

Let’s create a index.html and app.js file in your project’s root directory and put the following code in it –

index.html

 

On top of the the form we have a link User List to list all the registered users. Right below the form, you have a list of registered users along with Edit/Delete button.

Create AngularJS Application

In this step, we will first create a javascript file app.js in our project’s root directory and define a AngularJS application. Let’s create app.js file and put the following code in it –

app.js

AngularJS Registration Service

Now we will create a registration service that will be used add, list, edit and delete users. Let’s open app.js file and append the following code in it –

AngularJS Registration Controller

Now we will create a registration controller that will be bind add, list, edit and delete action to registration service. Let’s open app.js file and append the following code in it –

app.js

Our final app.js file will look like as following –

app.js

Run AngularJS Application

Now start the application server and visit the application to view the output.

Output:-

angularjs-simple-user-registration-form-3

What Is Single Page Application In Angularjs?

What Is Single Page Application In Angularjs?

Single page application (SPA) is a web application that is contained in a single page. In a single page application all our code (JS, HTML, CSS) is loaded when application loads for the first time. Loading of the dynamic contents and the navigation between pages is done without refreshing the page. Single page application (SPA) is usually created using javascript based front-end web application framework.

What Is AngularJS?

AngularJS is one of the widely used front-end web application framework used for building Single Page Application (SPA). It extends the traditional HTML with new attributes and data-binding components that enable us to serve dynamic page content. In Our Next article, we’ll learn how to build a Single Page Application (SPA) using AngularJS Routing and AngularJS Template.

What Are Single Page Application Advantages (Pros)

Building any application as single page application will comes with significant number of benefits. In this article, we will talk about some of the key single page application advantages listed as below –

Improved User Experience :- Single page application bring a much-improved experience to the user.

No Page Refresh :- In a Single Page Application, there is no need to refresh the whole page for every request, all our code (JS, HTML, CSS) is loaded when application loads for the first time. Loading of the dynamic contents and the navigation between pages is done without refreshing the page.

Faster and Responsive :- Single Page Applications are faster because they require less bandwidth, and no full page refreshes when user navigates through the application.

Caching capabilities :- Single Page Applications comes with caching capabilities which allows it to cache any local data effectively. Single Page Application sends single request to server and then stores all the data it receives locally. Which it can use it and work even offline.

What Are Single Page Application Disadvantages (Cons)

While building single page application will comes with significant number of benefits. It also has some disadvantages that must be considered while building a single page application –

Javascript Must Be Enabled :- Single Page Application requires javascript to enabled. Fortunately, almost everyone has javascript enabled.

Initial load is slow :- All our code (JS, HTML, CSS) is loaded when application loads for the first time which cause it slow initially.

Complex to build :- You must have understanding of single page application architecture and front end technologies. It also requires you to have pretty much javascript knowledge for building single page applications.

Search Engine Optimization(SEO) :- Single Page Applications are not considered as much seo friendly. Fortunately, Google and Bing started indexing Single Page Applications.

Single Page Application (SPA) Architecture

Single Page Application with AngularJS Routing and Templating

Single Page Application with AngularJS Routing and Templating

AngularJS is a javascript based front-end web application framework, it is widely used for building Single Page Application (SPA). It extends the traditional HTML with new attributes and data-binding components that enable us to serve dynamic page content. In this article, we’ll learn how to build a Single Page Application (SPA) using AngularJS Routing and AngularJS Template.

How to Create Single Page Application Using AngularJS

Create Single Page Application Using AngularJS

AngularJS is an open source front-end web application framework based on javascript, it is widely used for building Single Page Application (SPA). It extends the traditional HTML with new attributes and data-binding components that enable us to serve dynamic page content. In this article, we’ll learn how to build a Single Page Application (SPA) using AngularJS and AngularJS Route library.

What Is Single Page Application?

AngularJS Single page application (SPA) is a web application that is contained in a single page. In a single page application all our code (JS, HTML, CSS) is loaded when application loads for the first time. Loading of the dynamic contents and the navigation between pages is done without refreshing the page.

Step 1:- This is the simple part. Here we will create a simple index.html file and add a simple layout with a navigation bar. We will also load angular and angular route library via CDN.

index.html

Step 2:-

Angular Application

Every angular application starts from creating a angular module. Module is a container that holds the different parts of your application such as controllers, service, etc. In this step we will create a simple javascript file script.js and put the following code in it to create our angular module.

script.js

The app variable is initialized as angular module and named as “myApp”, the ng-app directive is used to bind the angular application to a container. It is important to use the same module name to bind using ng-app directive.

Step 3:-

Configure Routes

Since we are making a single page application and we don’t want any page refreshes. Here we’ll use Angular’s routing capabilities to setup single page application.We will use ngRoute module for that. Notice that we have added ngRoute as a part of the parameter passed to our angular module. The ngRoute module provides routing, deeplinking services and directives to our angular applications. We will be using $routeProvider in app.config to configure our application routing. Let’s open our script.js file and put the following in it –

script.js

Now we have defined our routes with $routeProvider. As you can see by the configuration, you can specify the route, the template file to use, and even a controller.

AngularJS Template

Writing HTML code inside template is very constraining and to counter it one can use templateURL and instead of writing HTML code directly we specify the HTML file that will be injected corresponding to route. Now, we just need to define the page templates that will be injected.

about.html

services.html

projects.html

AngularJS View

To finish off with this tutorial, we need to specify the container where content of each page will be loaded in our layout. In AngularJS, there is a ng-view directive that will injects the template file of the current route (/about , /services or /projects) in the main layout file. Notice that we have added ng-view directive in main (index.html) layout file.

Now, start the server and visit the project. You will see following screen as output –

Output:-

angularjs-single-page-application-1

About Page:-

angularjs-single-page-application-2

Services Page :-

angularjs-single-page-application-3

Projects Page :-

angularjs-single-page-application-4

 

AngularJS CRUD With Php MySql REST API or Webservice Example

AngularJS CRUD With Php MySql REST API or Webservice

In this AngularJS CRUD with Php/MySql tutorial, I’ll show you how to create a simple AngularJS CRUD application with PHP/MySql REST API or Webservice . In this step by step tutorial, we will be creating a simple AngularJS SPA blog application with PHP/MySql restful API. In this article, you will learn how to create fully functional CRUD (Create, Read, Update and Delete) REST API using PHP/MySql and integrate it with AngularJS Single Page Application. So, you have to just follow this step by step angularJS crud application tutorial to create a fully functional angularjs blog application.

Projects Directory Structure :-

angularjs-crud-php-mysql-rest-api-webservices-1

Create Database Table and Configuration File

Step 1:- Create DB and Posts Table

In this step we will create a database and posts table in it. I have created a database with name “crudone” and created a “posts” table inside in it. So you also need to create a database with name of your choice and put “posts” table in it. You can create “posts” table using the mysql query given as following –

Step 2:- Create DB Config file

Now, we will create a database configuration file to hold database credentials and database connection. Let’s create db_config.php file in your project root directory and put the following code in it –

db_config.php

Step 3:- Create index.php file

Next, we will create index.php file in project root directory and put the following code in it –

index.php

Create PHP/MySql CRUD REST API

Now, after creating database and posts table in it we are ready to implement Restful CRUD (Create, Read, Update and Delete) API. We will create a separate api directory in our project folder to keep all API files in it like as below.

angularjs-crud-php-mysql-rest-api-webservices-2

now we will be creating separate files for each of the individual CRUD operation and put the given code accordingly.

api/add.php

This file holds the logic to add blog posts into the database.

api/edit.php

This file holds the logic to fetch and return a single blog post with given id for editing.

api/update.php

This file holds the logic to update blog posts with given id into the database.

api/getData.php

This file holds the logic to fetch and return all blog posts from the database.

api/delete.php

This file holds the logic to delete a single blog post from the database.

Create AngularJS CRUD Appilication

Now, after done with all the backend Rest Api we are ready to create frontend AngularJS CRUD application. We will creating a separate app directory in our project’s root directory to keep all AngularJS files in it like as below.

angularjs-crud-php-mysql-rest-api-webservices-3

Create AngularJS Routing File

So first we will create a routes.js file inside app folder to hold all of the application routing logic. Let’s create routes.js file and put bellow code in it.

app/routes.js

Create AngularJS Controller File

Now we will create a AngularJS controller file “app/controller/PostController.js” to hold CRUD Operation logic. We will create a separate controller directory in app folder and create PostController.js file in it and put the following code in it.

app/controller/PostController.js

Create AngularJS Helper File

Now we will create a AngularJS Helper file app/helper/myHelper.js to hold all helper function . We will create a separate helper directory in app folder to hold all helper functions in it. Let’s create myHelper.js file in “app/helper/” directory and put the following code in it.

app/helper/myHelper.js

Create AngularJS Template File

Finally we will create a template file. In AngularJS when we visit any angularjs route then it will output using one of the angularjs template file. We will create a separate template directory in app folder to hold all the project template files in it. Here we will create posts.html file in it and put the code given below for all the CRUD Operations.

templates/posts.html

Start Application

Lets start the application and visit it to see following output –

Output :-

angularjs-crud-php-mysql-rest-api-webservices-4

Create Post –

angularjs-crud-php-mysql-rest-api-webservices-5

List Posts –

angularjs-crud-php-mysql-rest-api-webservices-6

Edit Post –

angularjs-crud-php-mysql-rest-api-webservices-7

Update Post –

angularjs-crud-php-mysql-rest-api-webservices-8

Delete Post –

angularjs-crud-php-mysql-rest-api-webservices-9

Laravel 5.8 Multiple Authentication Using Middleware

Laravel 5.8 Multiple Authentication Using Middleware

In this Laravel multi (auth) authentication tutorial we will learn how to create separate admin panel or login using middleware. Laravel multi (auth) authentication system allows to create multiple users login in single application.

While developing a laravel application there comes situations where we want create separate user login or separate user/admin panel for users having different privileges or access rights in same application. In laravel this can be achieved in following ways –

1. Laravel multi (auth) authentication using middleware

2. Laravel multi (auth) authentication Using Guards

In one of my previous article we have created separate admin login using laravel multi (auth) authentication using Guards. In this article we will creating separate admin login using laravel multi (auth) authentication system with middleware.

Install Laravel 5.8

First of all we need to create a fresh laravel project, download and install Laravel 5.8 using the below command

Configure Database In .env file

Now, lets create a MySQL database and connect it with laravel application. After creating database we need to set database credential in application’s .env file.

Generate Application Key

Open terminal and switch to the project directory and run the following command to generate application key and configure cache.

Set Default String Length

Locate the file “app/Providers/AppServiceProvider”, and add following line of code to the top of the file

and inside the boot method set a default string length as given below –

So this is how “app/Providers/AppServiceProvider” file looks like –

Migrations and User Model

After installing laravel, you will see the some migration files created inside database/migrations directory for creating default create users table and password reset table. Open app/database/create_users_table.php migration file and add/update the following field for admin.

After you added a column “is_admin” to user table run the migration using following command.

After this, go to app/User.php and add is_admin to fillable attribute in the User Model.

Authentication Scaffolding

Laravel comes with in-built basic authentication system, use the below command to generate default authentication scaffolding –

This command will generate required Controller files, views and add routes in our web.php routes file that are required for basic authentication system.

Create Admin Middleware

Now, we will create a middleware that authenticate users. This middleware will help to make sure who can access the admin area or who can access the normal user area. Use the following command to generate a middleware for Admin.

Next, open app/Http/ Middleware/Admin.php file, and here in handle() method implement the logic to authenticate users like below.

Now, we need to register admin route in $routeMiddleware property in the app/Http/Kernel.php file. Lets open app/Http/Kernel.php file and update the $routeMiddleware property like below –

Set Admin Protected Route

Next, create the route for admin. Open the routes/web.php file and add the following code in it.

routes/web.php

Create Controller Methods

Open the app/Http/Controllers/HomeController.php controller file and create two separate methods to handle admin and normal users.

app/Http/Controllers/HomeController.php

Create Blade/View

Now we will have two separate view files, first is for home page and second is for after login admin page. Open the resources/views/home.blade.php file and update the following code.

resources/views/home.blade.php

Here, if(auth()->user()->is_admin == 1) is used to check user is a normal user or an admin user, it will navigate to the admin area. Otherwise, it will redirect to users area.

Now, create a view file called admin.blade.php in the root of the views folder, and add the following code to it.

resources/views/admin.blade.php

Start Development Server

Start the development server using following artisan command –

In order to test laravel multi auth system first register a user through laravel register and then change the is_admin=1; and try to login again.

User Home 1 :-

laravel-multi-auth-2

After Login Admin Page :-

laravel-multi-auth-1

User Home 2 :-

laravel-multi-auth-3

How to Ban, Suspend or Block User Account in Laravel

How to Ban, Suspend or Block User Account in Laravel

In this laravel ban / suspend user account tutorial, I’ll show you how to ban, block or suspend a user account using laravel middleware.

Sometimes in laravel application we may identify user account with some suspicious activity, policy violation, spamming or any other misuse of the application. In such situation we may want to ban, block or suspend a user account for some time, after that ban is revoked. when a blocked user account’s ban is revoked it can use the application same as before the account is suspended or banned

In this tutorial, you will learn to ban, block or suspend a user account using laravel middleware. In this example, we will create a laravel middleware to check if the user is banned. In this example we will add a database field named blocked_until in users table then we will check user is suspend/banned or not using the blocked_until field. If an user is found banned or blocked we log them out and redirect back to login page with an error message.

Before starting with tutorial, we are assuming that you already have a fresh installation of a Laravel 5.8. If you have not installed it follow Laravel Installation Step.

Install Laravel 5.8

First of all we need to create a fresh laravel project, download and install Laravel 5.8 using the below command

Configure Database In .env file

Now, lets create a MySQL database and connect it with laravel application. After creating database we need to set database credential in application’s .env file.

Now, use the below command to create default laravel tables automatically.

Authentication Scaffolding

Now, use the below command to generate laravel default authentication scaffolding –

This command will generate required Controller files, views and add routes in our web.php routes file that are required for the authentication.

Add New column Using Migration

Now, lets a add a timestamp field named blocked_until that allows you check if user is banned or not. If its null then user is not banned, otherwise we know the date, until when user is banned. Use the following artisan command to generate laravel migration that adds blocked_until field to users table.

Once this command is executed you will find a migration file created under “database/migrations”. lets open migration file and modify up method with following code –

We also need to add that field to $fillable array in app/User.php model. We will put it into $dates array to.

app/User.php

Create Laravel Middleware CheckBlocked

Lets create a laravel middleware to check if the user is banned/suspended/blocked. If a blocked user will try to login we log them out and redirect back to login form with an error message. Create a laravel middleware using below command.

Once this command is executed you will find a middleware file created under “app/Http/Middleware/”. Open middleware file and implement logic of to check banned/blocked/suspended users. In that time, we will log them out and redirect to login screen with message.

app/http/middleware/CheckBlocked.php

Register Laravel Middleware

Open app/Http/Kernel.php file and register CheckBlocked middleware here, like below –

Add Error Message

Finally, we need to add a error message in login.blade.php. let’s open app/resources/views/auth/login.blade.php file and add error message on above of login form body, like below –

Now we are ready to run our example so lets start the development server using following artisan command –

Now, open the following URL in browser and try to login with blocked or suspended user account to see the output –

http://localhost:8000/login

Output:-

laravel-ban-user-account-1

Laravel 5.8 Passport Authentication | Create REST API with Passport authentication

Laravel 5.8 Create REST API with Passport Authentication

In one of my previous articles, we have learn How to Create REST API With JWT Authentication In Laravel using Laravel JWT package for REST authentication API. In this article, we will learn to create fully functional restful API with Passport Authentication in Laravel. In this tutorial, we will be creating fully functional CRUD APIs for Blog Posts along with Passport Authentication In laravel.

What is Passport Authentication?

Laravel comes with default login authentication, but when we want to create APIs we have to use tokens instead of sessions for authenticating users, as APIs does not support session variables. After login via API, user must be assigned a token and sent back to the user which is further used for authenticating API requests. Authentication token is used to securely transmit data between third-parties. Laravel provides Passport authentication which makes it easy creating REST APIs in laravel.

Install Laravel 5.8

First of all we need to create a fresh laravel project, download and install Laravel 5.8 using the below command

Install Laravel Passport Package

In this step, we need to install Laravel Passport package via the composer dependency manager. Use the following command to install passport package.

After Installing ‘laravel/passport’ package, we need to add Passport service provider in config/app.php file as following.

config/app.php

Run Migration and Install Laravel Passport

After successfully installing ‘laravel/passport’ package, we require to create default passport tables in our database. so let’s run the following command to migrate Laravel Passport tables to your database.

Now, it is mandatory to install passport using the command below. This command will generate encryption keys required to generate secret access tokens.

Laravel Passport Configuration

Now, we need to make following changes in our model, service provider and auth config file to complete passport configuration. Open App/User.php model file and add ‘Laravel\Passport\HasApiTokens’ trait in it.

app/User.php

Next Register passport routes in App/Providers/AuthServiceProvider.php, open App/Providers/AuthServiceProvider.php and add Passport::routes method in the boot method of your AuthServiceProvider. It will generate necessary routes. This is how the app/Providers/AuthServiceProvider.php will look like after changes.

Now open config/auth.php file and set api driver to passport instead of session.

config/auth.php

Create API Routes

Let’s create API routes. Open routes/api.php file create api routes as below –

Create Authentication Controller

Now, create a Authentication Controller name PassportController. Use the below command to create controller.

Once the above command executed, it will create a resource controller file “AuthController.php” in “app/Http/Controllers/” directory. Go to “PassportController.php” and put the following code in it.

Building the Post CRUD API

Next, we will be creating a simple blog application with post table and implement CRUD (Create, Read, Update and Delete) APIs. To create the blog posts APIs we have to define table schema for posts table. Open terminal and use the following artisan command to generate <timestamp>create_posts_table.php migration.

Once this command is executed you will find a migration file created under “database/migrations”. Lets open migration file and put following code in it –

Create Model

In this step, we will use the following command to create post model –

Once, the above command executed it will create a model file Post.php in app directory. Next, we have to assign fillable fields using fillable property inside Post.php file. Open app/Post.php file and put the following code in it –

app/Post.php

Now, run following command to migrate database schema.

After, the migration executed successfully the posts table will be created in database.

Now, we have to add a relationship in the User model to retrieve the related posts. In app/User.php add the following method.

Create Controller

In this step, we will use the following command to create post controller.

Once the above command executed, it will create a controller file “PostController.php” in “app/Http/Controllers/” directory. Open the PostController.php file and put the following code in it.

app/Http/Controllers/PostController.php

Create Resource Route

After this, we need to add resource route for post controller. Lets open “routes/api.php” file and add following route in it.

our final route file looks as following –

routes/api.php

Start Application Server

Lets start the development server using following artisan command –

Testing the REST API

Our Authentication API is ready to test. I will use Postman to test the API.

Register Api :-
Verb: POST
URL :http://localhost:8000/api/register

register

Login Api :-
Verb: POST
URL :http://localhost:8000/api/login

login

User Api :-
Verb: GET
URL: http://localhost:8000/api/user

userinfo

Add Post Api :-
Verb: POST
URL: http://localhost:8000/api/posts

add_post

List User Post Api :-
Verb: GET
URL: http://localhost:8000/api/posts

user_posts

Single Post Api :-
Verb: GET
URL: http://localhost:8000/api/posts/{ID}

get_single_post

Update Post Api :-
Verb: PUT
URL: http://localhost:8000/api/posts/{ID}

update_single_post

Delete Post Api :-
Verb: DELETE
URL: http://localhost:8000/api/posts/{ID}

delete_single_post

Laravel jwt Authentication API | Laravel 5.8 Create REST API with jwt Authentication

Laravel 5.8 Create REST API with jwt Authentication

In one of my previous articles, we have learn How to Create REST API With Passport Authentication In Laravel using Laravel passport for REST API authentication. In this article, we will learn to create fully functional restful API with JWT Authentication in Laravel. In this tutorial, we will be creating fully functional CRUD APIs for Blog Posts along with JWT Authentication.

What is JWT?

JWT stands for JSON Web Tokens. JSON Web Token (JWT) is an authentication token which is used to securely transmit data between third-parties as a JSON object. The JSON Web token usually remains valid for 3600s or one hour. Nowdays API’s are mostly developed with JWT authentication.

Install Laravel 5.8

First of all we need to create a fresh laravel project, download and install Laravel 5.8 using the below command

Install JWT Auth Package Using Composer

In this step, we will install tymon jwt auth package via the composer dependency manager. Use the following command to install laravel jet authentication package.

If you are using Laravel version 5.5 or above, run the following command to install jwt package.

If you are using the laravel version 5.4 or less, run the following command to install jwt package.

After Installing tymon/jwt-auth package, we need to add service provider and alias in config/app.php file as following.

config/app.php

For versions less than 5.5, you are also required to set service provider and alias in config/app.php file.

If you are using Laravel version 5.5 or above, laravel does it automatically using Package Auto-Discovery.

Publishing Configuration File

Publish the configuration file using the following command for versions 5.5 or above

If you are using previous versions of laravel, run the following command to publish the configuration

Above command will generate a config/jwt.php configuration file.

config/jwt.php

Generate JWT Key

Run the following command for laravel 5.5 or above to generate the secret key used to sign the tokens.

For versions below 5.5

Registering Middleware

Register auth.jwt middleware in app/Http/Kernel.php

app/Http/Kernel.php

Update User Model

In this step we will require to implement JWTSubject interface in User model. It is mandatory to implement the Tymon\JWTAuth\Contracts\JWTSubject interface on the User model. This interface requires implementing two methods getJWTIdentifier and getJWTCustomClaims. Let’s update app/User.php model file with the following lines of code.

app/User.php

Create Authentication API Routes

In this step, We will setup authentication routes to register a new user, login with their user credentials and get the authenticated user details by using JWT token. So add the following route in routes/api.php

routes/api.php

Create Authentication Controller

Now, create a Authentication Controller name AuthController. Use the below command to create controller.

Once the above command executed, it will create a resource controller file “AuthController.php” in “app/Http/Controllers/” directory. Go to “AuthController.php” and put the following code in it.

Building the Post CRUD API

Next, we will be creating a simple blog application with post table and implement CRUD (Create, Read, Update and Delete) APIs. To create the blog posts APIs we have to define table schema for posts table. Open terminal and use the following artisan command to generate <timestamp>create_posts_table.php migration.

Once this command is executed you will find a migration file created under “database/migrations”. Lets open migration file and put following code in it –

Now, run following command to migrate database schema.

After, the migration executed successfully the posts table will be created in database.

Create Model

In this step, we will use the following command to create post model –

Once, the above command executed it will create a model file Post.php in app directory. Next, we have to assign fillable fields using fillable property inside Post.php file. Open app/Post.php file and put the following code in it –

app/Post.php

Now, we have to add a relationship in the User model to retrieve the related posts. In app/User.php add the following method.

Create Controller

In this step, we will use the following command to create post controller.

Once the above command executed, it will create a controller file “PostController.php” in “app/Http/Controllers/” directory. Open the PostController.php file and put the following code in it.

app/Http/Controllers/PostController.php

Create Resource Route

After this, we need to add resource route for post controller. Lets open “routes/api.php” file and add following route in it.

our final route file looks as following –

routes/api.php

Start Application Server

Lets start the development server using following artisan command –

Testing the REST API

Our Authentication API is ready to test. I will use Postman to test the API.

Register Api :-
Verb: POST
URL :http://localhost:8000/api/register

register

Login Api :-
Verb: POST
URL :http://localhost:8000/api/login

login

User Api :-
Verb: GET
URL: http://localhost:8000/api/user

userinfo

Add Post Api :-
Verb: POST
URL: http://localhost:8000/api/posts

add_post

List Post Api :-
Verb: GET
URL: http://localhost:8000/api/posts

user_posts

Single Post Api :-
Verb: GET
URL: http://localhost:8000/api/posts/{ID}

user_single_post

Update Post Api :-
Verb: PUT
URL: http://localhost:8000/api/posts/{ID}

user_post_update

Delete Post Api :-
Verb: DELETE
URL: http://localhost:8000/api/posts/{ID}

user_post_delete

Laravel 5.8 Jquery UI Autocomplete Search Example

Laravel 5.8 Jquery UI Autocomplete Search Example

In this article, I will show you how to create a dynamic database driven ajax jquery autocomplete in Laravel. In this tutorial we will create a dynamic search dropdown autocomplete which will fetch options from database table using jquery autocomplete.

The jquery autocomplete plugin is used to create dynamic autocomplete input with several options. In this example you will learn how to implement jquery autocomplete in laravel.

Before starting with example I assume that you already have fresh laravel 5.8 installation ready, if you have not installed it yet you can follow laravel 5 installation instruction here.

Install Laravel 5.8

First of all we need to create a fresh laravel project, download and install Laravel 5.8 using the below command

Configure Database In .env file

Now, lets create a MySQL database and connect it with laravel application. After creating database we need to set database credential in application’s .env file.

.env

Create Model and Migration

Now, we have to define table schema for contact table. Open terminal and let’s run the following command to generate a Contact model along with a migration file to create contact table in our database.

Once this command is executed you will find a migration file created under “database/migrations”. Lets open migration file created and put following code in it –

Run Laravel Migration

Now, run following command to migrate database schema.

After, the migration executed successfully the contact table will be created in database.

Create AutoComplete Controller

Next, we have to create a controller for AutoComplete suggestion. Create a controller named AutoCompleteController using command given below –

Once the above command executed, it will create a controller file AutoCompleteController.php in app/Http/Controllers directory. Open the AutoCompleteController.php file and put the following code in it.

app/Http/Controllers/AutoCompleteController.php

Create Blade / View Files

In this step, we will create view/blade file to perform autocomplete Search Using jQuery UI Autocomplete. Lets create a blade file “search.blade.php” in “resources/views/jqueryAutocomplete/” directory and put the following code in it respectively.

resources/views/jqueryAutocomplete/search.blade.php

Create Routes

After this, we need to add following routes in “routes/web.php” file. Lets open “routes/web.php” file and add following route.

routes/web.php

Now we are ready to run our example so lets start the development server using following artisan command –

Now, open the following URL in browser to see the output –

http://localhost:8000/search

Output 1:-

laravel-jquery-ui-autocomplete-search-1

Output 2:-

laravel-jquery-ui-autocomplete-search-2