#explain facades in laravel
Explore tagged Tumblr posts
Text
Laravel Beginner tutorial | Laravel Facade - simplest explanation - Laravel
Laravel Beginner tutorial | Laravel Facade – simplest explanation – Laravel
Laravel Beginner tutorial | Laravel Facade – simplest explanation – Laravel
[ad_1]
Simplest Explanation of Laravel Facades. Implement your own Facade. What is Laravel Facades.
Full course at https://bitfumes.com/courses/laravel/laravel-for-beginner-from-download-to-deploy
Check https://bitfumes.com For ads free and more advanced courses (use Coupon code WELCOME60 to get 60% discount)
Join Our…
View On WordPress
#bitfumes laravel#explain facades in laravel#facade in laravel#facade laravel example#how laravel facade works#laravel 2019 tutorial#laravel 5.8 facade#laravel 5.8 features#laravel 5.8 tutorial#laravel facade simple explanation#laravel facade tutorial#laravel facades#laravel facades explained#php framework laravel#php framework tutorial for beginners#what is facade in laravel
0 notes
Text
Facades or Helpers?
In Laravel code we often use helpers and facades interchangably and many of the facades that are used most in Laravel are also available as Facades
eg.
view('order.show'); view::make('order.show');
This is so prevalent, that I thought that helpers were part of Facades so when I went to create my own facade I couldnt understand why the helper function didnt work.
Slowly it dawned on me this was not the case and what I really needed was a facade and a helper function.
I found this very helpful article on Laravel news
https://laravel-news.com/creating-helpers
This explains very simply what helper functions are, where and how your crate them and how you autoload them.
Now I have a facade and a helper function and I'm happy.
0 notes
Photo

