Bulk Action using Livewire

https://dev.to/social_previews/article/836547.png

In this Tutorial, we will see how to implement Bulk Action so that User can select and update multiple records using Livewire. This is the part 3 of the Series related to Livewire Table. In Part 2 of the Series we saw how to Hide/Show Columns in a Table using Livewire.

Let us assume we have a Model called as Product and it has a column status. We want to give user the ability to select multiple products and then change the value of status column for all of the selected products.

I would assume that you already have a working Livewire Component which is showing the Records in a Table Form. First of all we are going to add a New Property $selectedProducts to our Livewire Component. This would hold all the Products that user has selected.

public $selectedProducts = [];
Enter fullscreen mode

Exit fullscreen mode

Now in the View, we would like to display a checkbox next to each item. We would create a New column and we will paste the following code inside the loop which displays all the Results.

<input type="checkbox" value="" />
Enter fullscreen mode

Exit fullscreen mode

This would display the checkbox and we have given it the value which is the Primary Key of the Product Table so as to uniquely identify it.

Now we would link this checkbox to the $selectedProducts using the wire:model.

<input type="checkbox" value=""
     wire:model="selectedProducts" />
Enter fullscreen mode

Exit fullscreen mode

Now every time a User selects a Product, $selectedProducts would be updated. So at any time $selectedProducts would have all the Products that User has selected for Bulk Action.

Infact, we are going to use wire:model.defer. The defer directives makes sure that our Component will not be re-rendered when the User checks the checkbox. This will result in a significant performance improvement. If you want to learn more about defer and other techniques to improve Performance using Livewire, you can check this Article.

<input type="checkbox" value=""
     wire:model.defer="selectedProducts" />
Enter fullscreen mode

Exit fullscreen mode

Now we need to create 2 Buttons, Activate and Deactivate. Both these buttons will call a method changeStatus on click. We will pass the value that we want to set for the status column as the parameter. So for Activate we pass 1 and for Deactivate we will pass 0.

<button wire:click="changeStatus(1)">Activate</button>
<button wire:click="changeStatus(0)">Deactivate</button>
Enter fullscreen mode

Exit fullscreen mode

Next we need to define this method within our Component. We can define it as follows. Here $status will hold the value that we want to set for the status column. So for Activate it will be 1 and for Deactivate it will be 0.

public function changeStatus($status)
{
}
Enter fullscreen mode

Exit fullscreen mode

Within this method we will first of all check, if there are any Records that User has selected using $selectedProducts. Then we will update the status column for all those Products. And then we will finally clear the $selectedProducts variable.

if (!empty($this->selectedProducts)) {
    Product::whereIn('id', $this->selectedProducts)->update(['status' => $status]);
    $this->selectedProducts = [];
}
Enter fullscreen mode

Exit fullscreen mode

And that is all we need to do to give User the Ability to update Records in Bulk.

If you have liked this Tutorial, please checkout the Livewire Package tall-crud-generator which automatically generates all the Code related to Bulk Actions.

Laravel News Links

Trijicon Supports Mentorship With +One Experience Giveaway

https://www.ammoland.com/wp-content/uploads/2021/09/duck-hunt-iStock-1301911854-500×334.jpg

duck hunt iStock-1301911854
Trijicon’s efforts to supporting hunting are fantastic. IMG iStock-1301911854

U.S.A. -(AmmoLand.com)- NSSF, the firearm industry trade association, is pleased to announce that Trijicon is sponsoring the Trijicon Hunt +ONE Experience Giveaway to focus attention on the importance of mentoring in hunting through NSSF’s +ONE Movement.

The +ONE Movement encourages mentoring of newcomers by experienced hunters and target shooters to pass on the skills and appreciation for these popular outdoor activities. With hunting season approaching, now is a good time to introduce someone new to this great American tradition, and NSSF can help with mentoring and newcomer resources at LetsGoHunting.org.

Trijicon, the Michigan-based optics manufacturer, wants to give someone the hunting experience of a lifetime. The Trijicon Hunt +ONE Experience giveaway includes a fully paid and guided free-range trophy whitetail hunt at Lowrance Ranch in Truscott, Texas with all travel, licenses, lodging, and meals included in the package. The winner of the hunt also receives a Springfield Armory 2020 Waypoint Rifle chambered in 6.5 Creedmoor with a Trijicon Credo HX 2.5-15×42 riflescope to use on the hunt, bringing the total package value to $10,000.

Entries to the sweepstakes are open until October 29, 2021, on the dedicated Sweepstakes page.

