2016年11月23日 星期三

Implicit route model binding in Laravel 5.2

If you've never used it, Laravel's route model binding has been around for a while, but Laravel 5.2 is about to make it even easier.

The basics of route model binding #

Let's assume that a common pattern for binding a URL route is something like this:
Route::get('shoes/{id}', function ($id) {
    $shoe = Shoe::findOrFail($id);
    // Do stuff
});
This is something I do a lot. Wouldn't it be nice if you could drop the findOrFail line and just teach Laravel's router that this route represents a Shoe? You can. In your route service provider, just teach the router: $router->model('shoe', 'App\Shoe'); That means, "any time I have a route parameter named shoe, it's an ID representing an instance of App\Shoe". This allows us to re-write the above code like this:
Route::get('shoes/{shoe}', function ($shoe) {
    // Do stuff
});

Implicit route model binding #

In Laravel 5.2, it's even easier to use route model binding. Just typehint a parameter in the route Closure (or your controller method) and name the parameter the same thing as the route parameter, and it'll automatically treat it as a route model binding:
Route::get('shoes/{shoe}', function (App\Shoe $shoe) {
    // Do stuff
});
That means you can now get the benefits of route model binding without having to define anything in the Route Service Provider. Easy!
That's it for implicit route model binding! Everything past this point is already around in 5.1.

Little known features of route model binding #

These features are not new with 5.2, and therefore not specific to implicit route model binding, but they seem to be not commonly known, so I thought I would throw them in here.

Custom binding logic for route model binding #

If you want to customize the logic a route model binding uses to look up and return an instance of your model, you can pass a Closure as the second parameter of an explicit bind instead of passing a class name:
$router->bind('shoe', function ($value) {
    return App\Shoe::where('slug', $value)->where('status', 'public')->first();
});

Custom exceptions for route model binding #

