Tips for Laravel Performance Optimization

Since its release in 2011, Laravel has become popular choice for the development of business focused applications. One reason Laravel is too much popular in developers is its performance optimization that allows developers to fine tune Laravel based apps.

In this tutorial I will guide on how to optimize Laravel based application when in production.

Prerequisites

For this purpose of tutorial, I assume you have installed Laravel on your server. I have following setup:

Config Caching

Laravel provides outstanding command Artisan Cache Config which is very help full in boosting performance. The basic usage of command is as follows:

php artisan config:cache

Once you run this command, the changes you make will not have any effect. If you wish to refresh the cache, run this command once again. In order to clear the config cache, use the following command:

php artisan config:clear

To further optimize performance of your application you can use OpCache, that caches the php code, so you don’t have to recompile it again and again.

Routing Cache

Routes caching is very important optimization feature when you have lots of routes. The routes cache is a simple array and helps in speeding up Laravel Performance. Run the following command:

php artisan route:cache

Remember to run the command every time when you have made changes in routes file or added any new route. For clearing cache use following command:

php artisan route:clear

Remove Unused Service

In the context of Laravel optimization, an important tip is to not to load all services from the config, it is always important to disable unused services from config files.

Composer Optimize Autoload

It is a good idea to use Composer scan the application and create one-to-one association of the classes and files in the application. Use the following command:

composer dumpautoload -o

Limit Included Libraries

It is always important to review all the libraries that are called within the code. If you think you could do it without using a library remove it from config/app.php to speed up Laravel application.

JIT Compiler

On every request, converting PHP code to bytecode and then executing it is a resource intensive process. Therefore, go-between such as Zend Engine are required to execute the C subroutines. To reduce time, it is essential to repeat this process just once, this is where the Just-in-time (JIT) compiler has proven to be very useful. For Laravel based applications the recommended JIT compiler is HHVM by Facebook.

Cache Queries Results

By caching the results of the queries which are used frequently is a great way to optimize your Laravel based application. For this my recommendation is as follows:

$posts = Cache::remember('index.posts', 30, function() {return Post::with('comments', 'tags', 'author', 'seo')->whereHidden(0)->get();}); 

Use Eager Loading for Data

When Eloquent uses eager loading it loads all associated object models in response to the initial query. Let’s compare Eager loading and Lazy loading.  

The Lazy loading query will look as follows:

$books = App\Book::all(); foreach ($books as $book) { echo $book->author->name;} 

The Eager loading query will look as follows:

$books = App\Book::with('author')->get(); foreach ($books as $book) { echo $book->author->name;} 

Precompile Assets

For Laravel tuning developers often distribute code in separate files. While this keeps the code clean and manageable, but it doesn’t contribute to efficient production. To help developers in this context Laravel provides simple commands:

php artisan optimize php artisan config:cache php artisan route:cache 

via Laravel News Links
Tips for Laravel Performance Optimization

Transporting Firearms and Ammunition, a Frequent Flyer’s Perspective

Pelican 1510 “Carry-On Case” open to show storage.

U.S.A.-(Ammoland.com)- Recently I was talking with a few fellow gun owners about air travel and the transporting of firearms. I was surprised at how some of them thought that flying with firearms was more of a hassle than it is in reality. These were not casual shooters, either. Industry professionals would be a better term.

For decades flying with guns has been part of my way of life when traveling from point A to point B, whether to attend a trade show, go on a hunting trip, take a class or simply visit family and friends and want the security of my carry guns.

Airport Security Gun Ammo Ban istock
Airport Security Gun Ammo Ban istock

Air travel with firearms can be as difficult or complex as you want to make it or it can be very simple.

The most important thing to ensure is that your firearms and ammunition are legal in both your point of origin and destination.

The Rules

According to the TSA (Transportation Security Administration):

“When traveling, comply with the laws concerning possession of firearms as they vary by local, state and international governments. If you are traveling internationally with a firearm in checked baggage, please check the U.S. Customs and Border Protection website for information and requirements prior to travel. Declare each firearm each time you present it for transport as checked baggage. Ask your airline about limitations or fees that may apply. Firearms must be unloaded and locked in a hard-sided container and transported as checked baggage only. Only the passenger should retain the key or combination to the lock. Firearm parts, including magazines, clips, bolts and firing pins, are prohibited in carry-on baggage, but may be transported in checked baggage. Replica firearms, including firearm replicas that are toys, may be transported in checked baggage only. Rifle scopes are permitted in carry-on and checked baggage. Declare the firearm and/or ammunition to the airline when checking your bag at the ticket counter. Contact the TSA Contact Center with questions you have regarding TSA firearm regulations and for clarification on what you may or may not transport in your carry-on or checked baggage.”

“Unloaded firearms may be transported in a locked hard-sided container as checked baggage only. The container must completely secure the firearm from being accessed. Locked cases that can be easily opened are not permitted. Be aware that the container the firearm was in when purchased may not adequately secure the firearm when it is transported in checked baggage. Ammunition is prohibited in carry-on baggage, but may be transported in checked baggage. Small arms ammunition, including ammunition not exceeding .75 caliber and shotgun shells of any gauge, may be carried in the same hard-sided case as the firearm. Firearm magazines and ammunition clips, whether loaded or empty, must be securely boxed or included within a hard-sided case containing an unloaded firearm. Read the requirements governing the transport of ammunition in checked baggage as defined by 49 CFR 175.10 (a)(8).”

The Container

You have basically two routes you can go here as far as a container.

  • Use a dedicated hard-sided container for firearms
  • If flying with a pistol or two, place your locked pistol case inside another piece of checked luggage.

