#laravel registration form tutorial
Explore tagged Tumblr posts
laravelvuejs · 5 years ago
Text
Laravel Beginner tutorial | Create Login Register auth - Laravel
Laravel Beginner tutorial | Create Login Register auth – Laravel
Laravel Beginner tutorial | Create Login Register auth – Laravel
[ad_1]
Laravel has a command called ‘php artisan make:auth’ This command can instantly create Login and Register system on your laravel application. Creating Authentication system is very easy in laravel
Laravel Beginner tutorial – from download to deploy
Check https://bitfumes.com For ads free and more advanced courses
Join Our…
View On WordPress
0 notes
codesolutionsstuff · 3 years ago
Text
Laravel 8/7/6 Google ReCaptcha v2 Form Validation
Tumblr media
Laravel Google ReCaptcha – In this section, you will learn how to incorporate Google v2 Re Captcha form validation (security) into your Laravel application forms. Today, we will incorporate Google Re Captcha into the Laravel application. We will create one form with Google Re Captcha and validate the form data with Laravel validations before storing it in the database. In this Google Re captcha tutorial, we will go over all of the steps and then provide a live demo button. Click the live demo button to put this Laravel Google Recaptcha integration to the test.
Laravel Google V2 Re Captcha Form Validation
To learn more about Captcha validation in Laravel, go to Google. You can validate form data with Google v2 reCaptcha validation by following the steps below.
Table of Content
- Download laravel Fresh Setup - Setup Database Credentials - Install Google Captcha Package - Get Google Captcha Secrets - Create Route - Generate Controller by Command - Create Blade View (form) - Run Development Server
Step 1: Download laravel Fresh Setup
We must first download new Laravel setups. To download the laravel fresh setup on your system, run the command below. composer create-project --prefer-dist laravel/laravel blog
Step 2: Setup Database Credentials
Following the successful download of the laravel application, Set up database credentials in your project's.env file before proceeding to the next step: DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE=here your database name here DB_USERNAME=here database username here DB_PASSWORD=here database password here
Step 3: Install Google Captcha Package
In your Laravel 6 application, we'll now install the Google Captcha Package. Install this package in your Laravel application with the command below. composer require anhskohbo/no-captcha Open the config/app.php file and add service provider and alias after successfully installing Google Captcha Packages. config/app.php 'providers' => , 'aliases' =>
Step 4: Get Google Captcha Secrets
Now I'll make a site key and a secret key for Google Recaptcha in order to use it in a Laravel application. You only need to put the.env file if you already have site key and secret key. If you're not sure where we'll acquire secret key and secret site, use the link below and make your own secret credentials. Recaptcha is a new online registration system that uses a captcha system. The form will appear like this when you click this link Recaptcha new site registration. Fill in all of the required information and submit the form. After you submit the above form, you will be able to see your secret site and secret key. Here is where you should paste your credentials and your.env file. After that, we'll set the Google captcha secret in.env files. To do so, open a.env file and enter the following credentials:
Step 5: Create Route
We'll now add two routes to the web.php file, as seen below. The first is to display the form, and the second is to save the data from the form into the database. Open routes/web.php file Route::get('captcha-form', 'CaptchaController@captchForm'); Route::post('store-captcha-form', 'CaptchaController@storeCaptchaForm');
Step 6: Generate Controller by Command
We'll need to make a new controller called CaptchaController to handle two methods. Let's make a Controller with the command below. php artisan make:controller CaptchaController Now navigate to => app/Http/Controllers/CaptchaController.php to access the controller. Create some methods for displaying data and storing it in a database now. Read the full article
0 notes
t-baba · 5 years ago
Photo
Tumblr media
17 Best Bootstrap 4 Plugins
Totally open source and free to use, Bootstrap has become one of the most popular front-end frameworks for desktop and mobile development. With a mobile-first approach, the framework essentially forces designers to create sites for small screens and then scale designs up from there. 
Bootstrap 4 Plugins on CodeCanyon
Bootstrap 4 is the newest version of the framework, and today we take a look at the 17 best Bootstrap 4 plugins available at CodeCanyon. Whether you're coding a WordPress theme or searching for form or navbar templates for your static site, CodeCanyon has a plugin for you!
Depending on what are looking for some of these plugin cost as little as $5. You also get 6 months of free support as well as free lifetime updates for any plugin that you buy.
Best Bootstrap 4 Plugins
1. WP Pricing Builder
WP Pricing Builder allows users to set up responsive pricing tables within minutes. The plugin offers a drag-and-drop builder, 89 unique designs and a colour theme generator among other features. This makes setup easy and allows for a high degree of customisation.
User TelosAlpha says:
"Fast clear support. But beyond that, this is a very advanced and well  written piece of code. Very intuitive to use, many fantastic styles.”
2. Nearby Places
The Nearby Places plugin is an extension of the above Progress Map plugin. It allows users to display points of interest near a specific location added from the owner’s Progress Map. These points of interest are supplied by Google Maps. The plugin also provides a powerful search form that allows users to target their position or to enter a given address and display all nearby points of interest. The plugin can be customised from the admin panel in order to match the general look of your website.
User gijon says:
“After so much searching, this is the best map plugin I have found very complete and easy to use.”
3. Laravel Bootstrap Starter Kit
This Laravel- and Bootstrap- based starter kit could be perfect choice for your next project. The plugin author has add quite a few features to this kit such as authentication, registration, admin panel, responsive layout, and user roles. This should cover a lot of common functionality needed in many website projects.
The kit is based on Bootstrap 4. This makes it ideal for projects which are already using the Bootstrap framework as the overall layout and styling of the kit will match that of their website.
Even if you are creating a project from scratch, the use of Bootstrap 4 means that you won't have to worry about writing a lot of CSS as many well designed UI elements already exist within the framework.
4. Web Slide
Inspired by mobile design, Web Slide brings slide navigation to your website layout. Featuring one code for all devices, a mobile drawer style menu, an app style look and CSS 3 animation effects, the plugin is compatible with major desktop and mobile browsers like Chrome, Edge, Firefox, Safari, and Opera.
User quadnine says:
“A great product with top-notch support. This was money well spent.”
5. JQuery XML Shopping Cart
If you’re looking for a shopping cart that's easy to install and use, check out JQuery XML Shopping Cart. Some of its great features include support for unlimited products, which can easily be divided into categories and subcategories; a default tax rate which can be modified to a per-product tax rate; and a base shipping charge to which additional charges can be added as needed. 
User dnkn76 says:
“Documentation quality and flexibility is excellent comparing to another non-PHP shopping cart I bought. In no time the store was up and running and shipping cost, taxes and changing currency is a breeze. 
6. Bootstrap 4 Carousel
Bootstrap 4 Carousel gives users multiple options for displaying images on their website, including slider with thumbnails, multiple items carousel, fade effect carousel, Bootstrap image slider gallery, and more. The plugin provides over 200 pre-built examples and layouts for user convenience. This responsive carousel is compatible with mobile and tablet devices and all the latest web browsers. 
7. Bootstrap Plugin for TinyMCE
TinyMCE is one of the most popular and advanced WYSIWYG editors out there. This Bootstrap plugin for TinyMCE has been developed to make the editor even more powerful and useful for people who are using Bootstrap on their website.
This plugin gives you the ability to add Bootstrap-specific layout, components and styles to your content with ease. It comes with a bunch of awesome features like the Bootstrap 4 toolbar, styles, custom context menus and more. You can see all its features on the product description page.
8. Modern MegaMenu
Modern MegaMenu is all about giving users as many options as possible for creating the menu and navbar of their dreams. The plugin offers over 50 header layouts and a wide variety of navbar styles. This fully responsive Bootstrap 4 plugin is easily integrated into your site and is highly customisable. 
9. LiveSearch: Search Engine for Your Website
The LiveSearch plugin will add a basic search engine to your website. People will be able to use it to look up for text, images and PHP files within your website. It does not require the use of a database to function. You can also hide some content from being indexed. This plugin is ideal for small to medium sized websites.
The content of the website is crawled using a predefined based URL. The links and content is cached to make future searches faster. It is very easy to set up and you can also define logical correlation between search terms using AND and OR.
10. 47Admin: Bootstrap Admin Skin
47Admin is a Bootstrap skin that specifically targets admin templates. It comes with a lot of UI elements and bunch of additional functionality above what the basic Bootstrap framework provides. This will make help you quickly set up the front-end of the admin area in your next web project.
The templates and all their UI elements are responsive and come with cross-browser compatibility. It also comes with pages for login, registration, password recovery and more.
11. Floating Form
A collection of floating inline label forms, Floating Form contains a large number of forms such as contact, review, search, login and subscription forms, as well as a wide variety of booking forms. Each form has its own stylesheet.
12. Flat Form with Bootstrap 4
Flat Form is an incredible plugin if you want to add Bootstrap 4 based forms to your website. The plugin keeps its own styling to a minimum and take advantage of Bootstrap to design the forms. All the forms and UI elements look great. They will blend easily with the layout of your website.
There are shortcodes for adding ratings, toggle buttons, alerts, tooltips and much more. You can use the plugin to create all kinds of forms such as login, registration, review, comment or checkout form.
13. Bootstrap 4 WYSIWYG Editor
If you’re looking for a Bootstrap “what you see is what you get” (WYSIWYG) editor that will allow you to see what the end result of your project will look like while you’re creating it, then Bootstrap 4 WYSIWYG Editor may be for you. This simple and easy-to-use editor requires jQuery, Bootstrap 4, and Font Awesome. 
User innovationco says:
“I've used this for another plugin that I am making and it's a very nice editor with no bloat, which makes it easy for me to use. I have had no  issues with it and I would highly recommend it to others.”
Free Bootstrap 4 Plugins
In this section, I will cover some free Bootstrap 4 plugins that can help you add extra functionality to your website. They are mostly used to add some basic functionality unlike some of the premium plugins available on CodeCanyon.
1. Bootbox.js
 This is a free library that allows you to create Bootstrap based dialog boxes programatically. It automatically takes care of manipulating the DOM and event handlers for you.