Facades in laravel explained
In general terms, a Facade (pronounced as /fəˈsɑːd/) is the exterior and front facing side of a building or any thing. Importance of facades are they are easy to notice and more prominent, similarly there is a concept of facades in laravel too. No, we are not developing a building through laravel rather we are going to manage our code readability and build easy to remember syntax of functions and classes through it.
As you know, there are two types of functions in any programming language so do in PHP, which are non static functions and static functions.
Table of Contents
What do we mean by non static functions ?
What are static functions, then ?
What are facades in Laravel ?
Why do we use facades ?
How do I create a facade class and use in my application ?
Conclusion
Objective of this example
Step 1. Create a folder with the name “Facades” in app directory
Step 2. Create 2 Files in Facades directory
Step 3. Add the code in web.php
#laravel#laravel framework#php laravel codeigniter html mysql#laravel market share#facade#facades#php#php programming#programming#software#itsolutionstuff#appdividend#slideshare#composer#service provider#programming jokes#blog#blog po#author#twitter#facebook marketing#Social media#social media marketing#pinterest
0 notes
Text
Two Best Laravel Packages to Manage Roles/Permissions
Roles and permissions are an important part of many web applications. Laravel historically had a lot of packages for them, and improved the core code as well. So what is the situation on this market today? What packages are the best to use? I’ve picked two.
Why Do You Need Packages?
Let’s start from the beginning—Laravel has its own core logic for managing permissions. It was introduced in version 5.1.11 and has remained almost unchanged since. There we have things like:
Gates and Policies
$this->authorize() method
@can and @cannot Blade commands
One might say it’s enough to have Laravel core and there’s no need for packages. This is part of the reason older packages are abandoned; core functions replaced them.
But there’s still an area where packages can help—to manage the permissions and roles, which is not easy in the core. And there are two packages which do that really well and are actively maintained:
Laravel-permission by Spatie
Bouncer by Joseph Silber
Special mention: santigarcor/laratrust, which is a fork of unmaintained Entrust, and could be a strong third contestant. The problem with Laratrust is it replaces default Laravel commands with its own, so you wouldn’t be able to use Gates or @can syntax. Instead, you would need to use $user->can(‘edit-user’) or @permission Blade command. But if you don’t care about those extra syntax pieces, Laratrust is a great package. It also has Teams functionality, which is not present in Spatie’s or Bouncer packages.
There are a few more options, but they seem outdated and not that active. Still, you may want to watch them for a potential comeback:
Zizaco / entrust
Romanbican / roles
Kodeine / Laravel-acl
Now, let’s get deeper into a “battle review” between two main contestants.
What Do These Packages Actually Do?
They give you an API to deal with roles and permissions more easily. Also, the final code is more reader-friendly and easier to understand.
Instead of creating all rules in Policies and Gates, which would be fragmented in a few different places, you would have code like this:
$user->givePermissionTo('edit articles'); // Spatie package $user->allow('ban-users'); // Bouncer package
Essentially, those two packages offer really similar functionality, with slightly different syntax and database structure. Let’s dig deeper and compare.
Installation and Usage
Both packages are installed similarly:
Add to composer and install.
Add a provider and facade (Bouncer) to config/app.php.
Publish and run migrations.
Add a special trait into User model (both packages use Traits).
That’s it; use package’s methods (optionally including its classes where needed).
Packages assume you already have a default Laravel users DB table, but don’t have any structure for roles/permissions. They will add their own tables and fields.
Both packages have clear documentation, and there were no issues whatsoever. Great job done on README files!
Database Structure
This is where the packages are quite different. Spatie’s package has these tables:
Some explanations here:
Field guard_name has default value web—package allows to use multiple guards.
As you can see, there are two pivot tables for permissions—one with roles, and one with users.
Field model_type has default value App\User so there’s no direct foreign key to users table, no other table has user_id field.
Now let’s look at Bouncer’s database:
Quite different, isn’t it? And even fewer relationships. Now, let me explain:
What Spatie calls “permissions,” Bouncer calls “abilities.” And then the “permissions” table is a set of abilities attached to an “entity.”
“Entity” (in all tables) is an object to assign abilities to. It may be a role or a user. Therefore, there is no direct relationship to user_id or users table; the same as with Spatie’s package.
There are a few more fields different from the previous package: abilities.title, abilities.only_owned, and roles.level. They add some additional functionality, but it is not well explained in the README file.
Spatie has guard fields which are not present in Bouncer.
All in all, Bouncer’s database structure seems a little more complicated and more difficult to understand at first, but with that comes a little more flexibility.
Available Methods
These packages do offer really similar functionality, so let’s compare in details.
Create Roles/Permissions/Abilities
Spatie
You can use facades of the package as normal facades of Laravel:
use Spatie\Permission\Models\Role; use Spatie\Permission\Models\Permission; Role::create(['name' => 'writer']); Permission::create(['name' => 'edit articles']);
Bouncer
You can create role and ability, and assignment all in one sentence:
Bouncer::allow('admin')->to('ban-users');
That’s it. Behind the scenes, Bouncer will create a Role model and an Ability model for you.
But you can also work with facades, too:
use Silber\Bouncer\Database\Ability; Ability::create(['name' => 'edit articles']);
As you can see, Bouncer has a little more functionality here with automatic “behind the scenes” model creation.
Assigning Roles to a User
Spatie
$user->assignRole('writer'); $user->assignRole(['writer', 'admin']); $user->removeRole('writer');
Roles can also be synced:
// All current roles will be removed from the user and replace by the array given $user->syncRoles(['writer', 'admin']);
Bouncer
$user->assign('admin'); $user->assign(['writer', 'admin']); $user->retract('admin');
It’s great that both packages accept either individual roles or arrays.
But Spatie’s package wins here because of syncRoles functionality. It’s really useful; with Bouncer you need to perform it manually with a few operations.
Assigning Permissions/Abilities to a User
Spatie
$user->givePermissionTo('edit articles'); $user->givePermissionTo('edit articles', 'delete articles'); $user->revokePermissionTo('edit articles');
Bouncer
$user->allow('ban-users'); $user->allow(['ban-users', 'edit-articles']);
You can pass the model name as a second argument.
Bouncer::allow($user)->to('edit', Post::class); Bouncer::allow($user)->to('edit', $post); $user->disallow('ban-users'); Bouncer::disallow($user)->to('delete', Post::class);
Similar functionality, but Bouncer offers the ability to pass the model class or its instance.
Checking Permissions/Roles for a User
Spatie
Check roles
$user->hasRole('writer'); $user->hasAnyRole(Role::all()); $user->hasAllRoles(Role::all());
Check permissions
$user->can('edit articles'); $role->hasPermissionTo('edit articles');
Bouncer
Check roles
$user->isAn('admin'); $user->isA('subscriber', 'editor'); $user->isAll('editor', 'moderator'); $user->isNot('subscriber', 'moderator');
Check permissions
Bouncer::allows('edit articles')
This section is pretty similar in both packages, with no clear winner.
Blade Commands
Spatie
@role('writer') I'm a writer! @else I'm not a writer... @endrole
@hasanyrole('writer|admin') I have one or more of these roles! @else I have none of these roles... @endhasanyrole
Bouncer
Bouncer does not add its own Blade directives.
More functionality by Spatie’s package. Of course, with both packages you can use default Laravel commands like @can and @endcan.
Caching
Spatie
Role and permission data is automatically cached to speed up performance.
To manually reset the cache for this package, run:
php artisan cache:forget spatie.permission.cache
Bouncer
All queries executed by the bouncer are cached for the current request. If you enable cross-request caching, the cache will persist across different requests.
Whenever you need, you can fully refresh the bouncer’s cache:
Bouncer::refresh();
Alternatively, you can refresh the cache only for a specific user:
Bouncer::refreshFor($user);
Caching is a little more robust in Bouncer. Enabling/disabling cache is a good thing, and refreshing the cache for a particular user might come handy.
Overall Conclusion
If you still expect a clear winner here, it’s not going to happen. Both packages are really good, and it’s a matter of preference.
Both of them have advantages in some functionality, but it’s more about the details.
Spatie’s Advantages:
A little better documentation (some Bouncer’s methods aren’t mentioned in README)
A little more understandable DB structure
syncRoles() method instead of delete-insert way
A few blade commands – @role and @hasanyrole
Ability to use multiple guards
Bouncer’s Advantages:
Create role/ability and assign it—all in one sentence
Allow or disallow permission based on model or its instance
A little better caching mechanism
A little more robust DB structure with a few more useful fields
If any of these details are really important to you, that could be the reason for your choice. Otherwise, pick Spatie or Bouncer, and you shouldn’t be disappointed.
P.S. Bonus Gift
Finally, both packages offer a set of functions to manage roles and permissions but don’t have any UI or admin panel to manage it. I’ve prepared a UI starter kit, based on both packages. You can use it as a boilerplate to manage roles and permissions.
Here are links to the GitHub repositories:
Laravel 5.4 admin panel based on Spatie Laravel-permission
Laravel 5.4 admin panel based on Bouncer
via Laravel News http://ift.tt/2gNbMQ0
0 notes
Text
What’s New in Laravel 5.4
If you've been following Scotch for a while, you heard a lot about Laravel. Some months ago, Laravel 5.3 was released. It introduced new features like Mailables.
Yesterday, the 25th of January, Laravel 5.4 was released.
It comes with no surprise that it brought a lot of new and exciting features to Laravel, and for the remainder of this article, we shall go through the new features.
New Middlewares
With the release of 5.4, two new middlewares are now shipped with the framework. If you don't know what middlewares are, check out Understanding Laravel Middlewares.
The middlewares are:
Trim Strings Middleware
Just as the name implies, this middleware trims extra spaces from request data. For example, a user submits their email through a form on your website and mistakenly types in some extra space after the email.
This middleware will automatically trim whitespace, so if a user submits something like this.
// '[email protected] '
Because of the existence of this middleware (\Illuminate\Foundation\Http\Middleware\TrimStrings::class) in App/Kernel.php, it gets converted into.
// '[email protected]'
Convert Empty Strings to Null
Still, as the name implies, this middleware converts empty strings to null. So if a user submits an empty form instead of getting '' it gets converted to null.
Higher order messages
This is perhaps one of my favourite feature ever added to Laravel. It much easier to show than explain.
Imagine we have a collection of blog posts and we want to perform an operation on each item in the collection. Normally, we would do this.
Learn about Collections in Laravel.
// Loop through all the posts and schedule them for sharing to twitter $posts->each(function ($post) { return $post->schedule(TWITTER); });
With High order messages in Laravel, we can simplify the above code into this.
$posts->each->schedule(TWITTER);
Yes, this is now a possibility. It doesn't just stop here either, we can take this a bit further and chain them. Here, another scenario.
/** * Loop through all the posts and reject any archived post * Then for the remaining posts, schedule each of them to twitter. */ $posts->reject(function ($post) { return $post->archived; })->each(function ($post) { return $post->schedule(TWITTER); });
With high order messages, we can simplify the above code into this.
$posts->reject->archived->each->schedule(TWITTER);
Want to see how it's done, check out this commit. This is simply mindblowing
From Elixir to Mix
Laravel Elixir provided us with a gulp wrapper that made development and packaging of assets easier.
The next version of Laravel Elixir is changing the underlying system and will be built on Webpack, instead of Gulp. This will replace the plugin ecosystem, and because of such a significant change, it was time to rename the package.
Also, Laravel Mix comes with a new helper function called mix() that serves as a replacement to the former elixir() function.
If you have a project still using Elixir, you can continue using it, as it is still supported and not going anywhere anytime soon.
Fluent Routing
The Route facade in Laravel is now fluent. Previously, if we wanted to name a route, we would do this.
Route::get('user/{id}/profile', function ($id) { // })->name('profile');
Now, we can do this.
Route::name('profile')->get('user/{id}/profile', function ($id) { // some closure action... });
We could register a route name and a middleware
Route::name('users.index')->middleware('auth')->get('users', function () { // some closure action... });
Registering a middleware with a route prefix and group
Route::middleware('auth')->prefix('api')->group(function () { // register some routes... });
Registering a middleware to a resource controller
Route::middleware('auth')->resource('photo', 'PhotoController');
Components and Slots
Components and slots allow us to simplify HTML elements into reusable areas.
In our application, we usually have components like modals, notification panel etc. We can now define them as components and reuse them.
To create a component, we simply create a new blade file and refer to it using.
@component('path.to.blade.file') Modal text go in here @endcomponent
You can read all about components and slots here.
Real-Time Facades
Facades provide a “static” interface to classes that are available in the application’s service container. Laravel ships with many facades which provide access to almost all of Laravel’s features. Laravel facades serve as “static proxies” to underlying classes in the service container, providing the benefit of a terse, expressive syntax while maintaining more testability and flexibility than traditional static methods.
One example that comes to mind is Auth. In laravel, we access an authenticated user's data by doing Auth::user(). This Auth class is a facade.
Now in Laravel 5.4, we can create facades on the fly. All we need do is namespace class on the Facade namespace and we can use the class as a facade.
namespace Facade\App\User;
Doing this will automatically convert our User model into a facade.
Laravel dusk
Laravel Dusk provides an expressive, easy-to-use browser automation and testing API. By default, Dusk does not require you to install JDK or Selenium on your machine. Instead, Dusk uses a standalone ChromeDriver installation. However, you are free to utilise any other Selenium compatible driver you wish.
Basically, it means we can test our Laravel code like we would in a web browser. Currently, Laravel uses browser-kit for testing.
The problem with browser-kit is that it is limited, and Dusk serves as an alternative with more features.
Dusk can detect AJAX etc. A full-length article on Dusk is on the way, stay tuned.
Fix: Specified key was too long error
Laravel 5.4 made a change to the default database character set, and it’s now utf8mb4 which includes support for storing emojis. This only affects new applications and as long as you are running MySQL v5.7.7 and higher you do not need to do anything.
For those running MariaDB or older versions of MySQL you may hit this error when trying to run migrations:
[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
As outlined in the Migrations guide to fix this all you have to do is edit your AppServiceProvider.php file and inside the boot method set a default string length:
use Illuminate\Support\Facades\Schema; public function boot() { Schema::defaultStringLength(191); }
Conclusion
Some features not explained above include
Resourceful Controller with Model Boilerplate: in simple terms, it is route model bindings for controllers.
JSON Based Language Files: this means that translation for text in Laravel can now be done with JSON files instead of PHP files. Learn More.
Markdown Mailables: this allows us to build Mailables in laravel using the Markdown syntax.
Map Eloquent Events to Dedicated Classes. Here is a video that further explains this.
If something was omitted, please let us know in the comment. Also, there is a free video series on Laracasts that shows What's New in Laravel 5.4.
via Scotch.io http://ift.tt/2kOnb3i
0 notes