“We are grateful for Trijicon’s continued support of the +ONE Movement, which is so important to the future of hunting and recreational shooting,” said Zach Snow, NSSF Director, Member Development. “Trijicon’s efforts help to encourage experienced shooters and hunters to mentor newcomers so they can enjoy these lifelong activities with friends and family.”

“We are excited to further the NSSF +ONE Movement in conjunction with National Hunting & Fishing Day to show our support of the American hunting and conservation model,” said Josh Lyall, Trijicon Director of Marketing. “Trijicon is a company comprised of hunters and target shooters and we are always looking for ways to introduce more people to the world of hunting and shooting sports.”

There are now over 2 million pledges and potential mentees who are part of the +ONE Movement. Individuals and businesses interested in promoting and getting directly involved in the +ONE Movement can visit letsgoshooting.org/plusone and letsgohunting.org/plusone to learn more about the initiative and find ways to get started. Additional +ONE resources can be downloaded and or ordered at nssf.org/plusone.


About The National Shooting Sports Foundation

NSSF is the trade association for the firearm industry. Its mission is to promote, protect and preserve hunting and shooting sports. Formed in 1961, NSSF has a membership of thousands of manufacturers, distributors, firearm retailers, shooting ranges, sportsmen’s organizations, and publishers nationwide. For more information, visit nssf.org

National Shooting Sports Foundation

The post Trijicon Supports Mentorship With +One Experience Giveaway appeared first on AmmoLand.com.

AmmoLand.com

A Horizontal Scalability Mindset for MySQL

https://www.percona.com/blog/wp-content/uploads/2021/09/Horizontal-Scalability-for-MySQL.pngHorizontal Scalability for MySQL

Horizontal Scalability for MySQLAs a Technical Account Manager at Percona, I get to work with many of our largest clients. While the industry verticals vary, one main core challenge generally remains the same – what do I do with all this data? Dealing with massive data sets in MySQL isn’t a new challenge, but the best approach still isn’t trivial. Each application is obviously different, but I wanted to discuss some of the main best practices around dealing with lakes of data.

Keep MySQL Instances Small

First and foremost, the architecture needs to be designed to keep each MySQL instance relatively small. A very common question I get from teams new to working with MySQL is: “So what is the largest instance size MySQL supports?”. My answer goes back to my time in consulting: “It depends”. Can my MySQL instance support a 20TB dataset? Maybe, but it depends on the workload pattern. Should I store 20TB of data in a single MySQL instance? In most cases, absolutely not.

MySQL can definitely store massive amounts of data. But RDBMSs are designed to store, write, and read that data. When the data grows that large, often the read performance starts to suffer. But what if my working dataset still fits in RAM? This is often the critical consideration when it comes to sizing an instance. In this case, active read/write operations may remain fast, but what happens when you need to take a backup or ALTER a table? You are reading (and writing out) 20TB which will always be bounded by I/O.

So what is the magic number for sizing? Many large-scale shops try to keep individual instance sizes under the 2-3TB mark. This results in a few major advantages:

  • Predictable operational times (backups, alters, etc)
  • Allows for optimized and standardized hardware
  • Potential for parallelism in loading data

If I know my instance will never exceed a couple of terabytes, I can fully optimize my systems for that data size. The results are predictable and repeatable operational actions. Now, when a backup is “slow”, it is almost assuredly due to hardware and not being an outlier instance that is double the size. This is a huge win for the operations team in managing the overall infrastructure.  In addition to backups, you have the additional consideration of restore time.  Massive backups will slow restoration and have a negative impact on RTO.

Store Less Data

Now that the negative impact of large, individual instances is known, let’s look at how we keep the sizes down.  While seemingly obvious, the best way to keep data sizes small is to store less data.  There are a few ways to approach this:

  • Optimize data types
    • If data types are bigger than needed, it results in excess disk footprint (i.e. using bigint when int will suffice)
  • Review indexes for bloat
    • Limit composite Primary Keys (PKs)
    • Find and remove redundant indexes (using pt-duplicate-key-checker)
    • Avoid PKs using varchar
  • Purge old data
    • When possible, remove records not being read
    • Tools like pt-archiver can really help in this process

These techniques can help you delay the need for more advanced techniques.  However, in some cases (due to compliance, limited flexibility, etc), the above options aren’t possible.  In other cases, you may already be doing them and are still hitting size limits.

Horizontal Sharding

So what is another way to deal with massive data sets in MySQL? When all other options are exhausted, you need to look at splitting the data horizontally and spreading it across multiple equally sized instances. Unfortunately, this is much easier said than done. While there are some tools and options out there for MySQL (such as Vitess), often the best and most flexible approach is building this sharding logic into your application directly. Sharding can be done statically (key modulus for example) or more dynamically (via a dictionary lookup) or some hybrid approach of the two:

Horizontal Scalability Mindset for MySQL

Sharding Considerations

When you finally have to bite the bullet and split data horizontally, there are definitely some things to keep in mind.  First and foremost, picking the correct sharding key is imperative.  With the wrong key, shards won’t be balanced and you’ll end up with sizes all over the board.  This then becomes the same problem where a shard can grow too large.

Once you have the correct key, you need to understand that different workloads will be impacted by sharding differently.  When the data is split across shards, individual lookups are generally the easiest to implement.  You take the key, map to a shard, and fetch the results.  However, if the workload requires aggregate access (think reports, totals, etc), now you are dealing with combining multiple shards.  This is a primary and major challenge when looking at horizontal sharding.  As is the case in most architectures, the business requirements and workload will dictate the design.

If your team is struggling with an exploding data set, the Professional Services team at Percona can help you design a more flexible and scalable solution. Each case is unique and our team can work with your specific use case and business requirements to guide you in the right direction. The biggest thing to remember: please don’t just keep adding hard disk space to your instances while expecting it to scale. Proper design and horizontal sharding is the critical factor as your data grows!

Percona Distribution for MySQL is the most complete, stable, scalable, and secure, open-source MySQL solution available, delivering enterprise-grade database environments for your most critical business applications… and it’s free to use!

Download Percona Distribution for MySQL Today

Percona Database Performance Blog

Laravel Tinker PHPStorm Plugin

https://plugins.jetbrains.com/files/14957/137820/icon/pluginIcon.pngA free and open source plugin to run PHP code directly as if through Tinker without leaving your favorite IDE. Includes all PhpStorm features you are already used to like code completion, error correction and color scheme.Laravel News Links

Comic for September 25, 2021

https://assets.amuniversal.com/744dff80f250013976ad005056a9545d

Thank you for voting.

Hmm. Something went wrong. We will take a look as soon as we can.

Dilbert Daily Strip

I Love My Hoe Dag Garden Tool

https://i0.wp.com/toolguyd.com/blog/wp-content/uploads/2021/09/Hoe-Dag.jpg?resize=600%2C569&ssl=1

Hoe Dag

The Hoe Dag, shown in this photo by Lee Valley, has really been my MVP tool this past gardening season.

To be frank, it does not feel very heavy duty, but I put it through its paces, digging up rocks, roots, and heavy clay soil.

The Hoe Dag is said to be superb for digging, planting, tilling, weeding, and even chopping through roots. It’s described as rugged, and it has proven this to be true.

The multi-purposed gardening tool features an 8-1/2″ arc-shaped blade with a 2-1/2″ edge on one end and a 7/8″ edge on the other. It has a 15″ seasoned hardwood handle.

Lee Valley says that the Hoe Dag has been hand-crafted in the USA for over 50 years.

Although I’ve been hard on my Hoe Dag, I don’t forget that it’s handle is made of wood and that it’s attached to the steel head via a socket joint. It can handle a bit of abuse, but I reach for a different tool for heavier prying.

I absolutely definitely recommend the Hoe Dag. Sure, it’s basically a double-sided short-handle hoe, and there are other tools that are almost kind of like it, but they’re not quite the same.

The Hoe Dag is well-made, it’s extremely versatile, it’s comfortable and light to swing, and it’s made in the USA.

Price: $32.50

Buy Now via Lee Valley
See Also via Amazon

Lee Valley currently offers free ground shipping on orders $30 and up.

ToolGuyd

Decorator Pattern vs. Proxy Pattern

https://doeken.org/assets/img/decorator-vs-proxy-pattern.jpg

There are two patterns in PHP that are very similar; The Decorator Pattern and The Proxy Pattern. Because they are so
similar, you can quickly mistake one for the other. Does that matter? Maybe not, but I think it’s good to know the
differences when communicating about them.

Similarities between Decorators and Proxies

Both the Decorator Pattern and the Proxy Pattern revolve around the idea of wrapping an instance of an existing
interface (let’s call that the inner instance) with a class that implements that same interface and delegates their
function calls to the same functions on their inner instance.

These patterns are very useful for adding or changing functionality of an instance without breaking encapsulation. It
can also change or extend functionalities of final functions and classes. And because they usually serve one purpose
they can easily be tested.

Example

interface SubscriberInterface {

public function subscribe(string $email): void;

}

 

class SubscriberDecorator implements SubscriberInterface {

private SubscriberInterface $inner_subscriber;

 

public function subscribe(string $email): void {

$this->inner_subscriber->subscribe($email);

}

}

In this example you can see that our SubscriberDecorator implements the SubscriberInterface and it also requires
some instance of the SubscriberInterface. After that it delegates the subcribe() function to the same function on
that instance.

