Category: Laravel Development

Laravel Development

  • Installation of Laravel in Windows

    Here are some steps required to install Laravel in Windows operating system

    1. Server Requirements

    Installing Laravel first your system must satisfied few system requirements

    • PHP >= 7.13
    • BCMath PHP Extension
    • Ctype PHP Extension
    • JSON PHP Extension
    • Mbstring PHP Extension
    • OpenSSL PHP Extension
    • PDO PHP Extension
    • Tokenizer PHP Extension
    • XML PHP Extension

    Laravel Homestead virtual machine provides the all server requirements needed to install Laravel. Before launching Laravel Homestead you must install VirtualBox 6.x, VMWare, Parallels or Hyper-V. After installation of these one you must install “Vagrant”.
    OR
    If you are not using Homestead then you will need to install other web server such as “WAMP” or “XAMPP” free web server. These web servers automatically install everything you need to develop Web applications and provide the server for your Laravel application.
    In this article, I have used the WAMP server.

    1.1. Install server using WAMP(Window, Apache, MySQL, PHP) server
    Download the web server from link: http://www.wampserver.com

    After completion of download, install and run exe file

    2. Installing Laravel

    After installation of web server, install the “Composer” first in your machine before installing Laravel.

    2.1. Download the composer from the link: https://getcomposer.org/download/

    Download and run the composer-setup.exe file

    Installing composer
    For installing the latest version of Laravel project, make sure that you have selected the latest PHP version.

    2.2. Installing Laravel Via Composer
    Open terminal (cmd) in your machine and use directory “wamp64\www”

    After open the terminal check the composer is installed or not by using “composer” command’


    Install Laravel framework by issuing the composer “create-project” command in your terminal

    composer create-project –prefer-dist laravel/laravel projectname
    This command will create the latest version of Laravel under the “wamp64/www/” directory.

    After the project installed in your directory and we have installed php server, you may use “serve” artisan command to start development server: http://127.0.0.1:8000
    Command: php artisan serve

    Note: After installation of php server and composer, you must add environment variable on your system before start your project. These directories exist in different location based on your operating system, but some common locations of directory in windows are:
    Local server: “C:\wamp64\bin”
    Composer: “%USERPROFILE%\AppData\Roaming\Composer\vendor\bin”

  • Laravel Authentication

    In comparison to other framework, Laravel makes authentication very simple and almost everything is configured for you out of the box. You have to configure it. The authentication configuration file is located at “config/auth.php”, which contain several well documented options for tweaking the behaviour of the authentication services.

    At its core, Laravel authentication facilities are made up of “guards” and “providers”. Guards define how users are authenticated for each request, and Providers define how users are retrieved from your persistent storage.
    In Laravel, by default, it’s includes a “user.php” Eloquent model in your “app” directory (“app/user.php”). This model may be used with the default Eloquent authentication driver. If your application is not using the eloquent model, you may use the database authentication driver which uses the Laravel query builder.

    When building the database for the app\user model, make sure the password column is at least 60 characters in length and string column length should be 255 characters. And also, you should verify that user table contains a nullable, string “remember_token” (used for store a token and ‘remember me’ option for users when logging into your application) column of 100 characters.

    How to Start Authentication

    Laravel provide several pre-built authentication controller, such as:

    • ForgotPasswordController.php
    • LoginController.php
    • RegisterController.php
    • ResetPasswordController.php
    • VerificationController.php

    1. Setup Authentication

    First open your terminal and run the command:
    “php artisan make:auth”. But keep in mind, this command should be run on fresh laravel application.

    After run this command, this will install a layout view, auth view, as well as routes for all authentication end-points. These files are located in “resources\views” directory.

    Now, we have all views files and routes files, your application look like:
    Home Page

    Login Page

    Register Page

    2. Creating Database:

    After setup the authentication, then create the database into your local server: in this, I have use “Wamp” server for Laravel project, with database LDb name:

    After creating database, then go to your project and open “.env” file and do some changes: such as DB_DATABASE, DB_USERNAME and DB_PASSWORD.

    3. Run Migration

    Migration are like version control for your database which allowing you to easily modify and share the application’s database schema. Migrations are typically paired with Laravel’s schema builder to easily build your application’s database schema.

    In this project, I have generated only database and no schema is created. After run the migration, it will automatically create the table in your database.
    Run command: “php artisan migration”.

    After run migration command, three tables will be automatically generated in your database such as migration, password reset and users.

    Users’ field

    Password_reset

    Migration field
    After completion of all process, your project will work properly with authentication process.
    Note: In your “resources\views” directory, all of these views use the Bootstrap, CSS framework, but you are free to customize them however you wish.

    Results

    Register Page

    Login Page

    If you enter wrong password

  • How to make a Blog in Laravel

    In this article, we will go through how to make a blog in Laravel. We will build a simple blog and admin panel for managing the users and task. Source code for this project is available on GitHub, link: https://github.com/digitalcrm/Blog-Laravel.

    1. Installation

    First you will need a fresh installation of the Laravel framework. Install the Laravel framework using composer:
    “composer create-project –prefer-dist projectname”

    2. Prepping the Database

    2.1.Connect Database with your Laravel project:

    Go to your database server and create database. In this article, I have used the wamp server phpMyAdmin :

    Connect with your project, go to “.env” file and change the DB_CONNECTION, Database, User_name and password. In phpMyAdmin the default value of user_name is root and password is null(empty):

    3. Make Database Model and Migrations

    Next, create migrations and models for your blog. For creating model/migration run the artisan command in your terminal: “php artisan make:model model_name –m”. Here “-m” refers to migrations.

    In this article, I have created different models and migrations for User and Admin. The migration will be place in the “database/migrations” and Model will be placed in “app/model” directory of your project.

    Model “post.php”

    Migration table “create_posts_table.php”

    After creating and setup the migrations accordingly to your blog databases, run the migrate command in your terminals. Command: “php artisan migrate”

    After running migrate command, tables will be generated in database:

    4. Routing

    Next, we will add routes to our blog or application. Basically routes are used to points URLs to controllers or closure function that should be executed when a user accesses a given page. By default, all Laravel routes are defined in the “routes/web.php” file.
    In this article, I have created many routes for User, Admin, Home and Auth.

    5. Controller

    After adding the routes, we will need a controller for our blog or project. In Laravel all controller are generated in the “app\Http\Controller” directory. Command:
    php artisan make:controller ControllerName –resources
    OR
    php artisan make:controller ControllerName
    Resource Controller command

    Resource Controller (“app/Http/Controller/Admin/PostController.php”) file

    Controller Command

    Controller File (“app/Http/Controller/User/PostController.php”)

    In this article, I have created the different controller for the User, Admin and Home part of our blog.

    In the Admin controller, I have duplicated the auth controller for admin side authentication purpose.

    6. Authentication

    Run the auth artisan command in your terminal for creating the authentication in your project.
    Command: “php artisan make:auth”.

    After running this, the command will generate auth controllers, views and routes for your project.

    Controller: Auth controllers are generated in “app/Http/Controllers/Auth” directory.

    Views: auth views are generated under in “resources/views/auth” directory.

    7. Building Layouts & Views

    In this article has multiple views which contain a form for Admin, Blog, role, category, permission, tag, list users and as well as a listing of all blog. As we know all Laravel views are stored in “resources/views”. So we have defined multiple layout view in this directory.

    7.1. Layouts
    In this layout, we have created the app layouts for Login, Register and Logout.

    7.2. Admin Views
    In this view, we have created multiple views for admin task and also created an admin panel and blog page layouts.

    7.3. User Views
    Basically, as we know all web applications share the same layout across pages. So, in this view, we have defined the layouts for users. Laravel makes it easy to share these common features across every page using Blade layouts.

    8. Adding Tasks

    After creating the view, we have to move for create, update, store, edit, and delete tasks for each route of controller. Example for post-controller:

    create

    store

    edit and update

    destroy

    9. Authorization

    Laravel uses policies to organize authorization logic into simple, small classes. Typically, each policy corresponds to a model. In this article, we create a PostPolicy using the artisan command:
    “php artisan make:policy PostPolicy”

    After this command, we will add some validation in “post policy” as needed.

    10. Blog Interface

    Home Page

    Admin Dashboard

    Blog Create

    User’s Blogs

  • Laravel Notification

    Notifications are short informational messages that notify users of something that occurred in your application. Basically, Laravel provides support for sending notification across a variety of delivery channels, including mail, database, sms, markdown, broadcast and slack.

    Creating Notifications in Laravel

    In Laravel, each notification is represented by a single class and stored in the “app/Notifications” directory. This directory will be created for you when you run the “make:notification” Artisan command in your terminal.

    Basically Laravel feature provides the notification system; therefore, we just have to configure it on our Laravel project. In this article, we will show how to add notification system in Laravel. So, just follow these steps:

    Step1: Install New Laravel Project

    Create a new Laravel project with composer:
    composer create-project –prefer-dist laravel/laravel LaravelNotification

    Step2: Setup Database

    Next, setup the database and mail driver and add the database and mail driver credentials to “.env” file.
    Create Database:

    database credentials to .env file:

    Browse the mailtrap.io and create your own id, then you will get your own credentials like this.

    Add your Username and Password to .env file like this:

    Step3: Create user table and Authentication

    For creating the users table run the artisan command:
    “php artisan migrate”.

    Next, add authentication using auth command:
    “php artisan make:auth”

    Register the user in users table, navigate your browser localhost:8000/register

    Step4: Create Notification:

    Next, we need to add notification in your Laravel project. So run the artisan command:
    “php artisan make:notification SendNotification”

    After running the command, the file will be generated at app/Notification/SendNotification.php directory:

    Step5: Send Notification:

    Send Notification Using Notifiable Trait:
    Open routes/web.php file add “Notifiable Trait” like this:

    OR

    Send Notification Using The Notification Facade:
    Either you can send the notification by using the “Notification Facade” like this:

    Step6: Next, Navigate The Browser:

    After configuring the notification, navigate the URL: 127.0.0.1:8000/ or localhost:8000 and then check the demo inbox in mailtrap.io you will get the notification like this:

  • Benefits of Laravel

    Laravel deliver amazing application and provides pinch of magic tool kit for modern and maintainable php. It also provides all services, configuration, as well as what you have to need for your application provided into your application directory. Some key benefits of Laravel as follows:

    1. Artisan:

    Laravel provide the built-in tool command line interface called Artisan. Which help to developer to build and handles laravel project environment.

    For example: To view a list of all artisan command “list” command is used: “php artisan list”

    In command line every command includes a “help” command which displays and describes the command’s available arguments and options. For view the help screen, precede the name of the command with “help”: “php artisan help list”.

    2. Database

    Laravel makes databases extremely simple with interacting with variety of database backends using either raw SQL, the Query builder and the Eloquent ORM. Currently, Laravel supports four databases: MySQL, PostgreSQL, SQLite and SQL Server.

    For your application the configuration of database is located at “config/database.php”. This file may define all of your database connections, as well as this specifies which connection should be used by default.

    2.1. Eloquent ORM(Object Relational Mapping)

    Eloquent ORM (object relational mapping) provides a simple ActiveRecord, beautiful and expressive implementation for working with your database. Each database table has a corresponding “Model” which is used to interact and allow querying for data in your table, as well as insert new records into the table.

    Models typically live in your project “app” directory, but you can place them anywhere that can be auto-loaded according to your “composer.json” file. Artisan command “make:model” is the easiest way to create a model instance: “php artisan make:model ModelName”. And all eloquent models extend the “Illuminate\Database\Eloquent\Model” class.

    This model will be used for retrieve and store information from our Flight2 database table:

    Example:

    2.2. Query Builder:

    In your web application query builder used to perform databases operations and work on all supported database systems. It provides the convenient, fluent interface to creating and running database queries.

    This query builder perform the operations like Retrieving Results such as retrieving all rows/ single row or column from a table, Chunking Results when you need to work with thousands of database records, the “chunk” method is used and as well as provides operation insert, delete, joins, unions, updates, ordering, grouping, limit & offset, conditional clauses and debugging.

    Laravel query builder uses the PHP Data Object (PDO) parameter binding to protect application form SQL injection attacks.

    2.3. Migration System for Database

    In Laravel, migration is like version control for database, allowing you to expand the database structure and easily re-create when we make a change. Migration typically paired with the query builder for maintain and creating database schema. This migration system solves the problem of manually adding column into their local database schema.

    For creating migration, use Artisan command: “php artisan make:migration create_user_table”.

    Migration class contains two methods: up and down. The up method is used for adding new table, columns or indexes to your databases, while the down method reverse the operations performed by the up method. You can expressively create and modify tables using these both methods in Laravel schema builder.

    3. Authentication & Authorized System

    Laravel makes the authentication very simple and everything is configured out of the box. The authentication configuration file is located at “config/auth.php”.

    Laravel’s authentication facilities are made up of “defaults”, “guard”, “providers” and “resetting password”.

    Authentication Defaults
    This option is used for “guard” and reset password for your application. And this is perfect start for most of application but you may change as required.

    Authentication Guard
    This guard defines how users are authenticating for each request. This guard uses session storage and the eloquent user provider.

    User Providers
    defines how users are actually retrieved out of your database or other storage mechanism used by this application to persist your user’s data. If you have multiple table or models you may configure multiple sources which represent each model or table. These sources may then be assigned to any extra authentication guards you have defined.

    Resetting Passwords
    If you have more than one user table or model in your application and you want to have separate password reset settings based on the specific user types, you may specify multiple password reset configurations. The expire time is the number of minutes that the reset token should be considered valid. This security features keeps tokens short-lived so they have less time to be guessed.

    4. MVC (Model View Controller):

    MVC is a software architecture pattern that separates business logic from the user interface. It is divided into three part Model, View and Controller. All three works components work together to create three basic components. Model manages the fundamental database operation such fetching data or update data, the view provides the user interface of the application while controller contain business logic and provide link between model and view.

    Laravel support MVC structure which automatically care of segregation between logic and expression syntax. Such segregation makes it easier to designer to work on enhancing user interface without disturbing the core functionalities. Laravel provides the benefits for using this such as: Faster development of application, no conflict between designer and developer and easily debugging at any stage of development.

    5. Simplified Mail Integration System

    Laravel uses the “SwiftMailer” library that can be used for provide clean, simple API mail configuration. Laravel support sending emails and notification across multiple channels and offers drivers for different local and cloud based mail services such as SMTP, Mailgun, Postmark, SparkPost, Amazon SES and sendmail. The Mailgun, SparkPost, and Postmark are faster and simpler than SMTP severs. These all are required the Guzzle HTTP library, which may be installed via the composer package manager.

    Mail integration provides the benefits for you application like: send emails and notification via SMS & Slack, integrate mail notification systems and Notify users on performing each and every activity.

    Mailgun Driver
    To use this first you have to configure this option in your “config/mail.php”. Next, verify that your “config/services.php” which contains following option:

    Postmark Driver
    first you have to configure the file in “config/mail.php” directory and finally verify that your “config/service.php” file that contain following options:

    SparkPost Driver
    To use this driver, configure the “mail.php” file and verify your “config/services.php” file.

    6. Authentication:

    Laravel is built with to keep testing in mind. Laravel already set up the phpunit.xml file for your application. In Laravel, by defaults your application’s tests directory contains two directories: Feature and Unit. Where Feature tests focus on larger portion of your code while Unit tests focus on a very small, isolated portion of your code. When running the “phpunit”, Laravel automatically set the configuration environment to testing because of their environment variables defined in the “phpuint.xml” file.

    Creating test in the Feature directory

    Once the tests has been generated. Execute the phpunit command in your terminal.

    Creating test in the Unit directory

    Executes the phpunit command

    automatically configured the session and cache to the array driver, means that no session and cache data will be persisted while testing. For creating a new test case, use “make:test” command.

  • What is Laravel?

    Discussing the laravel first we go through about Framework and what Framework does?

    A framework is an abstraction in which they provides generic and conceptual structure for creating something useful and can be customized or overridden by user written code. The framework provides the code for establishes the application that knows “what” to do, but don’t know about “How” to do it, so this specific function (“How”) put into systematic way by the programmer.

    The framework does several things:
    • Framework makes development of application faster and help to make resource better.
    • Provide testing and debugging of code more easily.
    • Provide scalability of application.
    • Framework provides the model view controller (MVC) pattern for maintains the code.

    What is Laravel?

    Laravel is an open source php framework based on the model view controller (MVC) pattern. Laravel is highly used framework in comparison to other php framework such as Symfony, Cake php, Code Igniter and Zend Framework because of laravel has massive community over there. It is developed by Taylor Otwell, intended to make code easier and reduce the development cost.

    Laravel take the pain out of web development by easing the task of web projects, such as injection container, routing, mail validation, cache storage, session and real time event broadcasting. Laravel has its own architecture, which provide to developers to make application easier and create own infrastructure.

    A benefit of Laravel is accessible, powerful and provides tools required for large, robust applications. It is used for both big and small project.

    First version Laravel 1.0 release on June 2011. In Feb 26th 2019 Laravel introduced new version of Laravel 5.8.

    Google Trend (Laravel vs. other framework)

    #Laravel 5.8

    Laravel 5.8 introduced the improvement made in Laravel 5.7 by introducing the several things:

    • Eloquent hasOneThrough Relationship.
    • Improved Email Validation
    • Auto-Discovery Of Model Policies
    • DynamoDB Cache / Session Drivers
    • PSR-16 Cache Driver Compliance
    • Multiple Broadcast Authentication Guards
    • Token Guard Token Hashing
    • Default Scheduler Timezone
    • Carbon 2.0 Support
    • Pheanstalk 4.0 Support
    • Artisan Serve Improvements
    • PHPUnit 8.0 Support

    Laravel 5.8 fixes the variety of bug and improved the usability.

    Note: “Laravel provided the thorough documentation and video tutorial library of all modern web application. To learn about laravel, “Laracasts” contain 1518 video tutorial on the range of topics including laravel, modern Php, unit testing & Java Scripts”.

    Key Features:

    Routing

    For defining the routes Laravel providing basic and expressive method. The routes accept a URL and a closure. All routes are defined in your route files, which are located in the routes directory by framework automatically.

    Service Container

    This service container is essential used for building powerful, large application and as well as for contributing laravel core itself. And this is a tool for managing class dependencies and performing injection; Dependency injection is a fancy phrase that means “this” which provides benefits of to swap implementation of the injected class; where class dependencies “injected” into the class via the constructor or “setter” methods.

    Multiple Back-ends

    Laravel ships with a range of session and cache back-ends and provides an expressive, unified API for session and caching back-ends. Laravel also supports popular backends like Memcached and Redis.

    Eloquent ORM

    Currently Laravel supports four databases: MySQL, PostgreSQL, SQLite and SQL Server. But Laravel makes databases extremely simple with interacting with variety of database backends using either raw SQL, the Query builder and the Eloquent ORM.
    Eloquent ORM (object relational mapping) provides a simple ActiveRecord, beautiful and expressive implementation for working with your database. Each database table has a corresponding “Model” which is used to interact and allow querying for data in your table.

    Query Builder

    In your web application query builder used to perform databases operations and work on all supported database systems. It provides the convenient, fluent interface to creating and running database queries. Laravel query builder uses the PHP Data Object (PDO) parameter binding to protect application form SQL injection attacks.

    Pagination

    In comparison to other framework, pagination is excruciating. Laravel paginator is integrated with the Query builder and Eloquent ORM which provides the convenient, easy-to-use pagination of database results out of the box and paginator.

    Testing

    Laravel is built with to keep testing in mind. Laravel already set up the phpunit.xml file for your application. In Laravel, by defaults your application’s tests directory contains two directories: Feature and Unit. Where Feature tests focus on larger portion of your code while Unit tests focus on a very small, isolated portion of your code.

    Broadcasting

    Laravel assist you in building realtime, live-updating user interface; by make it easy to “broadcast” your event over a Web Socket connection. Broadcasting your Laravel events allows you to share the same event name between server-side code and client-side application. While in modern web application, when some data is updated on the server-side, a message is typically sent over a Web Socket connection to be handled by the client.

    File System

    Using the third party php package “Flysystem” laravel provides a powerful file system abstraction, simple to use drivers for working with local file systems, Amazon S3 and Rackspace cloud storage.

    Agnostic Migration

    In laravel, migration paired with laravel schema builder. Which provide you to easily build your application’s database schema. Laravel migration solve the problem of add column manually to their local database schema. The Laravel schema “facade” provides database agnostic support for creating and manipulating tables across all of Laravel supported database systems.

    Queues

    Laravel queues provide a unified API across a variety of different queue backend service such as Beanstalk, Amazon SQS, Redis, or even relational database. Queues allow deferring the processing of a time consuming task, such as sending an email, until a later time. In Laravel the configuration files of queue stored in “config/queue.php”. Where you will find the connection for each backend services.