2. Bootstrap-Navbar-Dropdowns
This plugin will come in handy when you want to quickly set up a multi-level dropdown menu based on Bootstrap.
3. DataTables
The Bootstrap DataTables plugin provides an easy way for you to add advanced interactions and controls to your tables. This includes things lie sorting the table along a particular column etc.
4. Bootstrap Select Dropdown
This Select Dropdown plugin comes will convert the select elements on your website to a dropdown. The aim is to make the long options list more user friendly with the help of keyboard navigation and a search box.
5. Form Validation
It is very important to validate any user input that comes you way through forms. This plugin will make it very easy for you to tell users if they filled any form incorrectly and how they can correct the error.
Tips for Choosing a Bootstrap Plugin
There are many things that can be confusing for an absolute beginner when it comes to choosing the right Bootstrap plugin. I have listed a few tips that can help you make the right decision.
Make sure that the plugin and your website are using the same version of Bootstrap. Many things change with each new version of Bootstrap. This means that some plugins and skins will not work with your website as expected if they are based on a different version.
One more thing that will help you quickly set things up in an existing project is to choose a plugin that does not apply excessive styling of its own over Bootstrap. This is particularly true if your own website uses minimal styling over what Bootstrap already provides.
Conclusion
The Bootstrap 4 plugins featured here just scratch the surface of options available at CodeCanyon, so if none of them appeal, there are plenty of other great options there to hold your interest.
And if you want to improve your skills using Bootstrap yourself, check out the ever so useful Bootstrap tutorials we have on offer.
by Monty Shokeen via Envato Tuts+ Code https://ift.tt/35dgluk
0 notes
airman7com · 5 years ago
Text
Laravel 7.x, 6 Custom Login Registration Example Tutorial
Laravel 6 custom login registration system with example. This tutorial demonstrates, how you can create your first custom login registration application using laravel version 6 with example.
This tutorial is a step by step guide, how you can create controllers, routes, models, and blade views files.
How you can create forms login & registration form and how to validate the form of data on…
View On WordPress
0 notes
itsmetacentric · 5 years ago
Link
laravel vue multi step form,laravel multi step form wizard,laravel multiple form submit,multi step registration laravel, In this tutorial we will go over Example of Multi Page / Step Form in Laravel with Validation
0 notes
Text
All about PHP Frameworks! Which is better to use & learn for Custom Web Applications & Why?
Tumblr media
PHP is essentially the most loved programming language when it comes to Website Development as well as complex Web Applications. However, Web Development can become trickier with increasing complexity. In such cases, PHP frameworks such as Codigniter, Laravel, Symphony and others come to the rescue. Here is everything you need to know about them and learn how to make most of Codeigniter Development, Laravel Development, Symphony Development, Zend Development etc…
CodeIgniter: Codeigniter is among the oldest PHP frameworks, having been around since 2006. Some of the features worth mentioning here are:
Model-View-Controller Based System: ensures scalable and well segregated development.
Light Weight: Web applications built on CodeIgniter are blazingly fast.
Database support
Support for email, image manipulation, FTP upload and much more.
Codeigniter Development is fun when you work with some of the brightest minds in the industry. Check with your service provider how well versed is their employees in CodeIgniter.
Laravel Development
Though Laravel is a late entrant to the field, it is essentially the hottest property in the town. As per a survey by popular site Sitepoint, it is the most preferred choice among developers. What is the reason behind the popularity of Laravel development? Here are some of the reasons behind its stupendous popularity:
Support for multiple file systems
Authentication feature that saves developers from writing tons of authentication related code
Route caching to speed up the application route registration
Highly improved method injection feature
Events object that helps speeding up Laravel development
Inbuilt templates that help in creating awesome content with lightning quick speed
Eloquent ORM to write database queries
MVC architecture support
Symphony Development
Symphony is yet another popular PHP framework that is immensely rich in incredible features. This is precisely the reason why it has enjoyed continuous love from developers all over the globe. Here are some of such features that deserve a mention:
Rich in features that make it flexible: Bundles are collection of files that make installation of new features tremendously easy. For instance, adding a new blog or a shopping cart can be done pretty easily by doing simple configuration. A number of similar such features essentially make Symphony a darling to web developers.
Commercial support: Commercial support from its parent company, SensioLabs has ensured that it has professionally curated tutorials and a lot of support as well.
-Ease of testing: PHPUnit Testing Library makes unit testing considerably easy.
Large community: Over the years, Symphony developers have ushered in a large community and by seeking support from the same one can tide over even the most complex problems.
Zend Development
Reasons to go for Zend development:
Extensible: Based on object oriented programming, Zend framework is immensely extendable. Zend developers can write awesome applications using its features like interfaces and inheritance without having to disturb the Zend framework codebase.
Decoupling lets you to use the features you need and skip everything else: Zend MVC architecture is so flexible that it lets you use only the features that are required for your application and skip those that you don’t need. This is essentially made possible with the help of classes based approach.
A variety of components that let you perform awesome tasks: You can do a lot with the vast variety of components like authentication, access control, create forms, RSS feed and so on with easily reusable components. So, step forward and implement that cracking functionality that you always wanted to add.
CakePHP: Here are some features of CakePHP, another immensely popular PHP framework that enjoys favor from many PHP developers:
MVC architecture: You can build scalable and inherently complex web applications using this framework
Object Relation Mapping: With the help of this feature you can write database queries with immense ease
Class inheritance: Class inheritence helps you to scale applications without unnecessary code and complications
Built-in validation: The validation related tasks can be completed without having to write enormous pieces of code thanks to the built-in validation featue
Yii: Some noteworthy features of Yii PHP framework:
Tremendous speed: Yii PHP framework is immensely fast and web applications written on it run like a charm
Form validation made easy
Enhanced security
CRUD validation
Authentication and Authorization features are in-built
The most popular PHP framework
Among all the PHP frameworks available today, the most popular one among these seems to be Laravel, given that it is used by over 50% of all PHP developers. Codeigniter and Symphony are up next due to their stupendous features, but even then they are far behind Laravel in terms of overall popularity.
Author Bio: Pushpendra Singh is a Freelance Codeigniter Developer working with F5 Buddy, who loves to develop Website, mobile and web applications. F5 Buddy is one of the amongst leading Development Outsourcing Company, which provides totally different array of real software package solutions like Custom software Development, IT Outsourcing Services, Web Application Development services to its clients globally.
0 notes
mbaljeetsingh · 8 years ago
Text
User Authorization in Laravel 5.4 with Spatie Laravel-Permission
What We'll Build
When building an application, we often need to set up an access control list (ACL). An ACL specifies the level of permission granted to a user of an application. For example a user John may have the permission to read and write to a resource while another user Smith may have the permission only to read the resource.
In this tutorial, I will teach you how to add access control to a Laravel app using Laravel-permission package. For this tutorial we will build a simple blog application where users can be assigned different levels of permission. Our user admin page will look like this:
Why Use Laravel-Permission
The Laravel-Permission package is built on top of Laravel's authorization features introduced in the 5.1.1 release. Although there are other packages that claim to offer similar functionalities, none of them have the same level of activity and maintenance as the laravel-permission package.
Development Environment and Installation
You can get Laravel up and running by first downloading the installer
composer global require "laravel/installer"
Then add $HOME/.composer/vendor/bin to your $PATH so the laravel executable can be located by your system. Now you can install the latest stable version of Laravel by running
laravel new
To install the laravel-permission package run
composer require spatie/laravel-permission
Next include the package to our list of service providers, in config/app.php add Spatie\Permission\PermissionServiceProvider::class so our file looks like this
'providers' => [ ... Spatie\Permission\PermissionServiceProvider::class, ];
Next publish the migration file for this package with the command
php artisan vendor:publish --provider="Spatie\Permission\PermissionServiceProvider" --tag="migrations"
Database Setup and Migrations
Next create the database and update the .env file to include the database information. For example, for this tutorial the database information section of the .env looks like this:
DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE=acl4 DB_USERNAME=root DB_PASSWORD=
To build the tables, run
php artisan migrate
Please note that in Laravel 5.4 the default character set is changed to utf8mb4, therefore if you are running MariaDB or MYSQL version lower than 5.7.7 you may get this error when trying to run migration files
[Illuminate\Database\QueryException] SQLSTATE[42000]: Syntax error or access violation: 1071 Specified key was too long; max key length is 767 bytes (SQL: alter table users add unique users_email_unique(email)) [PDOException] SQLSTATE[42000]: Syntax error or access violation: 1071 Specified key was too long; max key length is 767 bytes
To fix this error edit the app\Providers\AppServiceProvider.php file, setting the default string length in the boot method
use Illuminate\Support\Facades\Schema; public function boot() { Schema::defaultStringLength(191); }
After that run the migration again. If it works as normal you would find the following tables in your database:
migrations: This keeps track of migration process that have ran
users: This holds the users data of the application
password_resets: Holds token information when users request a new password
permissions: This holds the various permissions needed in the application
roles: This holds the roles in our application
role_has_permission: This is a pivot table that holds relationship information between the permissions table and the role table
user_has_roles: Also a pivot table, holds relationship information between the roles and the users table.
user_has_permissions: Also a pivot table, holds relationship information between the users table and the permissions table.
Publish the configuration file for this package by running
php artisan vendor:publish --provider="Spatie\Permission\PermissionServiceProvider" --tag="config"
The config file allows us to set the location of the Eloquent model of the permission and role class. You can also manually set the table names that should be used to retrieve your roles and permissions. Next we need to add the HasRoles trait to the User model:
use Illuminate\Foundation\Auth\User as Authenticatable; use Spatie\Permission\Traits\HasRoles; class User extends Authenticatable { use HasRoles; // ... }
Laravel Collective HTML Form builder
Next install Laravel Collective HTML Form builder as this will be useful further on when we are creating our forms:
composer require laravelcollective/html
Then add your new provider to the providers array of config/app.php:
'providers' => [ ... Collective\Html\HtmlServiceProvider::class, ];
Finally, add two class aliases to the aliases array of config/app.php:
'aliases' => [ // ... 'Form' => Collective\Html\FormFacade::class, 'Html' => Collective\Html\HtmlFacade::class, // ... ],
That's all the installation and configuration needed. A role can be created like a regular Eloquent model, like this:
use Spatie\Permission\Models\Role; use Spatie\Permission\Models\Permission; $role = Role::create(['name' => 'writer']); $permission = Permission::create(['name' => 'edit articles']);
You can also get the permissions associated to a user like this:
$permissions = $user->permissions;
And using the pluck method, pluck() you can get the role names associated with a user like this:
$roles = $user->roles()->pluck('name');
Other methods available to us include:
givePermissionTo(): Allows us to give persmission to a user or role
revokePermissionTo(): Revoke permission from a user or role
hasPermissionTo(): Check if a user or role has a given permission
assignRole(): Assigns role to a user
removeRole(): Removes role from a user
hasRole(): Checks if a user has a role
hasAnyRole(Role::all()): Checks if a user has any of a given list of roles
hasAllRoles(Role::all()): Checks if a user has all of a given list of role
The methods assignRole, hasRole, hasAnyRole, hasAllRoles and removeRole can accept a string, a Spatie\Permission\Models\Role-object or an \Illuminate\Support\Collection object. The givePermissionTo and revokePermissionTo methods can accept a string or a Spatie\Permission\Models\Permission object.
Laravel-Permission also allows to use Blade directives to verify if the logged in user has all or any of a given list of roles:
@role('writer') I'm a writer! @else I'm not a writer... @endrole @hasrole('writer') I'm a writer! @else I'm not a writer... @endhasrole @hasanyrole(Role::all()) I have one or more of these roles! @else I have none of these roles... @endhasanyrole @hasallroles(Role::all()) I have all of these roles! @else I don't have all of these roles... @endhasallroles
The Blade directives above depends on the users role. Sometimes we need to check directly in our view if a user has a certain permission. You can do that using Laravel's native @can directive:
@can('Edit Post') I have permission to edit @endcan
Controllers, Authentication and Views
You will need a total of four controllers for this application. Let's use resource controllers, as this automatically adds stub methods for us. Our controllers will be called
PostController
UserController
RoleController
PermissionController
Before working on these controllers let's create our authentication system. With one command Laravel provides a quick way to scaffold all of the routes and views needed for authentication.
php artisan make:auth
After running this command you would notice two new links for user login and registration in the home page.
This command also creates a HomeController (you can delete this as it won't be needed), a resources/views/layouts/app.blade.php file which contains markup that would be shared by all our views and an app/Http/Controllers/Auth directory which contains the controllers for registration and login. Switch into this directory and open the RegisterController.phpfile. Remove the bcrypt function in the create method, so the the method looks like this
protected function create(array $data) { return User::create([ 'name' => $data['name'], 'email' => $data['email'], 'password' => $data['password'], ]); }
Instead let's define a mutator in app\User.php which would encrypt all our password fields. In app\User.php add this method:
public function setPasswordAttribute($password) { $this->attributes['password'] = bcrypt($password); }
This would provide the same functionality as before but now you don't need to write the bcrypt function when dealing with the password field in subsequent controllers.
Also in the RegisterController.phpfile. Change the $redirectTo property to:
protected $redirectTo = '/';
Do the same thing in the LoginController.phpfile.
Since the HomeController has been deleted our users are now redirected to the home page which would contain a list of our blog posts.
Next let's edit the resources/views/layouts/app.blade.php file to include: an extra drop-down 'Admin' link to view all users and an errors file which checks if our form produced any error. The 'Admin' link would only be viewed by users with the 'Admin' Role. We would also create a custom styles.css which would have extra styling for our resources/views/posts/index.blade.php view. The styling is just a paragraph in the teaser of our index view, the file should be located in public/css/styles.css
<!DOCTYPE html> <html lang=""> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- CSRF Token --> <meta name="csrf-token" content=""> <title></title> <!-- Styles --> <link href="http://ift.tt/1uaQUM0" rel="stylesheet"> <link href="http://ift.tt/1uaQUM0" rel="stylesheet"> <link rel="stylesheet" href="http://ift.tt/2cYLUyN; integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> <!-- Scripts --> <script> window.Laravel = {!! json_encode([ 'csrfToken' => csrf_token(), ]) !!}; </script> <script src="http://ift.tt/2qqGPlI;></script> </head> <body> <div id="app"> <nav class="navbar navbar-default navbar-static-top"> <div class="container"> <div class="navbar-header"> <!-- Collapsed Hamburger --> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#app-navbar-collapse"> <span class="sr-only">Toggle Navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <!-- Branding Image --> <a class="navbar-brand" href="http://ift.tt/1uaQUM0"> </a> </div> <div class="collapse navbar-collapse" id="app-navbar-collapse"> <!-- Left Side Of Navbar --> <ul class="nav navbar-nav"> <li><a href="http://ift.tt/1uaQUM0">Home</a></li> @if (!Auth::guest()) <li><a href="http://ift.tt/1uaQUM0">New Article</a></li> @endif </ul> <!-- Right Side Of Navbar --> <ul class="nav navbar-nav navbar-right"> <!-- Authentication Links --> @if (Auth::guest()) <li><a href="http://ift.tt/1uaQUM0">Login</a></li> <li><a href="http://ift.tt/1uaQUM0">Register</a></li> @else <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false"> <span class="caret"></span> </a> <ul class="dropdown-menu" role="menu"> <li> @role('Admin') <a href="#"><i class="fa fa-btn fa-unlock"></i>Admin</a> @endrole <a href="http://ift.tt/1uaQUM0" onclick="event.preventDefault(); document.getElementById('logout-form').submit();"> Logout </a> <form id="logout-form" action="" method="POST" style="display: none;"> </form> </li> </ul> </li> @endif </ul> </div> </div> </nav> @if(Session::has('flash_message')) <div class="container"> <div class="alert alert-success"><em> {!! session('flash_message') !!}</em> </div> </div> @endif <div class="row"> <div class="col-md-8 col-md-offset-2"> @include ('errors.list') </div> </div> @yield('content') </div> <!-- Scripts --> <script src=""></script> </body> </html>
The error file is:
@if (count($errors) > 0) <div class="alert alert-danger"> <ul> @foreach ($errors->all() as $error) <li></li> @endforeach </ul> </div> @endif
and the styles.css file is simply:
p.teaser { text-indent: 30px; }
Post Controller
First, let's create the migration and model files for the PostController
php artisan make:model Post -m
This command generates a migration file in app/database/migrations for generating a new MySQL table named posts in our database and a model file Post.phpin the app directory. Let's edit the migration file to include title and body fields of our post. Add a title and body field so the migration file looks like this:
<?php //database\migrations\xxxx_xx_xx_xxxxxx_create_posts_table.php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreatePostsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('posts', function (Blueprint $table) { $table->increments('id'); $table->string('title'); $table->text('body'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('posts'); } }
After saving the file, run migration again
php artisan migrate
You can now check the database for the post table and columns.
Next make the title and body field of the Post model mass assignable
namespace App; use Illuminate\Database\Eloquent\Model; class Post extends Model { protected $fillable = [ 'title', 'body' ]; }
Now let's generate our resource controller.
php artisan make:controller PostController --resource
This will create our controller with all the stub methods needed. Edit this file to look like this
<?php // app/Http/Controllers/PostController.php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Post; use Auth; use Session; class PostController extends Controller { public function __construct() { $this->middleware(['auth', 'clearance'])->except('index', 'show'); } /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { $posts = Post::orderby('id', 'desc')->paginate(5); //show only 5 items at a time in descending order return view('posts.index', compact('posts')); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { return view('posts.create'); } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { //Validating title and body field $this->validate($request, [ 'title'=>'required|max:100', 'body' =>'required', ]); $title = $request['title']; $body = $request['body']; $post = Post::create($request->only('title', 'body')); //Display a successful message upon save return redirect()->route('posts.index') ->with('flash_message', 'Article, '. $post->title.' created'); } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show($id) { $post = Post::findOrFail($id); //Find post of id = $id return view ('posts.show', compact('post')); } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function edit($id) { $post = Post::findOrFail($id); return view('posts.edit', compact('post')); } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update(Request $request, $id) { $this->validate($request, [ 'title'=>'required|max:100', 'body'=>'required', ]); $post = Post::findOrFail($id); $post->title = $request->input('title'); $post->body = $request->input('body'); $post->save(); return redirect()->route('posts.show', $post->id)->with('flash_message', 'Article, '. $post->title.' updated'); } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { $post = Post::findOrFail($id); $post->delete(); return redirect()->route('posts.index') ->with('flash_message', 'Article successfully deleted'); } }
Here the Post class was imported from our model and the Auth class which was generated with the make:auth command earlier. These were imported so that you would be able to make Eloquent queries on the Post table and so as to be able to have access to authentication information of our users. In the constructor two middlewares were called, one is auth which restricts access to the PostController methods to authenticated users the other is a custom middleware is yet to be created. This would be responsible for our Permissions and Roles system. Next, index and show are passed into the except method to allow all users to be able to view posts.
The index() method lists all the available posts. It queries the post table for all posts and passes this information to the view. Paginate() allows us to limit the number of posts in a page, in this case five.
The create() method simply returns the posts/create view which would contain a form for creating new posts. The store() method saves the information input from the posts/create view. The information is first validated and after it is saved, a flash message is passed to the view posts/index.
Our show() method of the PostController allows us to display a single post. This method takes the post id as an argument and passes it to the method Post::find(). The result of the query is then sent to our posts/show view.
The edit() method, similar to the create() method simply returns the posts/edit view which would contain a form for creating editing posts. The update() method takes the information from the posts/edit view and updates the record. The destroy() method let's us delete a post.
Now that you have the PostController you need to set up the routes. Edit your app/routes/web.php file to look like this:
<?php Route::get('/', function () { return view('welcome'); }); Auth::routes(); Route::get('/', 'PostController@index')->name('home'); Route::resource('users', 'UserController'); Route::resource('roles', 'RoleController'); Route::resource('permissions', 'PermissionController'); Route::resource('posts', 'PostController');
The / route is the route to our home page, here it was renamed to home The Auth route was generated when you ran the make:auth command. It handles authentication related routes. The other four routes are for resources that would be created later.
Post Views
Only four views are needed for our PostController. Create the files \resources\views\posts\index.blade.php, \resources\views\posts\create.blade.php, \resources\views\posts\show.blade.php, \resources\views\posts\edit.blade.php
Edit the index.blade.phpfile to look like this
@extends('layouts.app') @section('content') <div class="container"> <div class="row"> <div class="col-md-10 col-md-offset-1"> <div class="panel panel-default"> <div class="panel-heading"><h3>Posts</h3></div> <div class="panel-heading">Page of </div> @foreach ($posts as $post) <div class="panel-body"> <li style="list-style-type:disc"> <a href="http://ift.tt/1uaQUM0"><b></b><br> <p class="teaser"> </p> </a> </li> </div> @endforeach </div> <div class="text-center"> {!! $posts->links() !!} </div> </div> </div> </div> @endsection
Notice that this file extends views\layouts\app.php file, which was generated earlier by the make:auth command.
The create.blade.php file looks like this
@extends('layouts.app') @section('title', '| Create New Post') @section('content') <div class="row"> <div class="col-md-8 col-md-offset-2"> <h1>Create New Post</h1> <hr> <div class="form-group"> <br> <br> </div> </div> </div> @endsection
The show view looks like this:
@extends('layouts.app') @section('title', '| View Post') @section('content') <div class="container"> <h1></h1> <hr> <p class="lead"> </p> <hr> {!! Form::open(['method' => 'DELETE', 'route' => ['posts.destroy', $post->id] ]) !!} <a href="http://ift.tt/1uaQUM0" class="btn btn-primary">Back</a> @can('Edit Post') <a href="http://ift.tt/1uaQUM0" class="btn btn-info" role="button">Edit</a> @endcan @can('Delete Post') {!! Form::submit('Delete', ['class' => 'btn btn-danger']) !!} @endcan {!! Form::close() !!} </div> @endsection
Here the can directive checks if a user has the permission to Edit or Delete Posts, if so the Edit and Delete button will be displayed. If the user does not have these permissions, only the Back button would be displayed.
The edit view just displays a edit form that will be used to update records:
@extends('layouts.app') @section('title', '| Edit Post') @section('content') <div class="row"> <div class="col-md-8 col-md-offset-2"> <h1>Edit Post</h1> <hr> <div class="form-group"> <br> <br> </div> </div> </div> @endsection
If you visit the home page you would see this
User Controller
The UserController will handle displaying all users, creating of new users, editing users, assigning roles to users and deleting users. As before generate the controller by running
php artisan make:controller UserController --resource
Then replace the content of this file with:
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\User; use Auth; //Importing laravel-permission models use Spatie\Permission\Models\Role; use Spatie\Permission\Models\Permission; //Enables us to output flash messaging use Session; class UserController extends Controller { public function __construct() { $this->middleware(['auth', 'isAdmin']); //isAdmin middleware lets only users with a //specific permission permission to access these resources } /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { //Get all users and pass it to the view $users = User::all(); return view('users.index')->with('users', $users); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { //Get all roles and pass it to the view $roles = Role::get(); return view('users.create', ['roles'=>$roles]); } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { //Validate name, email and password fields $this->validate($request, [ 'name'=>'required|max:120', 'email'=>'required|email|unique:users', 'password'=>'required|min:6|confirmed' ]); $user = User::create($request->only('email', 'name', 'password')); //Retrieving only the email and password data $roles = $request['roles']; //Retrieving the roles field //Checking if a role was selected if (isset($roles)) { foreach ($roles as $role) { $role_r = Role::where('id', '=', $role)->firstOrFail(); $user->assignRole($role_r); //Assigning role to user } } //Redirect to the users.index view and display message return redirect()->route('users.index') ->with('flash_message', 'User successfully added.'); } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show($id) { return redirect('users'); } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function edit($id) { $user = User::findOrFail($id); //Get user with specified id $roles = Role::get(); //Get all roles return view('users.edit', compact('user', 'roles')); //pass user and roles data to view } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update(Request $request, $id) { $user = User::findOrFail($id); //Get role specified by id //Validate name, email and password fields $this->validate($request, [ 'name'=>'required|max:120', 'email'=>'required|email|unique:users,email,'.$id, 'password'=>'required|min:6|confirmed' ]); $input = $request->only(['name', 'email', 'password']); //Retreive the name, email and password fields $roles = $request['roles']; //Retreive all roles $user->fill($input)->save(); if (isset($roles)) { $user->roles()->sync($roles); //If one or more role is selected associate user to roles } else { $user->roles()->detach(); //If no role is selected remove exisiting role associated to a user } return redirect()->route('users.index') ->with('flash_message', 'User successfully edited.'); } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { //Find a user with a given id and delete $user = User::findOrFail($id); $user->delete(); return redirect()->route('users.index') ->with('flash_message', 'User successfully deleted.'); } }
Here the User class, the Role class, the Permission class and the Auth class are imported. In the constructor the auth middleware is called to make sure only authenticated users have access to the User resource. A custom middleware isAdmin is also called. This checks if the authenticated user has administrator privileges. This middleware will be created later.
The index() method gets all users from the Users table and passes it to the index view which will display all users in a table. The create() method first gets all the Roles from the Roles table and passes it to the create view. This is so that Roles can be added when creating a User.
The store() method saves the input from the create view, after validating the input, looping through the Roles that was passed in the form and assigning these Roles to the User. The show()method just redirects back to the users page as for this demonstration, we wont need to show each user individually.
The edit() method gets the user corresponding to the id passed, then gets all roles and passes it to the edit view. The update() method validates data from the edit view and saves the updated name and password fields. It gets all roles from the roles table and while looping through them, removes any role assign to the user. It then takes the role data inputted from the form, matches them with the values in the databases and assigns these roles to the user.
The destroy() method allows us to delete a user along with it's corresponding role.
User Views
Three views are needed here: index, create and edit views. The index view would contain a table that lists all our users and their roles.
@extends('layouts.app') @section('title', '| Users') @section('content') <div class="col-lg-10 col-lg-offset-1"> <h1><i class="fa fa-users"></i> User Administration <a href="http://ift.tt/1uaQUM0" class="btn btn-default pull-right">Roles</a> <a href="http://ift.tt/1uaQUM0" class="btn btn-default pull-right">Permissions</a></h1> <hr> <div class="table-responsive"> <table class="table table-bordered table-striped"> <thead> <tr> <th>Name</th> <th>Email</th> <th>Date/Time Added</th> <th>User Roles</th> <th>Operations</th> </tr> </thead> <tbody> @foreach ($users as $user) <tr> <td></td> <td></td> <td></td> <td></td> <td> <a href="http://ift.tt/1uaQUM0" class="btn btn-info pull-left" style="margin-right: 3px;">Edit</a> {!! Form::open(['method' => 'DELETE', 'route' => ['users.destroy', $user->id] ]) !!} {!! Form::submit('Delete', ['class' => 'btn btn-danger']) !!} {!! Form::close() !!} </td> </tr> @endforeach </tbody> </table> </div> <a href="http://ift.tt/1uaQUM0" class="btn btn-success">Add User</a> </div> @endsection
The create view is just a form that allows us to create new users and assign roles to them.
@extends('layouts.app') @section('title', '| Add User') @section('content') <div class='col-lg-4 col-lg-offset-4'> <h1><i class='fa fa-user-plus'></i> Add User</h1> <hr> <div class="form-group"> </div> <div class="form-group"> </div> <div class='form-group'> @foreach ($roles as $role) <br> @endforeach </div> <div class="form-group"> <br> </div> <div class="form-group"> <br> </div> </div> @endsection
The edit view is a form that allows us to edit users and their roles. Using Laravel's form model binding the form is automatically populated with the previous values.
@extends('layouts.app') @section('title', '| Edit User') @section('content') <div class='col-lg-4 col-lg-offset-4'> <h1><i class='fa fa-user-plus'></i> Edit </h1> <hr> <div class="form-group"> </div> <div class="form-group"> </div> <h5><b>Give Role</b></h5> <div class='form-group'> @foreach ($roles as $role) <br> @endforeach </div> <div class="form-group"> <br> </div> <div class="form-group"> <br> </div> </div> @endsection
Permission Controller
Now let's tackle the PermissionControllerCreate the file and paste the following code:
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Auth; //Importing laravel-permission models use Spatie\Permission\Models\Role; use Spatie\Permission\Models\Permission; use Session; class PermissionController extends Controller { public function __construct() { $this->middleware(['auth', 'isAdmin']); //isAdmin middleware lets only users with a //specific permission permission to access these resources } /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { $permissions = Permission::all(); //Get all permissions return view('permissions.index')->with('permissions', $permissions); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { $roles = Role::get(); //Get all roles return view('permissions.create')->with('roles', $roles); } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { $this->validate($request, [ 'name'=>'required|max:40', ]); $name = $request['name']; $permission = new Permission(); $permission->name = $name; $roles = $request['roles']; $permission->save(); if (!empty($request['roles'])) { //If one or more role is selected foreach ($roles as $role) { $r = Role::where('id', '=', $role)->firstOrFail(); //Match input role to db record $permission = Permission::where('name', '=', $name)->first(); //Match input //permission to db record $r->givePermissionTo($permission); } } return redirect()->route('permissions.index') ->with('flash_message', 'Permission'. $permission->name.' added!'); } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show($id) { return redirect('permissions'); } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function edit($id) { $permission = Permission::findOrFail($id); return view('permissions.edit', compact('permission')); } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update(Request $request, $id) { $permission = Permission::findOrFail($id); $this->validate($request, [ 'name'=>'required|max:40', ]); $input = $request->all(); $permission->fill($input)->save(); return redirect()->route('permissions.index') ->with('flash_message', 'Permission'. $permission->name.' updated!'); } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { $permission = Permission::findOrFail($id); //Make it impossible to delete this specific permission if ($permission->name == "Administer roles & permissions") { return redirect()->route('permissions.index') ->with('flash_message', 'Cannot delete this Permission!'); } $permission->delete(); return redirect()->route('permissions.index') ->with('flash_message', 'Permission deleted!'); } }
In the store() method, we are making it possible for a role to be selected as a permission is created. After validating and saving the permission name field, a check is done if a role was selected if it was, a permission is assigned to the selected role.
Permission View
Three views are needed here as well. The index view would list in a table all the available permissions, the create view is a form which would be used to create a new permission and the edit view is a form that let's us edit existing permission.
@extends('layouts.app') @section('title', '| Permissions') @section('content') <div class="col-lg-10 col-lg-offset-1"> <h1><i class="fa fa-key"></i>Available Permissions <a href="http://ift.tt/1uaQUM0" class="btn btn-default pull-right">Users</a> <a href="http://ift.tt/1uaQUM0" class="btn btn-default pull-right">Roles</a></h1> <hr> <div class="table-responsive"> <table class="table table-bordered table-striped"> <thead> <tr> <th>Permissions</th> <th>Operation</th> </tr> </thead> <tbody> @foreach ($permissions as $permission) <tr> <td></td> <td> <a href="http://ift.tt/1uaQUM0" class="btn btn-info pull-left" style="margin-right: 3px;">Edit</a> {!! Form::open(['method' => 'DELETE', 'route' => ['permissions.destroy', $permission->id] ]) !!} {!! Form::submit('Delete', ['class' => 'btn btn-danger']) !!} {!! Form::close() !!} </td> </tr> @endforeach </tbody> </table> </div> <a href="http://ift.tt/1uaQUM0" class="btn btn-success">Add Permission</a> </div> @endsection
The following is the create view
@extends('layouts.app') @section('title', '| Create Permission') @section('content') <div class='col-lg-4 col-lg-offset-4'> <h1><i class='fa fa-key'></i> Add Permission</h1> <br> <div class="form-group"> </div><br> @if(!$roles->isEmpty()) //If no roles exist yet <h4>Assign Permission to Roles</h4> @foreach ($roles as $role) <br> @endforeach @endif <br> </div> @endsection
And finally the edit view:
@extends('layouts.app') @section('title', '| Edit Permission') @section('content') <div class='col-lg-4 col-lg-offset-4'> <h1><i class='fa fa-key'></i> Edit </h1> <br> <div class="form-group"> </div> <br> </div> @endsection
Role Controller
The RoleController is quite similar to the UserController. This controller will allow us to create roles and assign one or more permissions to a role. Create the file and paste the following code:
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Auth; //Importing laravel-permission models use Spatie\Permission\Models\Role; use Spatie\Permission\Models\Permission; use Session; class RoleController extends Controller { public function __construct() { $this->middleware(['auth', 'isAdmin']);//isAdmin middleware lets only users with a //specific permission permission to access these resources } /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { $roles = Role::all();//Get all roles return view('roles.index')->with('roles', $roles); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { $permissions = Permission::all();//Get all permissions return view('roles.create', ['permissions'=>$permissions]); } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { //Validate name and permissions field $this->validate($request, [ 'name'=>'required|unique:roles|max:10', 'permissions' =>'required', ] ); $name = $request['name']; $role = new Role(); $role->name = $name; $permissions = $request['permissions']; $role->save(); //Looping thru selected permissions foreach ($permissions as $permission) { $p = Permission::where('id', '=', $permission)->firstOrFail(); //Fetch the newly created role and assign permission $role = Role::where('name', '=', $name)->first(); $role->givePermissionTo($p); } return redirect()->route('roles.index') ->with('flash_message', 'Role'. $role->name.' added!'); } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show($id) { return redirect('roles'); } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function edit($id) { $role = Role::findOrFail($id); $permissions = Permission::all(); return view('roles.edit', compact('role', 'permissions')); } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update(Request $request, $id) { $role = Role::findOrFail($id);//Get role with the given id //Validate name and permission fields $this->validate($request, [ 'name'=>'required|max:10|unique:roles,name,'.$id, 'permissions' =>'required', ]); $input = $request->except(['permissions']); $permissions = $request['permissions']; $role->fill($input)->save(); $p_all = Permission::all();//Get all permissions foreach ($p_all as $p) { $role->revokePermissionTo($p); //Remove all permissions associated with role } foreach ($permissions as $permission) { $p = Permission::where('id', '=', $permission)->firstOrFail(); //Get corresponding form //permission in db $role->givePermissionTo($p); //Assign permission to role } return redirect()->route('roles.index') ->with('flash_message', 'Role'. $role->name.' updated!'); } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { $role = Role::findOrFail($id); $role->delete(); return redirect()->route('roles.index') ->with('flash_message', 'Role deleted!'); } }
Roles View
Three views are needed here as well. The index view to display available roles and associated permissions, the create view to add a new role and a view to edit an existing role. Create the index.blade.php file and paste the following:
@extends('layouts.app') @section('title', '| Roles') @section('content') <div class="col-lg-10 col-lg-offset-1"> <h1><i class="fa fa-key"></i> Roles <a href="http://ift.tt/1uaQUM0" class="btn btn-default pull-right">Users</a> <a href="http://ift.tt/1uaQUM0" class="btn btn-default pull-right">Permissions</a></h1> <hr> <div class="table-responsive"> <table class="table table-bordered table-striped"> <thead> <tr> <th>Role</th> <th>Permissions</th> <th>Operation</th> </tr> </thead> <tbody> @foreach ($roles as $role) <tr> <td></td> <td></td> <td> <a href="http://ift.tt/1uaQUM0" class="btn btn-info pull-left" style="margin-right: 3px;">Edit</a> {!! Form::open(['method' => 'DELETE', 'route' => ['roles.destroy', $role->id] ]) !!} {!! Form::submit('Delete', ['class' => 'btn btn-danger']) !!} {!! Form::close() !!} </td> </tr> @endforeach </tbody> </table> </div> <a href="http://ift.tt/1uaQUM0" class="btn btn-success">Add Role</a> </div> @endsection
For the create view:
@extends('layouts.app') @section('title', '| Add Role') @section('content') <div class='col-lg-4 col-lg-offset-4'> <h1><i class='fa fa-key'></i> Add Role</h1> <hr> <div class="form-group"> </div> <h5><b>Assign Permissions</b></h5> <div class='form-group'> @foreach ($permissions as $permission) <br> @endforeach </div> </div> @endsection
And for the edit view:
@extends('layouts.app') @section('title', '| Edit Role') @section('content') <div class='col-lg-4 col-lg-offset-4'> <h1><i class='fa fa-key'></i> Edit Role: </h1> <hr> <div class="form-group"> </div> <h5><b>Assign Permissions</b></h5> @foreach ($permissions as $permission) <br> @endforeach <br> </div> @endsection
Middleware
To restrict access to the roles and permissions page, a middleware was included called isAdmin in our PermissionController and RoleController. This middleware counts how many users are in the Users table, and if there are more than one users, it checks if the current authenticated User has the permission to 'Administer roles & permissions'. To create a permission visit http://localhost:8000/permissions/create. Then go to http://localhost:8000/roles/create to create a role, to which you can now assign the permission you created. For example you can create a permission called 'Administer roles & permissions' and a 'Admin' role to which you would assign this permission. Create the AdminMiddleware in the directory app/Http/Middleware/ and enter the following code:
<?php namespace App\Http\Middleware; use Closure; use Illuminate\Support\Facades\Auth; use App\User; class AdminMiddleware { /** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @return mixed */ public function handle($request, Closure $next) { $user = User::all()->count(); if (!($user == 1)) { if (!Auth::user()->hasPermissionTo('Administer roles & permissions')) //If user does //not have this permission { abort('401'); } } return $next($request); } }
A middleware called clearance was also included in our PostController. This middleware would check if a user has the permissions Administer roles & permissions, Create Post, Edit Post and Delete Post.
<?php namespace App\Http\Middleware; use Closure; use Illuminate\Support\Facades\Auth; class ClearanceMiddleware { /** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @return mixed */ public function handle($request, Closure $next) { if (Auth::user()->hasPermissionTo('Administer roles & permissions')) //If user has this //permission { return $next($request); } if ($request->is('posts/create'))//If user is creating a post { if (!Auth::user()->hasPermissionTo('Create Post')) { abort('401'); } else { return $next($request); } } if ($request->is('posts/*/edit')) //If user is editing a post { if (!Auth::user()->hasPermissionTo('Edit Post')) { abort('401'); } else { return $next($request); } } if ($request->isMethod('Delete')) //If user is deleting a post { if (!Auth::user()->hasPermissionTo('Delete Post')) { abort('401'); } else { return $next($request); } } return $next($request); } }
Add AdminMiddleware::class and ClearanceMiddleware::class to the $routeMiddleware property of /app/Http/kernel.php like this:
protected $routeMiddleware = [ 'auth' => \Illuminate\Auth\Middleware\Authenticate::class, 'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class, 'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class, 'can' => \Illuminate\Auth\Middleware\Authorize::class, 'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class, 'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class, 'isAdmin' => \App\Http\Middleware\AdminMiddleware::class, 'clearance' => \App\Http\Middleware\ClearanceMiddleware::class, ];
In both middelwares a 401 exception would be thrown if the conditions are not meet. Let's create a custom 401 error page:
@extends('layouts.app') @section('content') <div class='col-lg-4 col-lg-offset-4'> <h1><center>401<br> ACCESS DENIED</center></h1> </div> @endsection
Wrapping Up
First lets create an 'Admin' user and then create the necessary permissions and roles. Click on Register and create a user, then go to http://localhost:8000/permissions and create permissions to Create Post, Edit Post, Delete Post and Administer roles & permissions. After creating these permissions, your permissions page should look like this:
Next, you need to create roles to which you would add the Create, Edit and Delete Permissions. Click on Roles and create these roles:
Admin- A user assigned to this role would have all permissions
Owner- A user assigned to this role would have selected permissions assigned to it by Admin
Finally assign the Role of 'Admin' to the currently logged in User. Click on Users and then Edit. Check the Admin box under Give Role:
After assigning the 'Admin' role to our user, notice that you now have a new Admin link in the drop of the navigation, this links to our users page. Now create a new user and give it the more restrictive role of Owner. If you login as this user and try to visit the User, Role or Permission pages you get this as expected:
The Owner role does not have permission to Administer Roles & Users hence the exception is thrown.
To demonstrate how this works for posts, create a post by clicking on New Article. After creating the post, view the post and you would notice you have along with the Back button, an Edit and Delete button as shown below:
Now if you logout and view the post only the Back button will be available to us. This also works if you have a logged in user who does not have permissions to Edit or Delete Post.
Conclusion
The laravel-permission package makes it relatively easy to build a role and permission system. To recap we have considered installation of the laravel-permission package, laravel-permission blade directives, creating a custom middleware and implementing an access control list in a Laravel application. You can look at the final product on Github and if you have any questions or comments, don’t hesitate to post them below.
via Scotch.io http://ift.tt/2qogmXD
0 notes
laravelvuejs · 6 years ago
Text
Authentication in Laravel Tutorial for PHP applications 102 - Laravel
Authentication in Laravel Tutorial for PHP applications 102 – Laravel
Authentication in Laravel Tutorial for PHP applications 102 – Laravel
[ad_1]
Authentication in Laravel Tutorial for PHP applications. (see shortcuts below to key points) Adam Culp of Beachcasts php programming videos shares how to create authentication in Laravel using the Artisan make:auth command.
Please * LIKE, COMMENT, AND SUBSCRIBE * – and share with others!
Key Topics: – Create…
View On WordPress
0 notes
laravelvuejs · 5 years ago
Photo
Tumblr media
Laravel 5.4 Registration Form Tutorial This video will help you people to learn how to use different form elements to develop an online application form using PHP MVC Framework Laravel 5.4. source
0 notes
laravelvuejs · 6 years ago
Text
Laravel 5.8 Tutorial From Scratch - e09 - Form Validation - Laravel
Laravel 5.8 Tutorial From Scratch – e09 – Form Validation – Laravel
Laravel 5.8 Tutorial From Scratch – e09 – Form Validation – Laravel
[ad_1]
Now that we are adding customers, we need to add some validation to our form. Laravel makes this process very easy, follow along as we make the name field required.
For the best experience, follow along in our interactive school at https://www.coderstape.com
Resources Course Source Code https://github.com/coderstape/laravel…
View On WordPress
0 notes
airman7com · 5 years ago
Text
Laravel 7.x, 6 Tutorial Contoh Pendaftaran Registrasi Kustom
Laravel 6 sistem pendaftaran masuk kustom dengan contoh. Tutorial ini menunjukkan, bagaimana Anda dapat membuat aplikasi pendaftaran masuk khusus pertama Anda menggunakan laravel versi 6 dengan contoh.
Tutorial ini adalah panduan langkah demi langkah, cara membuat pengontrol, rute, model, dan file tampilan blade.
How you can create forms login & registration form and how to validate the form of…
View On WordPress
0 notes
Text
Which PHP Framework is better to use and learn for Custom Web Applications & Why?
Tumblr media
PHP is essentially the most loved programming language when it comes to Website Development as well as complex Web Applications. However, Web Development can become trickier with increasing complexity. In such cases, PHP frameworks such as Codigniter, Laravel, Symphony and others come to the rescue. Here is everything you need to know about them and learn how to make most of Codeigniter Development, Laravel Development, Symphony Development, Zend Development etc…
CodeIgniter: Codeigniter is among the oldest PHP frameworks, having been around since 2006. Some of the features worth mentioning here are:
Model-View-Controller Based System: ensures scalable and well segregated development.
Light Weight: Web applications built on CodeIgniter are blazingly fast.
Database support
Support for email, image manipulation, FTP upload and much more.
Codeigniter Development is fun when you work with some of the brightest minds in the industry. Check with your service provider how well versed is their employees in CodeIgniter.
Laravel Development
Though Laravel is a late entrant to the field, it is essentially the hottest property in the town. As per a survey by popular site Sitepoint, it is the most preferred choice among developers. What is the reason behind the popularity of Laravel development? Here are some of the reasons behind its stupendous popularity:
Support for multiple file systems
Authentication feature that saves developers from writing tons of authentication related code
Route caching to speed up the application route registration
Highly improved method injection feature
Events object that helps speeding up Laravel development
Inbuilt templates that help in creating awesome content with lightning quick speed
Eloquent ORM to write database queries
MVC architecture support
Symphony Development
Symphony is yet another popular PHP framework that is immensely rich in incredible features. This is precisely the reason why it has enjoyed continuous love from developers all over the globe. Here are some of such features that deserve a mention:
Rich in features that make it flexible: Bundles are collection of files that make installation of new features tremendously easy. For instance, adding a new blog or a shopping cart can be done pretty easily by doing simple configuration. A number of similar such features essentially make Symphony a darling to web developers.
Commercial support: Commercial support from its parent company, SensioLabs has ensured that it has professionally curated tutorials and a lot of support as well.
-Ease of testing: PHPUnit Testing Library makes unit testing considerably easy.
Large community: Over the years, Symphony developers have ushered in a large community and by seeking support from the same one can tide over even the most complex problems.
Zend Development
Reasons to go for Zend development:
Extensible: Based on object oriented programming, Zend framework is immensely extendable. Zend developers can write awesome applications using its features like interfaces and inheritance without having to disturb the Zend framework codebase.
Decoupling lets you to use the features you need and skip everything else: Zend MVC architecture is so flexible that it lets you use only the features that are required for your application and skip those that you don’t need. This is essentially made possible with the help of classes based approach.
A variety of components that let you perform awesome tasks: You can do a lot with the vast variety of components like authentication, access control, create forms, RSS feed and so on with easily reusable components. So, step forward and implement that cracking functionality that you always wanted to add.
CakePHP: Here are some features of CakePHP, another immensely popular PHP framework that enjoys favor from many PHP developers:
MVC architecture: You can build scalable and inherently complex web applications using this framework
Object Relation Mapping: With the help of this feature you can write database queries with immense ease
Class inheritance: Class inheritence helps you to scale applications without unnecessary code and complications
Built-in validation: The validation related tasks can be completed without having to write enormous pieces of code thanks to the built-in validation featue
Yii: Some noteworthy features of Yii PHP framework:
Tremendous speed: Yii PHP framework is immensely fast and web applications written on it run like a charm
Form validation made easy
Enhanced security
CRUD validation
Authentication and Authorization features are in-built
The most popular PHP framework
Among all the PHP frameworks available today, the most popular one among these seems to be Laravel, given that it is used by over 50% of all PHP developers. Codeigniter and Symphony are up next due to their stupendous features, but even then they are far behind Laravel in terms of overall popularity.
Author Bio: pushpendra singh is an Freelancer web developer working with F5 Buddy Professional web development company. You can contact her in order to hire a web developer to avail the highly functional web development and eCommerce solutions. He has several years of experience in the field of web development. He has successfully worked on various project and given on time delivery.
0 notes
mbaljeetsingh · 8 years ago
Text
User Authorization in Laravel 5.4 with Spatie Laravel-Permission
What We'll Build
When building an application, we often need to set up an access control list (ACL). An ACL specifies the level of permission granted to a user of an application. For example a user John may have the permission to read and write to a resource while another user Smith may have the permission only to read the resource.
In this tutorial, I will teach you how to add access control to a Laravel app using Laravel-permission package. For this tutorial we will build a simple blog application where users can be assigned different levels of permission. Our user admin page will look like this:
Why Use Laravel-Permission
The Laravel-Permission package is built on top of Laravel's authorization features introduced in the 5.1.1 release. Although there are other packages that claim to offer similar functionalities, none of them have the same level of activity and maintenance as the laravel-permission package.
Development Environment and Installation
You can get Laravel up and running by first downloading the installer
composer global require "laravel/installer"
Then add $HOME/.composer/vendor/bin to your $PATH so the laravel executable can be located by your system. Now you can install the latest stable version of Laravel by running
laravel new
To install the laravel-permission package run
composer require spatie/laravel-permission
Next include the package to our list of service providers, in config/app.php add Spatie\Permission\PermissionServiceProvider::class so our file looks like this
'providers' => [ ... Spatie\Permission\PermissionServiceProvider::class, ];
Next publish the migration file for this package with the command
php artisan vendor:publish --provider="Spatie\Permission\PermissionServiceProvider" --tag="migrations"
Database Setup and Migrations
Next create the database and update the .env file to include the database information. For example, for this tutorial the database information section of the .env looks like this:
DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE=acl4 DB_USERNAME=root DB_PASSWORD=
To build the tables, run
php artisan migrate
Please note that in Laravel 5.4 the default character set is changed to utf8mb4, therefore if you are running MariaDB or MYSQL version lower than 5.7.7 you may get this error when trying to run migration files
[Illuminate\Database\QueryException] SQLSTATE[42000]: Syntax error or access violation: 1071 Specified key was too long; max key length is 767 bytes (SQL: alter table users add unique users_email_unique(email)) [PDOException] SQLSTATE[42000]: Syntax error or access violation: 1071 Specified key was too long; max key length is 767 bytes
To fix this error edit the app\Providers\AppServiceProvider.php file, setting the default string length in the boot method
use Illuminate\Support\Facades\Schema; public function boot() { Schema::defaultStringLength(191); }
After that run the migration again. If it works as normal you would find the following tables in your database:
migrations: This keeps track of migration process that have ran
users: This holds the users data of the application
password_resets: Holds token information when users request a new password
permissions: This holds the various permissions needed in the application
roles: This holds the roles in our application
role_has_permission: This is a pivot table that holds relationship information between the permissions table and the role table
user_has_roles: Also a pivot table, holds relationship information between the roles and the users table.
user_has_permissions: Also a pivot table, holds relationship information between the users table and the permissions table.
Publish the configuration file for this package by running
php artisan vendor:publish --provider="Spatie\Permission\PermissionServiceProvider" --tag="config"
The config file allows us to set the location of the Eloquent model of the permission and role class. You can also manually set the table names that should be used to retrieve your roles and permissions. Next we need to add the HasRoles trait to the User model:
use Illuminate\Foundation\Auth\User as Authenticatable; use Spatie\Permission\Traits\HasRoles; class User extends Authenticatable { use HasRoles; // ... }
Laravel Collective HTML Form builder
Next install Laravel Collective HTML Form builder as this will be useful further on when we are creating our forms:
composer require laravelcollective/html
Then add your new provider to the providers array of config/app.php:
'providers' => [ ... Collective\Html\HtmlServiceProvider::class, ];
Finally, add two class aliases to the aliases array of config/app.php:
'aliases' => [ // ... 'Form' => Collective\Html\FormFacade::class, 'Html' => Collective\Html\HtmlFacade::class, // ... ],
That's all the installation and configuration needed. A role can be created like a regular Eloquent model, like this:
use Spatie\Permission\Models\Role; use Spatie\Permission\Models\Permission; $role = Role::create(['name' => 'writer']); $permission = Permission::create(['name' => 'edit articles']);
You can also get the permissions associated to a user like this:
$permissions = $user->permissions;
And using the pluck method, pluck() you can get the role names associated with a user like this:
$roles = $user->roles()->pluck('name');
Other methods available to us include:
givePermissionTo(): Allows us to give persmission to a user or role
revokePermissionTo(): Revoke permission from a user or role
hasPermissionTo(): Check if a user or role has a given permission
assignRole(): Assigns role to a user
removeRole(): Removes role from a user
hasRole(): Checks if a user has a role
hasAnyRole(Role::all()): Checks if a user has any of a given list of roles
hasAllRoles(Role::all()): Checks if a user has all of a given list of role
The methods assignRole, hasRole, hasAnyRole, hasAllRoles and removeRole can accept a string, a Spatie\Permission\Models\Role-object or an \Illuminate\Support\Collection object. The givePermissionTo and revokePermissionTo methods can accept a string or a Spatie\Permission\Models\Permission object.
Laravel-Permission also allows to use Blade directives to verify if the logged in user has all or any of a given list of roles:
@role('writer') I'm a writer! @else I'm not a writer... @endrole @hasrole('writer') I'm a writer! @else I'm not a writer... @endhasrole @hasanyrole(Role::all()) I have one or more of these roles! @else I have none of these roles... @endhasanyrole @hasallroles(Role::all()) I have all of these roles! @else I don't have all of these roles... @endhasallroles
The Blade directives above depends on the users role. Sometimes we need to check directly in our view if a user has a certain permission. You can do that using Laravel's native @can directive:
@can('Edit Post') I have permission to edit @endcan
Controllers, Authentication and Views
You will need a total of four controllers for this application. Let's use resource controllers, as this automatically adds stub methods for us. Our controllers will be called
PostController
UserController
RoleController
PermissionController
Before working on these controllers let's create our authentication system. With one command Laravel provides a quick way to scaffold all of the routes and views needed for authentication.
php artisan make:auth
After running this command you would notice two new links for user login and registration in the home page.
This command also creates a HomeController (you can delete this as it won't be needed), a resources/views/layouts/app.blade.php file which contains markup that would be shared by all our views and an app/Http/Controllers/Auth directory which contains the controllers for registration and login. Switch into this directory and open the RegisterController.phpfile. Remove the bcrypt function in the create method, so the the method looks like this
protected function create(array $data) { return User::create([ 'name' => $data['name'], 'email' => $data['email'], 'password' => $data['password'], ]); }
Instead let's define a mutator in app\User.php which would encrypt all our password fields. In app\User.php add this method:
public function setPasswordAttribute($password) { $this->attributes['password'] = bcrypt($password); }
This would provide the same functionality as before but now you don't need to write the bcrypt function when dealing with the password field in subsequent controllers.
Also in the RegisterController.phpfile. Change the $redirectTo property to:
protected $redirectTo = '/';
Do the same thing in the LoginController.phpfile.
Since the HomeController has been deleted our users are now redirected to the home page which would contain a list of our blog posts.
Next let's edit the resources/views/layouts/app.blade.php file to include: an extra drop-down 'Admin' link to view all users and an errors file which checks if our form produced any error. The 'Admin' link would only be viewed by users with the 'Admin' Role. We would also create a custom styles.css which would have extra styling for our resources/views/posts/index.blade.php view. The styling is just a paragraph in the teaser of our index view, the file should be located in public/css/styles.css
<!DOCTYPE html> <html lang=""> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- CSRF Token --> <meta name="csrf-token" content=""> <title></title> <!-- Styles --> <link href="http://ift.tt/1uaQUM0" rel="stylesheet"> <link href="http://ift.tt/1uaQUM0" rel="stylesheet"> <link rel="stylesheet" href="http://ift.tt/2cYLUyN; integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> <!-- Scripts --> <script> window.Laravel = {!! json_encode([ 'csrfToken' => csrf_token(), ]) !!}; </script> <script src="http://ift.tt/2qqGPlI;></script> </head> <body> <div id="app"> <nav class="navbar navbar-default navbar-static-top"> <div class="container"> <div class="navbar-header"> <!-- Collapsed Hamburger --> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#app-navbar-collapse"> <span class="sr-only">Toggle Navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <!-- Branding Image --> <a class="navbar-brand" href="http://ift.tt/1uaQUM0"> </a> </div> <div class="collapse navbar-collapse" id="app-navbar-collapse"> <!-- Left Side Of Navbar --> <ul class="nav navbar-nav"> <li><a href="http://ift.tt/1uaQUM0">Home</a></li> @if (!Auth::guest()) <li><a href="http://ift.tt/1uaQUM0">New Article</a></li> @endif </ul> <!-- Right Side Of Navbar --> <ul class="nav navbar-nav navbar-right"> <!-- Authentication Links --> @if (Auth::guest()) <li><a href="http://ift.tt/1uaQUM0">Login</a></li> <li><a href="http://ift.tt/1uaQUM0">Register</a></li> @else <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false"> <span class="caret"></span> </a> <ul class="dropdown-menu" role="menu"> <li> @role('Admin') <a href="#"><i class="fa fa-btn fa-unlock"></i>Admin</a> @endrole <a href="http://ift.tt/1uaQUM0" onclick="event.preventDefault(); document.getElementById('logout-form').submit();"> Logout </a> <form id="logout-form" action="" method="POST" style="display: none;"> </form> </li> </ul> </li> @endif </ul> </div> </div> </nav> @if(Session::has('flash_message')) <div class="container"> <div class="alert alert-success"><em> {!! session('flash_message') !!}</em> </div> </div> @endif <div class="row"> <div class="col-md-8 col-md-offset-2"> @include ('errors.list') </div> </div> @yield('content') </div> <!-- Scripts --> <script src=""></script> </body> </html>
The error file is:
@if (count($errors) > 0) <div class="alert alert-danger"> <ul> @foreach ($errors->all() as $error) <li></li> @endforeach </ul> </div> @endif
and the styles.css file is simply:
p.teaser { text-indent: 30px; }
Post Controller
First, let's create the migration and model files for the PostController
php artisan make:model Post -m
This command generates a migration file in app/database/migrations for generating a new MySQL table named posts in our database and a model file Post.phpin the app directory. Let's edit the migration file to include title and body fields of our post. Add a title and body field so the migration file looks like this:
<?php //database\migrations\xxxx_xx_xx_xxxxxx_create_posts_table.php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreatePostsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('posts', function (Blueprint $table) { $table->increments('id'); $table->string('title'); $table->text('body'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('posts'); } }
After saving the file, run migration again
php artisan migrate
You can now check the database for the post table and columns.
Next make the title and body field of the Post model mass assignable
namespace App; use Illuminate\Database\Eloquent\Model; class Post extends Model { protected $fillable = [ 'title', 'body' ]; }
Now let's generate our resource controller.
php artisan make:controller PostController --resource
This will create our controller with all the stub methods needed. Edit this file to look like this
<?php // app/Http/Controllers/PostController.php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Post; use Auth; use Session; class PostController extends Controller { public function __construct() { $this->middleware(['auth', 'clearance'])->except('index', 'show'); } /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { $posts = Post::orderby('id', 'desc')->paginate(5); //show only 5 items at a time in descending order return view('posts.index', compact('posts')); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { return view('posts.create'); } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { //Validating title and body field $this->validate($request, [ 'title'=>'required|max:100', 'body' =>'required', ]); $title = $request['title']; $body = $request['body']; $post = Post::create($request->only('title', 'body')); //Display a successful message upon save return redirect()->route('posts.index') ->with('flash_message', 'Article, '. $post->title.' created'); } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show($id) { $post = Post::findOrFail($id); //Find post of id = $id return view ('posts.show', compact('post')); } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function edit($id) { $post = Post::findOrFail($id); return view('posts.edit', compact('post')); } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update(Request $request, $id) { $this->validate($request, [ 'title'=>'required|max:100', 'body'=>'required', ]); $post = Post::findOrFail($id); $post->title = $request->input('title'); $post->body = $request->input('body'); $post->save(); return redirect()->route('posts.show', $post->id)->with('flash_message', 'Article, '. $post->title.' updated'); } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { $post = Post::findOrFail($id); $post->delete(); return redirect()->route('posts.index') ->with('flash_message', 'Article successfully deleted'); } }
Here the Post class was imported from our model and the Auth class which was generated with the make:auth command earlier. These were imported so that you would be able to make Eloquent queries on the Post table and so as to be able to have access to authentication information of our users. In the constructor two middlewares were called, one is auth which restricts access to the PostController methods to authenticated users the other is a custom middleware is yet to be created. This would be responsible for our Permissions and Roles system. Next, index and show are passed into the except method to allow all users to be able to view posts.
The index() method lists all the available posts. It queries the post table for all posts and passes this information to the view. Paginate() allows us to limit the number of posts in a page, in this case five.
The create() method simply returns the posts/create view which would contain a form for creating new posts. The store() method saves the information input from the posts/create view. The information is first validated and after it is saved, a flash message is passed to the view posts/index.
Our show() method of the PostController allows us to display a single post. This method takes the post id as an argument and passes it to the method Post::find(). The result of the query is then sent to our posts/show view.
The edit() method, similar to the create() method simply returns the posts/edit view which would contain a form for creating editing posts. The update() method takes the information from the posts/edit view and updates the record. The destroy() method let's us delete a post.
Now that you have the PostController you need to set up the routes. Edit your app/routes/web.php file to look like this:
<?php Route::get('/', function () { return view('welcome'); }); Auth::routes(); Route::get('/', 'PostController@index')->name('home'); Route::resource('users', 'UserController'); Route::resource('roles', 'RoleController'); Route::resource('permissions', 'PermissionController'); Route::resource('posts', 'PostController');
The / route is the route to our home page, here it was renamed to home The Auth route was generated when you ran the make:auth command. It handles authentication related routes. The other four routes are for resources that would be created later.
Post Views
Only four views are needed for our PostController. Create the files \resources\views\posts\index.blade.php, \resources\views\posts\create.blade.php, \resources\views\posts\show.blade.php, \resources\views\posts\edit.blade.php
Edit the index.blade.phpfile to look like this
@extends('layouts.app') @section('content') <div class="container"> <div class="row"> <div class="col-md-10 col-md-offset-1"> <div class="panel panel-default"> <div class="panel-heading"><h3>Posts</h3></div> <div class="panel-heading">Page of </div> @foreach ($posts as $post) <div class="panel-body"> <li style="list-style-type:disc"> <a href="http://ift.tt/1uaQUM0"><b></b><br> <p class="teaser"> </p> </a> </li> </div> @endforeach </div> <div class="text-center"> {!! $posts->links() !!} </div> </div> </div> </div> @endsection
Notice that this file extends views\layouts\app.php file, which was generated earlier by the make:auth command.
The create.blade.php file looks like this
@extends('layouts.app') @section('title', '| Create New Post') @section('content') <div class="row"> <div class="col-md-8 col-md-offset-2"> <h1>Create New Post</h1> <hr> <div class="form-group"> <br> <br> </div> </div> </div> @endsection
The show view looks like this:
@extends('layouts.app') @section('title', '| View Post') @section('content') <div class="container"> <h1></h1> <hr> <p class="lead"> </p> <hr> {!! Form::open(['method' => 'DELETE', 'route' => ['posts.destroy', $post->id] ]) !!} <a href="http://ift.tt/1uaQUM0" class="btn btn-primary">Back</a> @can('Edit Post') <a href="http://ift.tt/1uaQUM0" class="btn btn-info" role="button">Edit</a> @endcan @can('Delete Post') {!! Form::submit('Delete', ['class' => 'btn btn-danger']) !!} @endcan {!! Form::close() !!} </div> @endsection
Here the can directive checks if a user has the permission to Edit or Delete Posts, if so the Edit and Delete button will be displayed. If the user does not have these permissions, only the Back button would be displayed.
The edit view just displays a edit form that will be used to update records:
@extends('layouts.app') @section('title', '| Edit Post') @section('content') <div class="row"> <div class="col-md-8 col-md-offset-2"> <h1>Edit Post</h1> <hr> <div class="form-group"> <br> <br> </div> </div> </div> @endsection
If you visit the home page you would see this
User Controller
The UserController will handle displaying all users, creating of new users, editing users, assigning roles to users and deleting users. As before generate the controller by running
php artisan make:controller UserController --resource
Then replace the content of this file with:
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\User; use Auth; //Importing laravel-permission models use Spatie\Permission\Models\Role; use Spatie\Permission\Models\Permission; //Enables us to output flash messaging use Session; class UserController extends Controller { public function __construct() { $this->middleware(['auth', 'isAdmin']); //isAdmin middleware lets only users with a //specific permission permission to access these resources } /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { //Get all users and pass it to the view $users = User::all(); return view('users.index')->with('users', $users); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { //Get all roles and pass it to the view $roles = Role::get(); return view('users.create', ['roles'=>$roles]); } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { //Validate name, email and password fields $this->validate($request, [ 'name'=>'required|max:120', 'email'=>'required|email|unique:users', 'password'=>'required|min:6|confirmed' ]); $user = User::create($request->only('email', 'name', 'password')); //Retrieving only the email and password data $roles = $request['roles']; //Retrieving the roles field //Checking if a role was selected if (isset($roles)) { foreach ($roles as $role) { $role_r = Role::where('id', '=', $role)->firstOrFail(); $user->assignRole($role_r); //Assigning role to user } } //Redirect to the users.index view and display message return redirect()->route('users.index') ->with('flash_message', 'User successfully added.'); } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show($id) { return redirect('users'); } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function edit($id) { $user = User::findOrFail($id); //Get user with specified id $roles = Role::get(); //Get all roles return view('users.edit', compact('user', 'roles')); //pass user and roles data to view } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update(Request $request, $id) { $user = User::findOrFail($id); //Get role specified by id //Validate name, email and password fields $this->validate($request, [ 'name'=>'required|max:120', 'email'=>'required|email|unique:users,email,'.$id, 'password'=>'required|min:6|confirmed' ]); $input = $request->only(['name', 'email', 'password']); //Retreive the name, email and password fields $roles = $request['roles']; //Retreive all roles $user->fill($input)->save(); if (isset($roles)) { $user->roles()->sync($roles); //If one or more role is selected associate user to roles } else { $user->roles()->detach(); //If no role is selected remove exisiting role associated to a user } return redirect()->route('users.index') ->with('flash_message', 'User successfully edited.'); } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { //Find a user with a given id and delete $user = User::findOrFail($id); $user->delete(); return redirect()->route('users.index') ->with('flash_message', 'User successfully deleted.'); } }
Here the User class, the Role class, the Permission class and the Auth class are imported. In the constructor the auth middleware is called to make sure only authenticated users have access to the User resource. A custom middleware isAdmin is also called. This checks if the authenticated user has administrator privileges. This middleware will be created later.
The index() method gets all users from the Users table and passes it to the index view which will display all users in a table. The create() method first gets all the Roles from the Roles table and passes it to the create view. This is so that Roles can be added when creating a User.
The store() method saves the input from the create view, after validating the input, looping through the Roles that was passed in the form and assigning these Roles to the User. The show()method just redirects back to the users page as for this demonstration, we wont need to show each user individually.
The edit() method gets the user corresponding to the id passed, then gets all roles and passes it to the edit view. The update() method validates data from the edit view and saves the updated name and password fields. It gets all roles from the roles table and while looping through them, removes any role assign to the user. It then takes the role data inputted from the form, matches them with the values in the databases and assigns these roles to the user.
The destroy() method allows us to delete a user along with it's corresponding role.
User Views
Three views are needed here: index, create and edit views. The index view would contain a table that lists all our users and their roles.
@extends('layouts.app') @section('title', '| Users') @section('content') <div class="col-lg-10 col-lg-offset-1"> <h1><i class="fa fa-users"></i> User Administration <a href="http://ift.tt/1uaQUM0" class="btn btn-default pull-right">Roles</a> <a href="http://ift.tt/1uaQUM0" class="btn btn-default pull-right">Permissions</a></h1> <hr> <div class="table-responsive"> <table class="table table-bordered table-striped"> <thead> <tr> <th>Name</th> <th>Email</th> <th>Date/Time Added</th> <th>User Roles</th> <th>Operations</th> </tr> </thead> <tbody> @foreach ($users as $user) <tr> <td></td> <td></td> <td></td> <td></td> <td> <a href="http://ift.tt/1uaQUM0" class="btn btn-info pull-left" style="margin-right: 3px;">Edit</a> {!! Form::open(['method' => 'DELETE', 'route' => ['users.destroy', $user->id] ]) !!} {!! Form::submit('Delete', ['class' => 'btn btn-danger']) !!} {!! Form::close() !!} </td> </tr> @endforeach </tbody> </table> </div> <a href="http://ift.tt/1uaQUM0" class="btn btn-success">Add User</a> </div> @endsection
The create view is just a form that allows us to create new users and assign roles to them.
@extends('layouts.app') @section('title', '| Add User') @section('content') <div class='col-lg-4 col-lg-offset-4'> <h1><i class='fa fa-user-plus'></i> Add User</h1> <hr> <div class="form-group"> </div> <div class="form-group"> </div> <div class='form-group'> @foreach ($roles as $role) <br> @endforeach </div> <div class="form-group"> <br> </div> <div class="form-group"> <br> </div> </div> @endsection
The edit view is a form that allows us to edit users and their roles. Using Laravel's form model binding the form is automatically populated with the previous values.
@extends('layouts.app') @section('title', '| Edit User') @section('content') <div class='col-lg-4 col-lg-offset-4'> <h1><i class='fa fa-user-plus'></i> Edit </h1> <hr> <div class="form-group"> </div> <div class="form-group"> </div> <h5><b>Give Role</b></h5> <div class='form-group'> @foreach ($roles as $role) <br> @endforeach </div> <div class="form-group"> <br> </div> <div class="form-group"> <br> </div> </div> @endsection
Permission Controller
Now let's tackle the PermissionControllerCreate the file and paste the following code:
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Auth; //Importing laravel-permission models use Spatie\Permission\Models\Role; use Spatie\Permission\Models\Permission; use Session; class PermissionController extends Controller { public function __construct() { $this->middleware(['auth', 'isAdmin']); //isAdmin middleware lets only users with a //specific permission permission to access these resources } /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { $permissions = Permission::all(); //Get all permissions return view('permissions.index')->with('permissions', $permissions); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { $roles = Role::get(); //Get all roles return view('permissions.create')->with('roles', $roles); } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { $this->validate($request, [ 'name'=>'required|max:40', ]); $name = $request['name']; $permission = new Permission(); $permission->name = $name; $roles = $request['roles']; $permission->save(); if (!empty($request['roles'])) { //If one or more role is selected foreach ($roles as $role) { $r = Role::where('id', '=', $role)->firstOrFail(); //Match input role to db record $permission = Permission::where('name', '=', $name)->first(); //Match input //permission to db record $r->givePermissionTo($permission); } } return redirect()->route('permissions.index') ->with('flash_message', 'Permission'. $permission->name.' added!'); } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show($id) { return redirect('permissions'); } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function edit($id) { $permission = Permission::findOrFail($id); return view('permissions.edit', compact('permission')); } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update(Request $request, $id) { $permission = Permission::findOrFail($id); $this->validate($request, [ 'name'=>'required|max:40', ]); $input = $request->all(); $permission->fill($input)->save(); return redirect()->route('permissions.index') ->with('flash_message', 'Permission'. $permission->name.' updated!'); } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { $permission = Permission::findOrFail($id); //Make it impossible to delete this specific permission if ($permission->name == "Administer roles & permissions") { return redirect()->route('permissions.index') ->with('flash_message', 'Cannot delete this Permission!'); } $permission->delete(); return redirect()->route('permissions.index') ->with('flash_message', 'Permission deleted!'); } }
In the store() method, we are making it possible for a role to be selected as a permission is created. After validating and saving the permission name field, a check is done if a role was selected if it was, a permission is assigned to the selected role.
Permission View
Three views are needed here as well. The index view would list in a table all the available permissions, the create view is a form which would be used to create a new permission and the edit view is a form that let's us edit existing permission.
@extends('layouts.app') @section('title', '| Permissions') @section('content') <div class="col-lg-10 col-lg-offset-1"> <h1><i class="fa fa-key"></i>Available Permissions <a href="http://ift.tt/1uaQUM0" class="btn btn-default pull-right">Users</a> <a href="http://ift.tt/1uaQUM0" class="btn btn-default pull-right">Roles</a></h1> <hr> <div class="table-responsive"> <table class="table table-bordered table-striped"> <thead> <tr> <th>Permissions</th> <th>Operation</th> </tr> </thead> <tbody> @foreach ($permissions as $permission) <tr> <td></td> <td> <a href="http://ift.tt/1uaQUM0" class="btn btn-info pull-left" style="margin-right: 3px;">Edit</a> {!! Form::open(['method' => 'DELETE', 'route' => ['permissions.destroy', $permission->id] ]) !!} {!! Form::submit('Delete', ['class' => 'btn btn-danger']) !!} {!! Form::close() !!} </td> </tr> @endforeach </tbody> </table> </div> <a href="http://ift.tt/1uaQUM0" class="btn btn-success">Add Permission</a> </div> @endsection
The following is the create view
@extends('layouts.app') @section('title', '| Create Permission') @section('content') <div class='col-lg-4 col-lg-offset-4'> <h1><i class='fa fa-key'></i> Add Permission</h1> <br> <div class="form-group"> </div><br> @if(!$roles->isEmpty()) //If no roles exist yet <h4>Assign Permission to Roles</h4> @foreach ($roles as $role) <br> @endforeach @endif <br> </div> @endsection
And finally the edit view:
@extends('layouts.app') @section('title', '| Edit Permission') @section('content') <div class='col-lg-4 col-lg-offset-4'> <h1><i class='fa fa-key'></i> Edit </h1> <br> <div class="form-group"> </div> <br> </div> @endsection
Role Controller
The RoleController is quite similar to the UserController. This controller will allow us to create roles and assign one or more permissions to a role. Create the file and paste the following code:
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Auth; //Importing laravel-permission models use Spatie\Permission\Models\Role; use Spatie\Permission\Models\Permission; use Session; class RoleController extends Controller { public function __construct() { $this->middleware(['auth', 'isAdmin']);//isAdmin middleware lets only users with a //specific permission permission to access these resources } /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { $roles = Role::all();//Get all roles return view('roles.index')->with('roles', $roles); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { $permissions = Permission::all();//Get all permissions return view('roles.create', ['permissions'=>$permissions]); } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { //Validate name and permissions field $this->validate($request, [ 'name'=>'required|unique:roles|max:10', 'permissions' =>'required', ] ); $name = $request['name']; $role = new Role(); $role->name = $name; $permissions = $request['permissions']; $role->save(); //Looping thru selected permissions foreach ($permissions as $permission) { $p = Permission::where('id', '=', $permission)->firstOrFail(); //Fetch the newly created role and assign permission $role = Role::where('name', '=', $name)->first(); $role->givePermissionTo($p); } return redirect()->route('roles.index') ->with('flash_message', 'Role'. $role->name.' added!'); } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show($id) { return redirect('roles'); } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function edit($id) { $role = Role::findOrFail($id); $permissions = Permission::all(); return view('roles.edit', compact('role', 'permissions')); } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update(Request $request, $id) { $role = Role::findOrFail($id);//Get role with the given id //Validate name and permission fields $this->validate($request, [ 'name'=>'required|max:10|unique:roles,name,'.$id, 'permissions' =>'required', ]); $input = $request->except(['permissions']); $permissions = $request['permissions']; $role->fill($input)->save(); $p_all = Permission::all();//Get all permissions foreach ($p_all as $p) { $role->revokePermissionTo($p); //Remove all permissions associated with role } foreach ($permissions as $permission) { $p = Permission::where('id', '=', $permission)->firstOrFail(); //Get corresponding form //permission in db $role->givePermissionTo($p); //Assign permission to role } return redirect()->route('roles.index') ->with('flash_message', 'Role'. $role->name.' updated!'); } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { $role = Role::findOrFail($id); $role->delete(); return redirect()->route('roles.index') ->with('flash_message', 'Role deleted!'); } }
Roles View
Three views are needed here as well. The index view to display available roles and associated permissions, the create view to add a new role and a view to edit an existing role. Create the index.blade.php file and paste the following:
@extends('layouts.app') @section('title', '| Roles') @section('content') <div class="col-lg-10 col-lg-offset-1"> <h1><i class="fa fa-key"></i> Roles <a href="http://ift.tt/1uaQUM0" class="btn btn-default pull-right">Users</a> <a href="http://ift.tt/1uaQUM0" class="btn btn-default pull-right">Permissions</a></h1> <hr> <div class="table-responsive"> <table class="table table-bordered table-striped"> <thead> <tr> <th>Role</th> <th>Permissions</th> <th>Operation</th> </tr> </thead> <tbody> @foreach ($roles as $role) <tr> <td></td> <td></td> <td> <a href="http://ift.tt/1uaQUM0" class="btn btn-info pull-left" style="margin-right: 3px;">Edit</a> {!! Form::open(['method' => 'DELETE', 'route' => ['roles.destroy', $role->id] ]) !!} {!! Form::submit('Delete', ['class' => 'btn btn-danger']) !!} {!! Form::close() !!} </td> </tr> @endforeach </tbody> </table> </div> <a href="http://ift.tt/1uaQUM0" class="btn btn-success">Add Role</a> </div> @endsection
For the create view:
@extends('layouts.app') @section('title', '| Add Role') @section('content') <div class='col-lg-4 col-lg-offset-4'> <h1><i class='fa fa-key'></i> Add Role</h1> <hr> <div class="form-group"> </div> <h5><b>Assign Permissions</b></h5> <div class='form-group'> @foreach ($permissions as $permission) <br> @endforeach </div> </div> @endsection
And for the edit view:
@extends('layouts.app') @section('title', '| Edit Role') @section('content') <div class='col-lg-4 col-lg-offset-4'> <h1><i class='fa fa-key'></i> Edit Role: </h1> <hr> <div class="form-group"> </div> <h5><b>Assign Permissions</b></h5> @foreach ($permissions as $permission) <br> @endforeach <br> </div> @endsection
Middleware
To restrict access to the roles and permissions page, a middleware was included called isAdmin in our PermissionController and RoleController. This middleware counts how many users are in the Users table, and if there are more than one users, it checks if the current authenticated User has the permission to 'Administer roles & permissions'. To create a permission visit http://localhost:8000/permissions/create. Then go to http://localhost:8000/roles/create to create a role, to which you can now assign the permission you created. For example you can create a permission called 'Administer roles & permissions' and a 'Admin' role to which you would assign this permission. Create the AdminMiddleware in the directory app/Http/Middleware/ and enter the following code:
<?php namespace App\Http\Middleware; use Closure; use Illuminate\Support\Facades\Auth; use App\User; class AdminMiddleware { /** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @return mixed */ public function handle($request, Closure $next) { $user = User::all()->count(); if (!($user == 1)) { if (!Auth::user()->hasPermissionTo('Administer roles & permissions')) //If user does //not have this permission { abort('401'); } } return $next($request); } }
A middleware called clearance was also included in our PostController. This middleware would check if a user has the permissions Administer roles & permissions, Create Post, Edit Post and Delete Post.
<?php namespace App\Http\Middleware; use Closure; use Illuminate\Support\Facades\Auth; class ClearanceMiddleware { /** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @return mixed */ public function handle($request, Closure $next) { if (Auth::user()->hasPermissionTo('Administer roles & permissions')) //If user has this //permission { return $next($request); } if ($request->is('posts/create'))//If user is creating a post { if (!Auth::user()->hasPermissionTo('Create Post')) { abort('401'); } else { return $next($request); } } if ($request->is('posts/*/edit')) //If user is editing a post { if (!Auth::user()->hasPermissionTo('Edit Post')) { abort('401'); } else { return $next($request); } } if ($request->isMethod('Delete')) //If user is deleting a post { if (!Auth::user()->hasPermissionTo('Delete Post')) { abort('401'); } else { return $next($request); } } return $next($request); } }
Add AdminMiddleware::class and ClearanceMiddleware::class to the $routeMiddleware property of /app/Http/kernel.php like this:
protected $routeMiddleware = [ 'auth' => \Illuminate\Auth\Middleware\Authenticate::class, 'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class, 'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class, 'can' => \Illuminate\Auth\Middleware\Authorize::class, 'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class, 'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class, 'isAdmin' => \App\Http\Middleware\AdminMiddleware::class, 'clearance' => \App\Http\Middleware\ClearanceMiddleware::class, ];
In both middelwares a 401 exception would be thrown if the conditions are not meet. Let's create a custom 401 error page:
@extends('layouts.app') @section('content') <div class='col-lg-4 col-lg-offset-4'> <h1><center>401<br> ACCESS DENIED</center></h1> </div> @endsection
Wrapping Up
First lets create an 'Admin' user and then create the necessary permissions and roles. Click on Register and create a user, then go to http://localhost:8000/permissions and create permissions to Create Post, Edit Post, Delete Post and Administer roles & permissions. After creating these permissions, your permissions page should look like this:
Next, you need to create roles to which you would add the Create, Edit and Delete Permissions. Click on Roles and create these roles:
Admin- A user assigned to this role would have all permissions
Owner- A user assigned to this role would have selected permissions assigned to it by Admin
Finally assign the Role of 'Admin' to the currently logged in User. Click on Users and then Edit. Check the Admin box under Give Role:
After assigning the 'Admin' role to our user, notice that you now have a new Admin link in the drop of the navigation, this links to our users page. Now create a new user and give it the more restrictive role of Owner. If you login as this user and try to visit the User, Role or Permission pages you get this as expected:
The Owner role does not have permission to Administer Roles & Users hence the exception is thrown.
To demonstrate how this works for posts, create a post by clicking on New Article. After creating the post, view the post and you would notice you have along with the Back button, an Edit and Delete button as shown below:
Now if you logout and view the post only the Back button will be available to us. This also works if you have a logged in user who does not have permissions to Edit or Delete Post.
Conclusion
The laravel-permission package makes it relatively easy to build a role and permission system. To recap we have considered installation of the laravel-permission package, laravel-permission blade directives, creating a custom middleware and implementing an access control list in a Laravel application. You can look at the final product on Github and if you have any questions or comments, don’t hesitate to post them below.
via Scotch.io http://ift.tt/2qobS1L
0 notes