You can also customize the exceptions that the route model bindings throw (if they can't find an instance of that model) by passing a Closure as the third parameter:
$router->model('user', 'App\User', function () {
    throw new NotFoundHttpException;
});

Changing an Eloquent model's "route key" #

By default, Laravel assumes an Eloquent model should map to URL segments using its id column. But what if you expect it to always map to a slug, like in my shoe custom binding logic example above?
Eloquent implements the Illuminate\Contracts\Routing\UrlRoutable contract, which means every Eloquent object has a getRouteKeyName() method on it that defines which column should be used to look it up from a URL. By default this is set to id, but you can override that on any Eloquent model:
class Shoe extends Model 
{
    public function getRouteKeyName()
    {
        return 'slug';
    }
}
Now, I can use explicit or implicit route model binding, and it will look up shoes where the slugcolumn is equal to my URL segment. Beautiful.

from : https://mattstauffer.co/blog/implicit-model-binding-in-laravel-5-2

Form array validation in Laravel 5.2

It's time to start writing about the new features in Laravel 5.2! You'll notice that many of these features are quicker and easier to learn and write up, so it may seem that it's a smaller release. But many of the features in 5.2 will have a big impact on the simplicity and convenience of the code we write day-to-day.

A quick introduction to HTML Form arrays #

Form array validation simplifies the process of validating the somewhat abnormal shape of data HTML forms pass in when the array syntax is used. If you're not familiar with it, a common use case is when you allow a user to add multiple instances of the same type on one form.
Let's imagine you have a form where a user is adding a company, and as a part of it they can add as many employees to the company as they want. Each employee has a name and a title.
Here's our HTML; imagine that we have some JavaScript that creates a new "employee" div every time you press the "Add another employee" button so they user can add as many employees they want.
<form>
    <label>Company Name</label>
    <input type="text" name="name">

    <h3>Employees</h3>
    <div class="add-employee">
        <label>Employee Name</label>
        <input type="text" name="employee[1][name]">
        <label>Employee Title</label>
        <input type="text" name="employee[1][title]">
    </div>
    <div class="add-employee">
        <label>Employee Name</label>
        <input type="text" name="employee[2][name]">
        <label>Employee Title</label>
        <input type="text" name="employee[2][title]">
    </div>
    <a href="#" class="js-create-new-add-employee-box">Add another employee</a>

    <input type="submit">
</form>
If you fill out that form and submit it, this is the shape of the $_POST:
array(2) {
  ["name"]=>
  string(10) "Acme, Inc."
  ["employee"]=>
  array(2) {
    [1]=>
    array(2) {
      ["name"]=>
      string(10) "Joe Schmoe"
      ["title"]=>
      string(11) "Head Person"
    }
    [2]=>
    array(2) {
      ["name"]=>
      string(18) "Conchita Albatross"
      ["title"]=>
      string(21) "Executive Head Person"
    }
  }
}
As you can see, we get an employee "object". And it contains an array of the IDs that we passed in, with the key/value pairs of "fieldname" => "user provided field value".
Note: It used to be common to just set every instance of the "employee name" field, for example, to be just employee[][name] without setting the ID manually. Don't do this.It'll make every aspect of working with the code more complex.
But how do we validate this? Prior to 5.2, it's a bunch of manual work. Now, Laravel understands this nesting structure and can validate against it uniquely.

Writing form array validation rules #

So, how do we do it? Let's take a look at a normal validator:
    // CompaniesController.php
    public function store(Request $request)
    {
        $this->validate($request, [
            'name' => 'required|string'
        ]);
        // Save, etc.
    }
And now let's add validation for our company employee fields:
    // CompaniesController.php
    public function store(Request $request)
    {
        $this->validate($request, [
            'name' => 'required|string',
            'employee.*.name' => 'required|string',
            'employee.*.title' => 'string',
        ]);
        // Save, etc.
    }
Now we're validating every employee[*][name] and employee[*][title] uniquely, with pretty much no effort on our part. Beautiful.

Postscript #

You may have noticed that the shape of the validation is employee.*.name, with an asterisk in the middle, which almost indicates that you could put something else there.
What if, instead of an asterisk to indicate "all", you put a specific number there? Turns out it'll only validate the entities with that ID. So if you put employee.1.name in the validation array instead of employee.*.name, only the employee with the ID of 1 will be validated according to those rules.
I don't know why or when you would do it, but you could actually set completely separate validation rules for each ID:
    $this->validate($request, [
        'employee.1.name' => 'required|string',
        'employee.2.name' => 'integer', // Not sure *why* you would do this, but, it's possible
    ]);
That's it. Enjoy!

from : https://mattstauffer.co/blog/form-array-validation-in-laravel-5-2

ACL (Access Control List) Authorization in Laravel 5.1

The authentication that Laravel provides out-of-the-box makes it simple to get user signup, login, logout, and password resets up and running quickly and easily.
But if you needed to control access to certain sections of the site, or turn on or off particular pieces of a page for non-admins, or ensure someone can only edit their own contacts, you needed to bring in a tool like BeatSwitch Lock or hand-roll the functionality, which would be something called ACL: Access Control Lists, or basically the ability to define someone's ability to do and see certain things based on attributes of their user record.
Thankfully, Taylor and Adam Wathan wrote an ACL layer in Laravel 5.1.11 that provides this functionality without any added work.

What can it do? #

The out-of-the-box Laravel ACL is called Gate (that's not a product name like "Spark", but rather the name of the classes and the façades).
Using the Gate classes (either injecting them or using the Gate façade) allows you to easily check if a user (either the currently-logged-in user or a specific user) is "allowed" to do a certain thing. Check out this syntax for a taste:
if (Gate::denies('update-contact', $contact)) {
    abort(403);
}
Drop that into your controller and it checks the currently authenticated user against a ruleset that you defined (and which you named update-contact); it takes the data of that particular contact, checks it agains the ruleset, and returns whether or not the user is authorized.
You can also check for Gate::allows, you can use it in conditionals in Blade with @can, and there's much, much more. So, let's take a look.

How does it work? #

Everything with Laravel's ACL is founded on a concept called an "Ability." An Ability is a key (e.g. "update-contact") and a Closure (with optional parameters) that returns either true or false.

Defining Abilities #

Let's define an Ability in the default location, the AuthServiceProvider:
...
class AuthServiceProvider extends ServiceProvider
{
    public function boot(GateContract $gate)
    {
        parent::registerPolicies($gate);

        $gate->define('update-contact', function ($user, $contact) {
            return $user->id === $contact->user_id;
        });
    }
}
As you can see, the first parameter for our Closure is the user. If there's no currently-authenticated user (and if you haven't specified one--we'll see that later), Gate will automatically return false for every Ability.

Class methods instead of Closures

Just like most other places in Laravel that accept Closures (e.g. route definition), you can pass a class name and method into the second parameter of define instead of a Closure, and it'll be resolved out of the Container:
$gate->define('update-post', '');

Checking with Façades #

Gate allows you to check using the following methods: check, allows, or denies. Note that check is just the same as allows, and denies is exactly the opposite of allows; so it's really just allows with a clone named check and an opposite check named denies.
If you're using the façade, you won't need to pass in the user; the façade automatically passes in the currently authenticated user for you.
if (Gate::denies('update-contact', $contact)) {
    abort(403);
}
if (Gate::allows('create-contact')) {
    redirect('hooray');
}
Or, if you've defined an Ability with multiple parameters:
$gate->define('delete-interaction', function ($user, $contact, $interaction) {
    // Do stuff...
});
Just pass an array to the second parameter:
if (Gate::allows('delete-interaction', [$contact, $interaction]) {
    // Do stuff...
});
What if you want to check this ability for a specific user, instead of the currently authenticated user?
if (Gate::forUser($user)->denies('update-contact', $contact)) {
    abort(403);
}

Checking with Injected Gate #

As always, you can inject the class itself instead of using the façade. The class you'll inject is the same GateContract that's injected into the AuthServiceProvider: Illuminate\Contracts\Auth\Access\Gate.
    public function somethingResolvedFromContainer(Gate $gate)
    {
        if ($gate->denies('create-team')) {
            // etc.
        }
    }

Checking on the user model #

Laravel's App\User model now provides can and cannot, which mirror allows and denies on the Gate. This comes from the Authorizable trait.
So, if we have a user somewhere, we can check can() on them:
if ($user->can('update-contact', $contact)) {
    // Do stuff
}

Blade #

You can also use can (optionally with else) in Blade:
<nav>
    <a href="/">Home</a>
    @can('edit-contact', $contact)
        ]) }}">Edit This Contact</a>
    @endcan