Differences between Decorators and Proxies

When it comes to naming a class a Decorator or a Proxy you have to look at its intent. What is the class actually doing
with the instance it is wrapping?

Required vs. Optional dependency

You might have noticed I didn’t include a __construct() method in the previous example. This was intentional, because
this is where the first difference can be apparent.

A Decorator requires an instance of the interface it is wrapping, while a Proxy does not require such an
instance. A Proxy can receive an instance, but is also allowed to create this instance itself. So you can create
a new Proxy on its own, while a Decorator needs another instance as dependency.

// Decorator

public function __construct(public SubscriberInterface $inner_subscriber){}

 

// Proxy

public function __construct(?SubscriberInterface $inner_subscriber = null){

$this->inner_subscriber = $inner_subscriber ?? new InnerSubscriber();

}

Additive vs. Restrictive

Decorators are additive; meaning they only add new functionality by wrapping the function call and returning the
original value. It can however do anything before or after that call. You can for example log every value when a
function is called or dispatch an event. Just make sure to return the original value.

Proxies are restrictive; meaning they can change the behavior of a function or even restrict calling a specific function
by throwing an exception.

Tip: Both Decorators and Proxies are allowed to add any extra functions or parameters that are not on the interface. It can therefore be wise to implement some magic __isset(), __get() and __call() methods on the Decorator or Proxy to pass these calls along to their inner instance as well. This way you can still call those methods and parameters even if you add multiple decorators on top.

public function __call($name, $arguments)

{

return $this->inner_subscriber->{$name}(...$arguments);

}

 

public function __get($name)

{

return $this->inner_subscriber->{$name};

}

 

public function __isset($name)

{

return isset($this->inner_subscriber->{$name});

}

General purpose vs. Specific purpose

Decorators serve a general purpose. It will add some functionality regardless of the instance it is wrapping. This means
that multiple decorators should be able to be applied on top of one another in any random order and still produce the
same result and added functionality.

Proxies serve a more specific purpose. It will mostly be used to change or append functionality to a specific instance
of the interface. Proxies also aren’t commonly stacked on top of one another as a single proxy is usually enough.

Tips for Decorators and Proxies

Here are a few tips you might consider when working with Decorators and Proxies.

Make a base abstraction

If you create multiple Decorators or Proxies of the same interface it can be beneficial to create an abstract class of
the interface or a trait that satisfies the interface, where every function is already deferred to the function on
the inner instance. If you are a package creator, you might even consider providing this implementation inside the
package. This way a Decorator or Proxy can extend or use this implementation and only (re)declare the functions
it needs.

interface SubscriberInterface

{

public function subscribe(string $email): bool;

 

public function unsubscribe(string $email): bool;

}

 

trait SubscriberTrait { ... }

{

private SubscriberInterface $inner_subscriber;

 

public function subscribe(string $email): bool

{

return $this->inner_subscriber->subscribe($email);

}

 

public function unsubscribe(string $email): bool

{

return $this->inner_subscriber->unsubscribe($email);

}

 

public function __call($name, $arguments)

{

return $this->inner_subscriber->{$name}(...$arguments);

}

 

public function __get($name)

{

return $this->inner_subscriber->{$name};

}

 

public function __isset($name)

{

return isset($this->inner_subscriber->{$name});

}

}

 

// You can now extend this class, or implement the interface and trait.

abstract class SubscriberDecorator implements SubscriberInterface

{

use SubscriberTrait;

 

public function __construct(SubscriberInterface $inner_subscriber)

{

$this->inner_subscriber = $inner_subscriber;

}

}

Single responsibility Decorators

It might be tempting to add multiple features onto a Decorator, but the beauty of them is that they can be added or
removed without changing the underlying code. So try to make tiny Decorators that focus on one thing and apply these on
top of each other. Again, this simpleness makes them easier to test as well.

Examples

You can find a couple of nice examples of Decorators and Proxies in Symfony.

Their developer toolbar shows a lot of information regarding events and cache, for example. They log this information by
decorating the current EventDispatcher with
a TraceableEventDispatcher and
the current cache adapter with
a TraceableAdapter
within the dev environment.

An example of a Proxy can be found in
the DeflateMarshaller of
the symfony/cache package. This Marshaller is restrictive due to its dependency on gzinflate() & gzdeflate() and
it’s changes to the output of the inner instance.

Thanks for reading

I hope you enjoyed reading this article! If so, please leave a 👍 reaction or a 💬 comment and consider subscribing to
my newsletter! I write posts on PHP almost every week. You can also follow me
on twitter for more content and the occasional tip.

Laravel News Links