When I fly, I always go with the first option. You may think that this only makes sense when traveling with a long gun and using a $300 wheeled and lockable rifle case and that certainly is an option. However, I found a case that fits not only my needs for flying with a few handguns but other valuables I do not trust to the good graces of an airport’s baggage crew.

Pelican 1510

It is the Pelican 1510 “Carry-On Case”, but do not let the name fool you, Pelican calls it that as it meets the maximum dimensions for carry-on baggage with most commercial airlines: 22.00″ x 13.81″ x 9.00″ (55.9 x 35.1 x 22.9 cm). Although, to be honest, it is a lot smaller than what I see most air travelers fly with as carry-on items.

Pelican 1510 “Carry-On Case”

Seriously, when did one bag and one personal item become two steamer trunks made in the 1920s with wheels and collapsible handles?

The interior gives you 19.75″ x 11.00″ x 7.60″ (50.2 x 27.9 x 19.3 cm) of secure storage space and the case can be ordered in a variety of colors (black, orange, yellow, red, green and tan). Additionally, you can configure the interior to how you want it.

Most shooters opt for the foam configuration and pluck out the shape of their firearm(s). I find this wasteful and recommend either the Trek Pak Divider system or the padded dividers. This allows me to use a second internal pistol case with my firearms and gives me plenty of room for other items I like to keep under lock and key such as cameras, night vision, thermal imagers, rifle parts, suppressors, ammunition and custom knives.

That is the second benefit of flying with a firearm; since it is transported in a locked case you can place other valuables with it for their protection.

Pelican’s 1510 case is small enough that it is easy to get around with due to its strong polyurethane wheels with stainless steel bearings and retractable extension handle, yet big enough that it cannot be secreted out of a secure area within an airport by a baggage thief. The padlock inserts are reinforced with stainless steel hardware and if you use quality padlocks, your guns and gear will usually arrive safe and sound.

If you think this is too much luggage to haul around with your other bags and are just transporting a handgun or two for concealed carry, you can place a small locked pistol case inside another piece of luggage. The pistol case must be locked, but the outer case cannot be. In my opinion this still leaves your pistol case open to theft as someone can reach in, remove the locked case and get it to a location where it can be pilfered or (if the case is small enough) stolen outright.

You can simply lock your unloaded handgun and ammo in a pistol case and put it inside your unlocked suitcase. The author recommends against this, however.

Firearms

“United States Code, Title 18, Part 1, Chapter 44, firearm definitions includes: any weapon (including a starter gun) which will, or is designed to, or may readily be converted to expel a projectile by the action of an explosive; the frame or receiver of any such weapon; any firearm muffler or firearm silencer; and any destructive device. As defined by 49 CFR 1540.5 a loaded firearm has a live round of ammunition, or any component thereof, in the chamber or cylinder or in a magazine inserted in the firearm.”

On one occasion while flying through Phoenix International Airport with firearms, a fellow passenger took note of us putting padlocks on my Pelican case and asked me how I was able to do that. He routinely transported high end electronics and did not trust the security of “TSA Approved Locks”.

I told him that I was transporting firearms and suggested he could do the same, by placing a firearm in his secured case with proper locks. He seemed hesitant but then relieved when I told him that TSA considers a pellet gun or starter pistol a fully-fledged firearm and a $20 non-gun would protect his case’s other more valuable contents.

Ammunition

When flying with handguns for CCW, I take along about 150 rounds in the original factory boxes. If I am attending a class that requires more (say 500 to 2000 rounds) I either buy it locally or have it shipped to the final destination.

Various ways to store ammo when flying: factory box, aftermarket plastic box or in a magazine.

As noted previous, ammunition may be stored in magazines, plastic reloading cases or the original cardboard containers.

If you are flying with a substantial amount, this is where the rules of the airlines come into play as many have specific weight allowances for ammunition. The limit seems to be 11 pounds on average.

Documentation

Oftentimes, ticket counter agents or even TSA Agents may not completely know the rules. I advise printing out copies of the regulations governing firearms from the TSA Website as well as the airline’s requirements for the same in advance of your trip to present it when difficulties in communication occur.

When you declare your firearm, you will be given a declaration form to place in the case containing the firearm after you complete it.  You may be asked to wait nearby for up to 30 minutes as the bag is checked in case TSA feels the need to inspect it. If TSA does not arrive, proceed to passenger screening and on to the gate.

Firearm Declaration Form

When you reach your destination and retrieve your baggage it may come out on the carousel. Some airports will take secured baggage to an office near the baggage claim or a roped off area in the vicinity. Claim your bags and be on your way, it is that easy.


About Mike Searson

Mike Searson

Mike Searson’s career as a shooter began as a Marine Rifleman at age 17. He has worked in the firearms industry his entire adult life as a Gunsmith, Ballistician, Consultant, Salesman, Author and was first certified to teach firearms safety in 1989.

Mike has written over 2000 articles for several magazines, websites and newsletters including Blade, RECOIL, OFF-GRID, Tactical Officer, SWAT, Tactical World, Gun Digest, Examiner.com and the US Concealed Carry Association as well as AmmoLand Shooting Sports News.

  • Home page: www.mikesearson.com
  • FB: www.facebook.com/mike.searson
  • TWITTER: www.twitter.com/mikesearson

The post Transporting Firearms and Ammunition, a Frequent Flyer’s Perspective appeared first on AmmoLand.com.

via AmmoLand.com
Transporting Firearms and Ammunition, a Frequent Flyer’s Perspective

Watch: Clay Pigeons on ‘How It’s Made”