</nav>

Intercepting checks #

What if you have the idea of a superuser, or admin? Or what if you want to be able to set a temporary toggle to change the ACL logic for your users?
The before function allows you to return early, before all of your other checks, in certain exceptional circumstances.
$gate->before(function ($user, $ability) {
    if ($user->last_name === 'Stauffer') {
        return true;
    }
});
Or, more realistically:
$gate->before(function ($user, $ability) {
    if ($user->isOwner()) {
        return true;
    }
});

Policies #

There's another concept that you can (optionally) use to define access logic in your applications. It's an organizational structure that'll help keep you from crudding up the AuthServiceProvider; it's almost like a controller, in that it helps you group your ACL logic based on the resource that it's controlling access to.

Generating Policies

You can generate a policy with Artisan:
php artisan make:policy ContactPolicy
Then you register it with the AuthServiceProvider in the policies property:
class AuthServiceProvider extends ServiceProvider
{
    protected $policies = [
        Contact::class => ContactPolicy::class,
    ];
Here's what our auto-generated Policy looks like:


namespace App\Policies;

class ContactPolicy
{
    /**
     * Create a new policy instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }
}
So, let's define the update method:


namespace App\Policies;

class ContactPolicy
{
    public function update($user, $contact)
    {
        return $user->id === $contact->user_id;
    }
}
Note: I've primarily been using the update method as an example here. There are a few situations (see below) where the method name matters, because it needs to sync with the calling method. But you'll like have a variety of method names: show, create, or even addInteraction.

Checking Policies

If there's a policy defined for a resource type, the Gate will use the first parameter key to figure out which method to check on your policy.
So, to check if you can update a Contact, just pass the contact in and check for the update Ability. This code will pass to the update method on the ContactPolicy:
if (Gate::denies('update', $contact)) {
    abort(403);
}
This also works for the User model checking and Blade checking.
Additionally, there's a policy helper that allows you to retrieve a policy class and run its methods:
if (policy($contact)->update($user, $contact)) {
    // Do stuff
}

Controller authorization #

Since much of the authorization will be quitting out of a controller method if the Ability is denied, there's a shortcut for that when in a Controller (which is added via the new AuthorizesRequests trait):
    public function update($id)
    {
        $contact = Contact::findOrFail($id);

        $this->authorize('update', $contact);

        // Do stuff...
    }
Just like in our examples above, this will throw a 403 error if the authorization fails.
And finally, if your controller method name lines up with the same method name on the Policy (e.g. the update controller method and the update method on the Policy), you can skip the first parameter of authorize entirely:
    public function update($id)
    {
        $contact = Contact::findOrFail($id);

        $this->authorize($contact);

        // Do stuff...
    }
This is one of my favorites; you might not love the magic, but since this is something I do so often, I'm really excited to trim down the amount of my controller methods that are dedicated to the same ACL logic, over and over.

Concliption #

That's it. As someone who has written ACLs dozens of times, I can say: This is better than anything I've built, simpler than anything I've imported from others, and does everything I need.
If you need anything like Roles, user groups, or database-defined permissions levels, you'll still need to do some of the work yourself--and you may still find yourself reaching for an external package. But for most circumstances, this is more than enough, and just as simple as it can be.

from : https://mattstauffer.co/blog/acl-access-control-list-authorization-in-laravel-5-1

wibiya widget