About Sharp for Laravel — Part 3.

Filtering things.

Philippe Lonchampt
code16
3 min readFeb 27, 2018

--

See Part 1 and Part 2.

Let’s start today with something really simple, at least if you’re a Laravel developer : validation. Right now, if we try to update or create a Player without typing a name, we got this nasty database error:

Of course, we are in debug mode here.

Let’s add a validation layer. First, we create a new PlayerSharpValidator class with extends Laravel’s regular FormRequest:

Standard stuff here: wa can use all the good from Laravel validation system, like custom messages, custom validation rules, … Now we just have to register this validator in sharp config file:

Et voilà:

Of course, message localization is standard too.

Next task: we need to add the country information in our Team entity. This is mainly to show how filters works, so let’s skip the database migration, form and list update and we’re here:

I changed the seeder too, to generate more players.

To create our filter, we first write a Filter class:

Our values() code is a little odd here, because we choose a string attribute instead of a foreign key for this example, but why not. We next register this filter in the Team EntityList class:

And filter is on:

But for now changing its value does nothing... We have to take this new filter into account:

Like always with Sharp, you’ll have to write this code because Sharp won’t presume anything about your data structure, and this is very useful in many trickier cases. The result here is as expected:

Yes, handball is a German sport…

Okay, let’s reproduce this quickly in a more realistic case; filter players by teams.

Notice we implement EntityListRequiredFilter, and thus we have to define defaultValue() too. The idea is that we decide it’s mandatory to choose a team to list players. More on this required filter and other options (like multiple filter) in the documentation.

Two minutes to implement, and it’s working:

We could remove the “team” column now, since we implement the team filter as a required one.

I promised that we’ll review form lists, but I’d like to keep these posts short: I keep that for Part 4 (EDIT: which is live now).

The Part 3 code is available on github (https://github.com/code16/sharp-handball-sample/tree/part-3), and I tried to organize commits to make it easy to follow.

--

--

Philippe Lonchampt
code16

Developer and founder of Code 16, maintainer of Laravel Sharp.