I think we all know what a “clay pigeon” is — and most if not all of us have been entranced by watching “How It’s Made,” the TV documentary that shows how stuff is manufactured in “Reader’s Digest condensed” form. I haven’t watched it in years, and back when I did my wife constantly complained about the monotonous narrator. These days there’s a different narrator, but I think he might be related to the original one because he’s just about as bland.

This 5-minute episode is about the making of clay targets, sometimes called skeet, and early on we’re told they’re not made of clay at all, but of petroleum pitch or resin mixed with talc.

After they’re molded, they’re flipped with the hollow side down — the way we are used to seeing them stacked in boxes — and they’re still soft. Check out this guy squishing one. This explains the weirdly distorted ones we sometimes find amongst the good ones.

After they cool & harden, they’re coated with a water-based paint and conveyed through a hot-air tunnel to cure the paint. Finally, they’re machine-stacked into nice neat columns.

Nice. I only wish I could hit more of them during a round of skeet!

The post Watch: Clay Pigeons on ‘How It’s Made” appeared first on AllOutdoor.com.

via All Outdoor
Watch: Clay Pigeons on ‘How It’s Made”

Synchronize and migrate data between the application and the database

Data migrations from Laravel

This package simplifies the migration and synchronization of data between the application and the database, allowing you to control for example settings or permissions lists. Provides resources to view the status and changes not yet made, migrate and synchronize the data.

Installation

composer require fndmiranda/data-migration 

Usage

You may generate an data migration of the data-migration:make Artisan command:

php artisan data-migration:make PermissionDataMigration 

This command will generate a data migration at app/DataMigrations/PermissionDataMigration.php. The data migration will contain the model, data, and options methods.

<?php  namespace App\DataMigrations;  use Fndmiranda\DataMigration\Contracts\DataMigration;  class PermissionDataMigration implements DataMigration {  /**  * Get the model being used by the data migration.  *  * @return string  */  public function model()  {  //  }   /**  * Get the data being used by the data migration.  *  * @return mixed  */  public function data()  {  //  }   /**  * Get the data options being used by the data migration.  *  * @return mixed  */  public function options()  {  //  } }

Method model

Method to specify the model bound to the data migration class.

/**  * Get the model being used by the data migration.  *  * @return string  */ public function model() {  return \App\Permission::class; }

Method data

Method to specify the data to be migrated.

/**  * Get the data being used by the data migration.  *  * @return mixed  */ public function data() {  return [  ['name' => 'product.products.index', 'title' => 'List products', 'group' => 'Product'],  ['name' => 'product.products.show', 'title' => 'Show product', 'group' => 'Product'],  ['name' => 'product.products.store', 'title' => 'Create product', 'group' => 'Product'],  ['name' => 'product.products.update', 'title' => 'Update product', 'group' => 'Product'],  ['name' => 'product.products.destroy', 'title' => 'Delete product', 'group' => 'Product'],   ['name' => 'product.brands.index', 'title' => 'List brands', 'group' => 'Product'],  ['name' => 'product.brands.show', 'title' => 'Show brand', 'group' => 'Product'],  ['name' => 'product.brands.store', 'title' => 'Create brand', 'group' => 'Product'],  ['name' => 'product.brands.update', 'title' => 'Update brand', 'group' => 'Product'],  ['name' => 'product.brands.destroy', 'title' => 'Delete brand', 'group' => 'Product'],  ]; }

Method options

The options method to specify the parameters to be used in the migration.

/**  * Get the data options being used by the data migration.  *  * @return mixed  */ public function options() {  return [  'identifier' => 'name',  'show' => ['name', 'title'],  ]; }

The following keys are available as options:

Key Description Type
identifier Column with unique value to validate status. string
show Columns to show in commands output. array
relations Relationships options, see the usage with relationships. array

Run a data migration

You can run a data migration via command or facade.

Show the status of each data with the database with data-migration:status Artisan command:

php artisan data-migration:status App\\DataMigrations\\PermissionDataMigration 

Output:

+--------------------------+------------------------+--------+ | name | title | status | +--------------------------+------------------------+--------+ | product.products.index | List products | Create | | product.products.show | Show product | OK | | product.products.store | Create product updated | Update | | product.products.destroy | Delete product | OK | | product.brands.show | Show brand | Create | | product.brands.store | Create brand updated | Update | | product.brands.update | Update brand | OK | | product.brands.destroy | Delete brand | OK | | product.products.update | Update product | Delete | | product.brands.index | List brands | Delete | +--------------------------+------------------------+--------+ 

Or with DataMigration facade:

$status = DataMigration::status(\App\DataMigrations\PermissionDataMigration::class);

Show changes between data migration and database with data-migration:diff Artisan command:

php artisan data-migration:diff App\\DataMigrations\\PermissionDataMigration 

Output:

+--------------------------+------------------------+--------+ | name | title | status | +--------------------------+------------------------+--------+ | product.products.index | List products | Create | | product.products.store | Create product updated | Update | | product.brands.show | Show brand | Create | | product.brands.store | Create brand updated | Update | | product.products.update | Update product | Delete | | product.brands.index | List brands | Delete | +--------------------------+------------------------+--------+ 

Or with DataMigration facade:

$diff = DataMigration::diff(\App\DataMigrations\PermissionDataMigration::class);

Migrate data from a data migration to the database. Only necessary operations with status to create will be executed with data-migration:migrate Artisan command:

php artisan data-migration:migrate App\\DataMigrations\\PermissionDataMigration 

Output:

+--------------------------+------------------------+--------+ | name | title | status | +--------------------------+------------------------+--------+ | product.products.index | List products | Create | | product.brands.show | Show brand | Create | +--------------------------+------------------------+--------+ 

Or with DataMigration facade:

$migrated = DataMigration::migrate(\App\DataMigrations\PermissionDataMigration::class);

Synchronize data from a data migration with the database. All necessary create, update, and delete operations will be performed with data-migration:sync Artisan command:

php artisan data-migration:sync App\\DataMigrations\\PermissionDataMigration 

Output:

+--------------------------+------------------------+--------+ | name | title | status | +--------------------------+------------------------+--------+ | product.products.index | List products | Create | | product.products.store | Create product updated | Update | | product.brands.show | Show brand | Create | | product.brands.store | Create brand updated | Update | | product.products.update | Update product | Delete | | product.brands.index | List brands | Delete | +--------------------------+------------------------+--------+ 

Or with DataMigration facade:

$synchronized = DataMigration::sync(\App\DataMigrations\PermissionDataMigration::class);

Usage with relationships

Example of a permissions model with a relationship for dependencies of type belongsToMany with pivot_example_1 and pivot_example_2, and a relationship for brand of type belongsTo to exemplify a data migration.

<?php  namespace App;  use Illuminate\Database\Eloquent\Model;  class Permission extends Model {  /**  * The attributes that are mass assignable.  *  * @var array  */  protected $fillable = [  'name', 'title', 'group', 'brand_id',  ];   /**  * The dependencies that belong to the permission.  */  public function dependencies()  {  return $this->belongsToMany(Permission::class)->withPivot(['pivot_example_1', 'pivot_example_2']);  }   /**  * Get the brand of the permission.  */  public function brand()  {  return $this->belongsTo(Brand::class);  } }

Method data with relationships

The data method to specify the data to be migrated with relationships.

/**  * Get the data being used by the data migration.  *  * @return mixed  */ public function data() {  return [  ['name' => 'product.products.index', 'title' => 'List products', 'group' => 'Product', 'brand' => ['name' => 'Brand test 1']],  ['name' => 'product.products.show', 'title' => 'Show product', 'group' => 'Product'],  ['name' => 'product.products.store', 'title' => 'Create product', 'group' => 'Product', 'dependencies' => [  ['name' => 'product.brands.index', 'pivot_example_1' => 'Pivot value 1'], ['name' => 'product.categories.index'],  ], 'brand' => ['name' => 'Brand test 2']],  ['name' => 'product.products.update', 'title' => 'Update product', 'group' => 'Product', 'dependencies' => [  ['name' => 'product.brands.index'], ['name' => 'product.categories.index', 'pivot_example_2' => 'Pivot value 2'],  ]],  ['name' => 'product.products.destroy', 'title' => 'Delete product', 'group' => 'Product'],   ['name' => 'product.brands.index', 'title' => 'List brands', 'group' => 'Product', 'brand' => ['name' => 'Brand test 1']],  ['name' => 'product.brands.show', 'title' => 'Show brand', 'group' => 'Product'],  ['name' => 'product.brands.store', 'title' => 'Create brand', 'group' => 'Product'],  ['name' => 'product.brands.update', 'title' => 'Update brand', 'group' => 'Product', 'brand' => ['name' => 'Brand test 2']],  ['name' => 'product.brands.destroy', 'title' => 'Delete brand', 'group' => 'Product'],  ]; }

Method options with relationships

The options method with relationships to specify the parameters to be used in the data migration.

/**  * Get the data options being used by the data migration.  *  * @return mixed  */ public function options() {  return [  'identifier' => 'name',  'show' => ['name', 'title'],  'relations' => [  [  'type' => 'belongsToMany',  'relation' => 'dependencies',  'identifier' => 'name',  'show' => ['name'],  ],  [  'type' => 'belongsTo',  'relation' => 'brand',  'identifier' => 'name',  'show' => ['name'],  ],  ],  ]; }

The following keys are available as relationships options:

Key Description Type
relation Name of the relationship of the model. string
type Model relationship type, belongsToMany or belongsTo. string
identifier Column with unique value to validate status. string
show Columns to show in commands output. array

Security

If you discover any security related issues, please email fndmiranda@gmail.com instead of using the issue tracker.

License

The MIT License (MIT). Please see License File for more information.

via Laravel News Links
Synchronize and migrate data between the application and the database

Laravel Tip: 5 examples of why you should be using Macros


Go to the profile of Peter Fox

Photo by Lance Asper on Unsplash

Macros in Laravel are something that I think are still not talked about enough in the framework. They’re really power and really useful. I don’t think there’s a project I’ve created in the last year or two that isn’t using a macro somewhere.

To cover what a macro is briefly, it’s a way of extending a class’ methods but without using inheritance and instead it works by adding a Closure to a class. This then means that all instances of that class has that newly added method. Any class that has uses the Macroable trait found in the Laravel framework can have macros applied to them.

In this article I want to cover a range of simple use cases that will improve things for you, reducing duplicating code, making code more readable or simply getting around problems you might have in testing.

How to make them and where to put them

This isn’t an obvious thing from the get go. There’s one of two places I would advise putting your macros. The first is by using a simple PHP file loaded up via Composer. I generally make this new file in the app folder and call it macros.php Then you simply edit the autoloader key in composer.json to have a files property and within that array list you should add the relative path to the fileapp/macros.php. This then just requires running composer dump-autoloader so the newly added file will be loaded and executed at runtime, setting up our macros for the entire application.

The other place to put Macros is in the boot method of service providers. This can get a bit messy to be honest as your application grows and you add more macros but there will be the odd Macro that can’t be configured in the macros.php file, namely when adding macros to the Route class as it’s tied to the instance stored in the service container. We won’t be using the Route class in this article though.

Collections

Ok, this is a boring one, but it’s where most people will have been introduced to Macros in Laravel so I wanted to cover this one quickly. A nice little example of one macro I’ve had to use before is converting keys for array, something that could be quite tedious if you wrote it out as a function.

Instead we can add it as a macro. First we can make a macro to do all the mapping for us and manage it recursively.

Then we’ll make another just to wrap it up nicely.

That’s it. Now we can use it like the following example.

Eloquent Queries

This is probably one of the most important places where macros really make a difference. For example it would be near impossible to extend the query builder yourself but with a macros you don’t have to.

For example, often you might want to make direct use of functionality in your database server and often you’ll do this with raw queries.

But this can become very repetitive if you’re doing this in your application a lot, let alone when mixing trying to do multiple wheres in one statement.

One way to get around this might be to use a scope but then this still requires added the scope to any model you need to use it with. We can really just make a macro for this. In this example we’ll make a macro for filter results in MySQL using the built in geospatial functions of the server.

Then we can add another macro just so we can do orWhere statements with it as well.

Now when we want to do filtering by MySQL we can call it directly like any other where statement.

Testing Responses

Writing feature tests are common and really effective but it can get quite repetitive. Worst yet, maybe you have something custom, like an API that always returns the HTTP status as 200 but returns something like

{"error"=>true,"message"=>"bad API call"}

You might end up needing write tests like this

Which is fine for one test, but what about all of them. Maybe a macro could solve this, and guess what it can.

Firstly, we’re going to want to make a tests/macros.php this time and add it to composer.json instead under the autoload-dev then files array that we need to likely add ourselves. We also need to reload the autoloader with composer dump-autoloader afterwards.

Then in the new macro file tests/macros.php file we can add the following.

Now we can use it our tests.

It’s a very simple snippet but it really can make your tests far more readable when you start reducing repetitive behaviors into reusable macros.

File operations (for mocking)

Another time where a macro is useful is when you want to make use of Facades and their ability to be mocked swifty for your unit tests. No better scenario exists for mocking than using the built in PHP classes that will touch the file system during a test.

For example, see this code using the ZipArchive class.

I can’t mock this, it’s a totally new instance of a ZipArchive class. At best I could make some ZipArchive factory to make the class but it seems a bit overkill just to use a simple bit of PHP’s built in functionality. Instead we’ll macro it (in our app/macros.php file).

So when it comes to production code all we need to do is use the facade.

But for our tests we just mock the method using the Facade.

This means we not longer have to worry about cleaning up the file system for our tests. We’ve neatly wrapped up our Zip Archive logic into something reusable but also something easily mockable.

Validation Rules

The last of the examples is really simple but again will help hugely when it comes to managing your code.

For example, often I’ve come across this and it’s no surprising because I used to do it too.

It’s not very clean looking on it’s own, let alone when there’s multiple fields and multiple rules per field like this.

Instead we’re be much better off with something like the following

And with a macro we can.

Bonus Tip: What to do when you’ve got too many macros in one really long file?

You’ve seen the example now but what about when you now have so many macros that you find it hard to actually find or just organise them? The instant go to might be to just make more files like app/validation_macros.php but you’d be wrong. This is where Mixins come in (not to be confused with Traits which are sometimes thought of as Mixins due to other languages having mixins as a concept).

A mixin is a class that defines lots of Macros that can then be provided to your macroable class to implement all of them in one go.

Lets look at an example by creating a new class app/RulesMixin.php.

As you can see from the code above, all the mixin has to go is implement a method with no arguments that returns the closure that will be our macro, using the method name for the macro as well.

Now in our app/macros.php we can just set up the class to use the macro like the following

This then means the Rule class will not only still have the before method, it’ll now have the after, beforeOrEqual and afterOrEqual validation rules in a more accessible format.

Conclusions

Overall I really enjoy the use of Macros in Laravel and can’t emphasise enough how useful they can be for extending the functionality of the framework to suit your needs without lots of work to do so.

If you want to see more classes that use the Macroable trait I’ve put together a quick list for Laravel 5.8.

If you want to see the project implementation you can view the code on GitHub.


I’m Peter Fox, a software developer in the UK who works with Laravel among other things. If you want to know more about me you can at https://www.peterfox.me and feel free to follow me @SlyFireFox on twitter for more Laravel tips and tutorials.

via Laravel News Links
Laravel Tip: 5 examples of why you should be using Macros

Eager Load Relations of Morphed Models in Laravel 5.8.22

Eager Load Relations of Morphed Models in Laravel 5.8.22

The Laravel team released v5.8.22 yesterday with a new morphWith method to eager load relationships of morphed models. This release is packed with new features so be sure to check out the full release notes and a few notes about some of the new features below.

First, a new @componentFirst directive was added, which is similar to how @includeFirst works:

<div> @componentFirst(['missing/file', 'found/file']) @slot('title', 'Test Component') @endcomponent </div> 

Next, a new withMorph method was added when you want to load relations of morphed models eagerly:

$comments = Comment::query() ->with(['commentable' => function (MorphTo $morphTo) { $morphTo->morphWith([Post::class => ['user']]); }]) ->get(); 

I would recommend checking out Pull Request #28647 for a better understanding of how this works. One benefit of this approach is that nested relationships are supported by using with (as seen in the above example).

Next, a new containsAll method was added to the Str utility class which determines if a given string contains all array values:

// true Str::containsAll('taylor otwell', ['taylor', 'otwell']); // false Str::containsAll('taylor otwell', ['taylor', 'xxx']); 

Next, error handling for maintenance mode commands was introduced which now outputs a failed message and an exit code of 1 if either up or down commands fail.

Next, the TestResponse::assertJsonValidationErrors method now has message value assertions which enables you to check both error keys and messages:

$response->assertJsonValidationErrors([ 'key' => 'validation message' ]); 

The JSON validation errors message still allows index arrays which will assert a matching key, and a mix of both indexed array values and associative arrays of key and message values.

This assertion also accepts an array of messages:

$response->assertJsonValidationErrors([ 'key' => ['validation message', 'another validation message'], ]); 

I also wanted to give a massive shout-out to Tetiana Blindaruk for handling the changelog and releases for Laravel. It’s not an easy job to consolidate all the merged pull requests and commits and format them into a clean changelog. Thank you, Tetiana!

You can see the full list of fixes below, and the whole diff between 5.8.21 and 5.8.22 on GitHub. The full release notes for Laravel 5.8 are available in the GitHub 5.8 changelog:

v5.8.22

Added

  • Added @componentFirst directive (#28783)
  • Added support for typed eager loads (#28647, d72e3cd)
  • Added Related and Recommended to Pluralizer (#28749)
  • Added Str::containsAll() method (#28806)
  • Added: error handling for maintenance mode commands (#28765, 9e20849)
  • Added message value assertion to TestResponse::assertJsonValidationErrors() (#28787)
  • Added: Automatically bind the viewAny method to the index controller action (#28820)

Fixed

  • Fixed database rules with where clauses (#28748)
  • Fixed: MorphTo Relation ignores parent $timestamp when touching (#28670)
  • Fixed: Sql Server issue during dropAllTables when foreign key constraints exist (#28750, #28770)
  • Fixed Model::getConnectionName() when Model::cursor() used (#28804)

Changed

  • Made force an optional feature when using ConfirmableTrait. (#28742)
  • Suggest resolution when no relationship value is returned in the Model::getRelationshipFromMethod() (#28762)

Filed in: News / Releases


Enjoy this? Get Laravel News delivered straight to your inbox every Sunday.

No Spam, ever. We’ll never share your email address and you can opt out at any time.

via Laravel News
Eager Load Relations of Morphed Models in Laravel 5.8.22

6 Great Sites For Buying Ammunition Online

Credit: Douglas Muth/Wikimedia Commons/CC-BY

Buying ammunition online can save you money and get you far more in terms of choice. Prices are usually lower (watch out for those shipping charges, though) and you aren’t at the mercy of the local gun store’s distributor.

No, your LGS doesn’t buy straight from Federal or Winchester. They go through a third, fourth or even a fifth party depending on the distributor they deal with. That’s why some stores seem to have different ammo for sale all the time.

Before we begin, however, we need to point out that California has made the online purchase of ammunition more difficult for the people who live there. (The Nanny State Strikes Again: Electric Boogaloo) Since purchase of ammunition now requires a background check, it makes buying ammo online more complicated.

The quick version is that you can still buy your ammunition online, but it has to be shipped to either a designated FFL or a California Ammo Vendor with a Certificate of Eligibility in jurisdictions that do not forbid having ammunition shipped to an FFL or CAV/COE for purchase.

Obviously, it’s not that you can’t, but it’s more complicated than it was or needs to be thanks to California’s apparent need to continually make it hard for anyone to enjoy anything, anywhere, ever, at all.

With that said, if you want to secure a regular supply of a particular box and brand, or buy in bulk, getting your ammunition online is one of the best ways to do it.

However, take into consideration what kind of ammunition you’re shopping for. There are certain brands/boxes/types of ammunition that any retailer will have (hardball for range use) and others that you have to find the right source for. Every ammunition site is a little different and tends to caters to a specific market. For instance, some have a lot of different rifle ammo choices, some are a bit more weighted to handguns, and so on.

With that said, who are the go-tos?

Credit: Midwayusa.com

MidwayUSA is one of the largest online retailers of all things gun-related, including a decent selection of…ammunition. Here you can find a pretty decent cross-section of every kind of gun food you might want, from bulk FMJ to JHP for concealed carry, JSP for handgun hunting and anything and everything in between.

Selection isn’t unlimited, but they have far more than almost any other online ammunition retailer. If there’s a one-stop-shop for all things ammunition, guns and so on, Midway USA is as close as it gets.

MidwayUSA is also one of the few somewhat reliable sources for occult esoteric like 7.62mm Tokarev, .45 GAP, 7mm Shooting Times Westerner or .35 Whelen, which many ammunition websites don’t stock at all and you can basically forget about finding in local stores.

Credit: ableammo.com

Able’s Ammo comes close to Midway in terms of breadth and depth of selection. Prices are competitive, and you can find almost any style of bullet you might want. They have a good mix of bulk ammunition and practical ammunition as well.

Credit: luckygunner.com

If all you’re looking for is pistol ammo – and maybe some 5.56/.223 on the side – then LuckyGunner.com is also a very decent supplier. They have a generous selection for people who own typical handguns in typical chamberings such as 9mm, .40 S&W and so on, with a few “oddballs” (.25 and .32 ACP, .50 AE, .357 Sig) as well. FMJ and JHP abounds, so most handgunners will be able to find almost anything they need.

As a bonus, LuckyGunner also produces some fantastic video content as well as maintains a testing database for concealed carry ammunition. Their test is similar to the FBI protocol, so you can see if they’ve tested your carry rounds or the ones you’re thinking of switching to.

Credit: ammunitiondepot.com

Ammunition Depot bridges the gap, so to speak, between Midway and LuckyGunner. The former has darn near everything, the latter only deals in the most popular handgun, a very limited number of rifle calibers (5.56/.223, 7.62x39mm and .308/7.62mm NATO) and does offer some 12-gauge shotgun shells.

Ammunition Depot expands their rifle offerings to include more common rifle calibers and a bit more in terms of shotgun offerings.

However, pickings are a little slimmer for rifle ammunition basically outside of the AR/AK/tactical rifle/assault rifle/modern sporting rifle/whatever you want to call a semi-auto family. In other words, you’ll be happier than a pig in slop if you want .300 Blackout. If you have a .30-06, they have some, but be prepared to feel almost as let down than Cleveland Browns fans.

Credit: sportsmansguide.com

Sportsman’s Guide is not a bad choice for ammunition either. Granted, there are certain things they don’t have much or any of (shop for your JHP elsewhere) but what they DO usually have is great for certain people.

Specifically, they have a good selection of hunting ammunition and some fantastic deals on bulk ammunition as well. If you’re stocking up on, say, Nosler Partitions or laying in a few thousand rounds of 9mm hardball or 5.56/.223, they’re a great source.

Credit: ammo.com

Ammo.com is one of the few sites that comes close to rivaling Midway in terms of sheer breadth of selection. Rifle, pistol and shotgun ammo abounds and with multiple bullet styles and in dozens of calibers. However, their forte is volume, so this isn’t where you go to get a box or two of hardball for the range, hollow points for concealed carry or JSP for hunting. This is where you go to buy A LOT of it.

If you feel like there is a better source than the above, say so in the comments! We, along with everyone else, are always interested in finding a new, better, more cost-effective and reliable source of freedom seeds.

via The Truth About Guns
6 Great Sites For Buying Ammunition Online

The Right to Bear Which Arms? – 2A Interpretation and the Federalist Papers

By Mark Houser

The 2020 presidential campaigns have just begun, but on the issue of gun control, we’re already hearing a common refrain from numerous candidates: The Second Amendment does not protect anyone’s right to own, as they put it, “weapons of war” (a term the candidates use to refer to such things as semi-automatic rifles and standard-capacity magazines).

That’s wrong. The Second Amendment unambiguously protects our right to own “weapons of war.” That is, weapons suitable not just for sport, but for combat.

Many people find this obvious. It’s hard to imagine what else the Second Amendment could possibly be intended to do. James Madison wrote the Second Amendment in the aftermath of a bloody war for independence from a tyrannical empire. The first shots of that war were fired to resist disarmament. Can anyone truly believe that Madison wrote the Second Amendment with, say, hunting or target shooting in mind? It’s a preposterous notion.

But, let’s suppose that we’re not sure what “arms” the Second Amendment refers to. How might we figure out what the authors of our Constitution and Bill of Rights were thinking when they used the term “arms?” Were they thinking about “weapons of war,” or something else?

The Federalist Papers offer a window into the minds of the founders of our country and the architects of our Constitution specifically during the time between its writing and subsequent ratification (and the addition of the Bill of Rights).

In the papers, the term “arms” appears 27 times. “Arms” unambiguously refers to weapons (rather than something like “appendages”) 25 times. In every instance that the term “arms” refers to “weapons,” “arms” is used in the context of combat and warfare, not recreation.* Here are just a few examples:

“(W)ho, by their joint counsels, arms, and efforts, fighting side by side throughout a long and bloody war, have nobly established general liberty and independence.” –Federalist 2 (John Jay)

“(T)hat combination and union of wills of arms and of resources, which would be necessary to put and keep them in a formidable state of defense against foreign enemies.” –Federalist 5 (John Jay)

“To these would be opposed a militia amounting to near half a million of citizens with arms in their hands…fighting for their common liberties…It may well be doubted, whether a militia thus circumstanced could ever be conquered by such a proportion of regular troops. Those who are best acquainted with the last successful resistance of this country against the British arms, will be most inclined to deny the possibility of it.” –Federalist No. 46 (James Madison)

Moreover, in the papers’ extensive discussions of the civilian militia, there is never any suggestion that the arms of the militia ought to be different from or inferior to those of the state military. If anything, the papers call for parity in arms between the militia and the state military.

In Federalist 29, Hamilton wrote:

“If circumstances should at any time oblige the government to form an army of any magnitude that army can never be formidable to the liberties of the people while there is a large body of citizens, little, if at all, inferior to them in discipline and the use of arms, who stand ready to defend their own rights and those of their fellow-citizens.”

This statement simply wouldn’t make sense if Hamilton envisioned the militia being armed with categorically inferior weapons compared to those carried by the state military. What good is a militia that’s well-trained, but poorly armed?

And note that the terms “sport,” “game,” and “hunt” do not appear anywhere in the Federalist Papers. That the Second Amendment protects the right to own weapons suitable for fighting is clear not only from what the papers say, but also from what they don’t say.

Gun control proponents are quick to point out that Madison and his contemporaries didn’t imagine the sort of weapons that exist today. That’s probably true, but it’s irrelevant to the question at hand.

We don’t say that the First Amendment doesn’t apply to typed or online publications simply because the Framers did not imagine typewriters or the internet. We don’t say that the Fourth Amendment does not apply to search and surveillance capabilities that the Framers did not imagine, such as GPS tracking. Technological development doesn’t change the fundamental nature of the rights that the Bill of Rights seeks to secure.

The Second Amendment clearly and unambiguously protects the right to own weapons suitable for combat. The Bill of Rights concerns itself with defense against tyrants–foreign and domestic–not with clay pigeons or whitetail deer.

The only way to escape this conclusion is to adopt a method of constitutional interpretation that willfully ignores the clear language and plain meaning of the Constitution and thus imperils every right that it seeks to secure.

Note, I have not argued here that it’s a good thing that the Second Amendment secures the right to own “weapons of war.” I have merely shown that the Second Amendment obviously does secure that right. Intellectually honest opponents and proponents of gun control alike must recognize that reality.

Yes, this is an inconvenient truth for gun control proponents, because it means that measures they think are “common sense” (like an “assault weapons ban”) are blatantly unconstitutional, and, if the courts are faithful to the document, would require a constitutional amendment in order to be legal.

However, gun-rights supporters can’t complacently retreat to the apparent safety of the Second Amendment, no matter how plain and obvious its meaning. On the contrary, they would do well to remember that the Constitution has been amended 17 times since the adoption of the Bill of Rights.

Our rights may be innate and eternal, but the document that protects them from violation is certainly not. And even if the document remains unchanged, we have ample evidence that, without our tireless vigilance, it will often be ignored.

So it’s not enough to merely have the Constitution and to know what it means. We must also do the continual work of holding our politicians accountable to it.

 

* The Anti-Federalist papers use “arms” in the same way.

via The Truth About Guns
The Right to Bear Which Arms? – 2A Interpretation and the Federalist Papers

SQL Having Clause Example | SQL Having Tutorial

SQL Having Clause Example | SQL Having Tutorial

SQL Having Clause Example | SQL Having Tutorial is today’s topic. The SQL HAVING clause is used in the combination with a GROUP BY CLAUSE to restrict the groups of returned rows to only those whose condition is TRUE. The HAVING clause was added to SQL because the WHERE keyword could not be used with aggregate functions.

SQL Having Clause Example

SQL HAVING filters the records that work on summarized GROUP BY results. The HAVING applies to the summarized group records, whereas WHERE applies to the individual records. Only the groups that meet a HAVING criteria will be returned. HAVING requires that the GROUP BY clause is present. WHERE and HAVING can be in a same query.

Syntax

SELECT Expressions, aggregate functions(aggregate_expression) 
FROM TABLE
WHERE CONDITION 
GROUP BY COLUMN
HAVING CONDITION;

PARAMETERS

Expressions: Expressions that are not encapsulated within the aggregate function and must be included in the GROUP BY Clause near the end of an SQL statement.

Aggregate function: Sum, count, Min, Max are some of the aggregate functions.

Aggregate Expressions: It is the column expression used in an aggregate function.

Table: Name of the table.

Where Condition: Where condition Is used for the records to be selected.

Group By: It is a keyword used for grouping some rows based on the same values.

Having Keyword: This is the further condition applied only to an aggregated results to restrict the groups of the returned rows. Only those groups whose condition evaluates to be TRUE will be included in the result set.

Let’s clear with an example:

Consider the following Table.

CUSTOMERS

CUST_CODE CUST_NAME CITY GRADE AMOUNT
101 SHUBH KOLKATA 1 10000
201 SOURAV KOLKATA 1 10000
301 KISHAN PATNA 2 20000
401 DILEEP ALLAHABAD 2 30000
501 SHRUTI PATNA 3 40000

In this, we are going to use the aggregate function count. See the following query.

QUERY

Select city,count(grade) 
From customers 
Group By city 
Having count(grade)>=2;

See the following output.

SQL Having Clause Example

 

Explanation

In the above example, we have displayed the total no of employees having similar grades greater than 2, and their city groups data.

SQL Having With Aggregate MIN

In this example, we are going to use the aggregate function MIN.

QUERY

Select city, MIN(amount) as “LESS AMOUT” 
From customers 
Group By city 
Having MIN(amount)>10000;

See the following output.

HAVING Clause with SQL MIN

 

Explanation

In this example, we have displayed the Min amount a customer has belonging to the respective city.

SQL Having With Aggregate SUM

In this example, we are going to use an aggregate function SUM.

QUERY

Select city, SUM(amount) 
From customers 
Group By city 
Having sum(Amount) >= 10000;

See the output.

SQL Having With Aggregate SUM

 

Explanation

In this example, we have displayed the total sum of the number of customers belonging to the same city.

SQL Having With Aggregate MAX

In this example, we are going to use the aggregate function MAX.

QUERY

Select city, MAX(amount) 
From customers 
Group By city 
Having MAX(amount)<20000;

OUTPUT

SQL Having With Aggregate MAX

 

Explanation

In this example, we have displayed the max amount from customers grouped by their cities.

SQL Having With Aggregate WHERE

In this example, we are going to use the where keyword.

QUERY

Select city, SUM(amount) 
From customers 
Where grade=2 
Group By city 
Having sum(amount) >= 10000;

OUTPUT

SQL Having With Aggregate WHERE

 

In this example, we have displayed the total sum of amount whose grades are 2 and are grouped by their city and also having a total sum greater than equal to 10000.

SQL Having With Aggregate Order By

In this example, we are going to use the ORDER BY keyword.

QUERY

Select city, sum(amount) 
From customer 
Where grade=2 
Group By city 
Having sum(amount)>=10000 
Order By city;

OUTPUT

SQL Having With Aggregate Order By

 

Explanation

In this example, we have displayed the total sum of amount whose grades are 2 and are grouped by their city and also having a total sum greater than equal to 10000 followed by order by, which have displayed the city in ascending order as ASC is executed by default.

When WHERE statement, GROUP BY, and HAVING clauses are used together in the SELECT statement, the WHERE clause is processed first and then rows that are returned after a WHERE clause is executed are grouped based on a GROUP BY clause. Finally, any conditions on that group functions in a HAVING clause are applied to the grouped rows before the final output is displayed.

So, we have seen SQL Having with WHERE clause, GROUP BY, ORDER BY and all the aggregate functions.

Finally, SQL Having Clause Example | SQL Having Tutorial is over.

The post SQL Having Clause Example | SQL Having Tutorial appeared first on AppDividend.

via Planet MySQL
SQL Having Clause Example | SQL Having Tutorial