FBI Massively Understates Shooting Statistics: Analysis Show Armed Americans Stop About Half of Active Killer Attacks

https://cdn0.thetruthaboutguns.com/wp-content/uploads/2022/10/FBI-active-shooter.jpg

Screen cap by Boch via FBI.

Next Post Coming Soon…▶

The Federal Bureau of Investigation continues to tarnish its own reputation by vastly downplaying — by a factor of more than 10 — the number of incidents in which armed Americans stop spree killers. According to the FBI, the same people who can find no evidence of crime on Hunter Biden’s laptop, only 4.4% of these incidents were stopped by a good guy “civilian” with a gun. Analysis by the Crime Prevention Research Center shows the actual number is closer to 50% or more in some instances.

Not only that, but with each passing year, the numbers of spree killings cut short by everyday Americans carrying firearms continues to steadily grow. That shouldn’t surprise anyone as more and more Americans get concealed carry licenses, to say nothing of the half of the nation now living under constitutional carry laws where good guys don’t need a permission slip to carry.

What’s more, in non-“gun-free” zones where good guys aren’t prohibited from carrying lawfully, the number of mass murders interrupted is over 50%.

Image by Boch. Base image by Crime Prevention Research Center.

The CPRC, John Lott’s group, took the time to do the research and what they found is truly appalling. Example: the FBI claimed the would-be murder spree in a White Settlement, Texas church wasn’t stopped by a civilian good guy. Instead, the FBI massaged that case and sorted it as a “security guard” stopping the attack.

How did the Fibbies’ galaxy brains steer that away from a “good guy with a gun” description? They claimed that because Jack Wilson volunteered as church security, he was a “security guard.”

You be the judge. Was that Mr. Wackenhut or Ms. Securitas who took down this killer, or was it an everyday good guy with a gun?

Then again, this is the same FBI that took weeks to determine that the San Bernardino mass killers were jihadists. Ditto for the Pulse Nightclub killer.

The Crime Prevention Research Center has the details . . .

The shooting that killed three people and injured another at a Greenwood, Indiana, mall on July 17 drew broad national attention because of how it ended – when 22-year-old Elisjsha Dicken, carrying a licensed handgun, fatally shot the attacker.

While Dicken was praised for his courage and skill – squeezing off his first shot 15 seconds after the attack began, from a distance of 40 yards – much of the immediate news coverage drew from FBI-approved statistics to assert that armed citizens almost never stop such attackers: “Rare in US for an active shooter to be stopped by bystander” (Associated Press); “Rampage in Indiana a rare instance of armed civilian ending mass shooting” (Washington Post); and “After Indiana mall shooting, one hero but no lasting solution to gun violence” (New York Times).

Evidence compiled by the Crime Prevention Research Center shows that the sources the media relied on undercounted the number of instances in which armed citizens have thwarted such attacks by an order of more than ten, saving untold numbers of lives. Of course, law-abiding citizens stopping these attacks are not rare. What is rare is national news coverage of those incidents. Although those many news stories about the Greenwood shooting also suggested that the defensive use of guns might endanger others, there is no evidence that these acts have harmed innocent victims.

The FBI reports that armed citizens only stopped 11 of the 252 active shooter incidents it identified for the period 2014-2021. The FBI defines active shooter incidents as those in which an individual actively kills or attempts to kill people in a populated, public area. But it does not include those it deems related to other criminal activity, such as a robbery or fighting over drug turf.

An analysis by my organization identified a total of 360 active shooter incidents during that period and found that an armed citizen stopped 124. A previous report looked at only instances when armed civilians stopped what likely would have been mass public shootings. There were another 24 cases that we didn’t include where armed civilians stopped armed attacks, but the suspect didn’t fire his gun. Those cases are excluded from our calculations, though it could be argued that a civilian also stopped what likely could have been an active shooting event.

The FBI reported that armed citizens thwarted 4.4% of active shooter incidents, while the CPRC found 34.4%.

As usual with John Lott’s research, there’s a ton of details and background information at the link.  Go read it.

Two factors explain this discrepancy – one, misclassified shootings; and two, overlooked incidents. Regarding the former, the CPRC determined that the FBI reports had misclassified five shootings: In two incidents, the Bureau notes in its detailed write-up that citizens possessing valid firearms permits confronted the shooters and caused them to flee the scene. However, the FBI did not list these cases as being stopped by armed citizens because police later apprehended the attackers. In two other incidents, the FBI misidentified armed civilians as armed security personnel. Finally, the FBI failed to mention citizen engagement in one incident.

For example, the Bureau’s report about the Dec. 29, 2019 attack on the West Freeway Church of Christ in White Settlement, Texas, that left two men dead does not list this as an incident of “civic engagement.” Instead, the FBI lists this attack as being stopped by a security guard. A parishioner, who had volunteered to provide security during worship, fatally shot the perpetrator. That man, Jack Wilson, told Dr. John Lott that he was not a security professional. He said that 19 to 20 members of the congregation were armed that day, and they didn’t even keep track of who was carrying a concealed weapon.

As for the second factor — overlooked cases — the FBI, more significantly, missed 25 incidents identified by CPRC where what would likely have been a mass public shooting was thwarted by armed civilians. There were another 83 active shooting incidents that they missed.

It’s almost as if the Biden administration and Merrick Garland’s FBI have been working hard to smother the facts showing that good guys with guns do indeed stop bad people with evil in their hearts.

And that’s despite the fact that most of these shootings intentionally occur in “gun-free” zones, where only the good guys are disarmed and the bad guys know they’ll find defenseless victims. Because of this, we, as the armed citizenry, have one hand tied behind our back when it comes to these statistics. Even without the .gov’s stats massaging trickery.

Americans aren’t stupid though.

 

Next Post Coming Soon…▶

The Truth About Guns

TFB Review: The Magpul RLS – Rifleman Loop Sling

https://www.thefirearmblog.com/blog/wp-content/uploads/2022/09/RLS-19-180×180.jpg

TFB Review: The Magpul RLS - Rifleman Loop SlingMost people use rifle slings to carry a long gun when their hands are busy with other things. Various trends have come and gone, such as the three-point and one-point slings. Another classic style of sling that is not as common today is the shooting sling, which secures around the arm to add tension and […]

Read More …

The post TFB Review: The Magpul RLS – Rifleman Loop Sling appeared first on The Firearm Blog.

The Firearm Blog

Roblox sued for allegedly enabling young girl’s sexual, financial exploitation

https://cdn.arstechnica.net/wp-content/uploads/2022/10/GettyImages-1235736525-760×380.jpg

Roblox sued for allegedly enabling young girl’s sexual, financial exploitation

Through the pandemic, the user-created game platform that’s so popular with kids, Roblox, expanded its user base and decided to go public. Within two years, its value shot from less than $4 billion to $45 billion. Now it’s being sued—along with Discord, Snap, and Meta—by a parent who alleges that during the pandemic, Roblox became the gateway enabling multiple adult users to prey on a 10-year-old girl.

The lawsuit filed Wednesday in the San Francisco Superior Court shows how sexual predators can exploit multiple social platforms at once to cover their tracks while financially and sexually exploiting children. It alleges that, in 2020, Roblox connected a young girl called S.U. with adult men who abused her for months, manipulating her into sending payments using Roblox currency called Robux and inducing her to share explicit photos on Discord and Snapchat through 2021. As the girl grew increasingly anxious and depressed, the lawsuit alleges that Instagram began recommending self-harm content, and ultimately, S.U. had to withdraw from school after multiple suicide attempts.

Like many similar product liability lawsuits that social platforms have recently faced for allegedly addicting children and causing harms, this new lawsuit seeks to hold platforms accountable for reportedly continuing to promote the use of features that tech companies know can pose severe risks for minor users. And S.U.’s guardian, known as C.U. in the lawsuit, wants platforms to pay for profiting off systems that allegedly recklessly engage child users.

The lawsuit says that platforms neglect to prevent predator access to minors, suggesting cheap and simple fixes that platforms overlook because they’d potentially limit profits. These suggestions include warning minors about potential predatory engagement, verifying the age of account holders, restricting adult users from messaging minor users, banning adult users who message minors, or preventing minors from circumventing parental oversight by limiting minor’s access to certain features and abilities to create duplicate accounts.

A Roblox spokesperson told Ars, “While we do not comment on pending litigation, Roblox has a safety-first culture and works tirelessly to maintain a platform that is safe and civil for all.” Roblox also says it has a zero-tolerance policy for users “endangering or sexualizing children in any way” and takes “swift action against anyone found to be acting in breach of our Community Standards.”

Discord told Ars it scans every image on its platform to detect child sexual abuse materials and, echoing Roblox, said it has a zero-tolerance policy and takes immediate action when it becomes aware of child endangerment or sexual exploitation. “This includes proactively investigating and banning users, shutting down servers, and making targeted efforts to detect and disable accounts that violate our Terms of Service and Community Guidelines.”

Snap did not immediately provide comment to Ars.

Meta told Ars that it cannot comment on active litigation but says its “deepest sympathies are with anyone affected by these difficult and complex issues.”

Meta has, arguably, faced the most criticism on this issue, ever since whistleblower Frances Haugen told the US Senate how Facebook knowingly harmed young users. A Meta spokesperson told Ars that it has implemented changes on Instagram that are similar—though seemingly weaker—to the changes the lawsuit seeks.

“Teens automatically have their accounts set to private when they join Instagram, adults can’t message teens that don’t follow them, we don’t show accounts belonging to teens to some adults in places where we suggest content, and we have controls designed to limit the types of content teens see,” a Meta spokesperson told Ars.

As a result of S.U.’s experiences on Roblox, Discord, Snapchat, and Instagram, the girl’s guardian C.U. has since had to quit her “dream job” with the government, sacrificing benefits and a pension, to attend to S.U.’s escalated care needs. So far, C.U. says in the lawsuit that she has gone into $10,000 in debt from healthcare co-pays and that S.U. continues to need care for ongoing health issues.

The lawsuit seeks damages from social platforms to help recover the costs of S.U.’s medical care, as well as monetary damages for S.U.’s future care, C.U.’s income loss and future earning capacity, punitive damages, and more, to be determined, they’ve demanded, by a jury.

Ars Technica – All content

Are You Nuts? Know your Fishing Knots! – The Uni-to-Uni Knot

https://www.alloutdoor.com/wp-content/uploads/2022/10/20221004_182715.jpg

Where going with a different style of knot for this week, instead of a knot used to connect your fishing line or leader to a hook, swivel, or lure. I’m going to show you how to tie a Uni-to-Uni Knot, a line-to-line connection, perfect for tying a monofilament leader to your mainline, or in a pinch a line splice if you get partially spooled and need to add more line to a reel. The Uni-to-Uni Knot consists of two uni knots as the name implies. The knots are tied around the other line and then are pulled together to make a strong connection. This is a very strong line-to-line connection that is much easier than something like an FG Knot or Bobbin Knot, but does suffer from being bulky and not sliding through the guides as easily.

Step 1

Overlap your two lines with each other.

Step 2

With the first line make a loop parallel to the other line, don’t cross over the other line just yet.

Are You Nuts? Know your Fishing Knots! – The Uni-to-Uni Knot

Step 3

Wrap the tag end of the first line several times through the loop you first formed, minimum four wraps but use more for the thinner the lines you are tying.

Are You Nuts? Know your Fishing Knots! – The Uni-to-Uni Knot

Step 4

Wet the line and wraps and then cinch the knot down, but not too tight, and leave the tag end still.

Are You Nuts? Know your Fishing Knots! – The Uni-to-Uni Knot

Step 5

Now with the other line, you are going to repeat steps 1 through 3 and start tying another uni knot on the first line.

Are You Nuts? Know your Fishing Knots! – The Uni-to-Uni Knot

Step 6

Again make sure the line is wet then tighten the second uni knot but again don’t cinch it all the way down.

Are You Nuts? Know your Fishing Knots! – The Uni-to-Uni Knot

Step 7

Wetting both the lines, pull the two uni knots towards each other. Once they are tight against each other do a final cinching down and then cut the tags short. If using a monofilament line you can carefully use a lighter to make a small bead of melted line at the tag end for extra security, but you must make sure not to burn the knot or lines.

Are You Nuts? Know your Fishing Knots! – The Uni-to-Uni Knot

The post Are You Nuts? Know your Fishing Knots! – The Uni-to-Uni Knot appeared first on AllOutdoor.com.

AllOutdoor.com

Laravel Controller into Service Class with Injection

https://laraveldaily.com/storage/113/controller-service-injection.png

In this article, I will show you how to shorten Controllers by using Service classes, and different ways to initialize or inject that Service.

First, the “before” situation – you have a Controller with two methods: store() and update():

class UserController extends Controller
{
    public function store(StoreUserRequest $request)
    {
        $user = User::create($request->validated());

        $user->roles()->sync($request->input('roles', []));

        // More actions with that user: let's say, 5+ more lines of code
        // - Upload avatar
        // - Email to the user
        // - Notify admins about new user
        // - Create some data for that user
        // - and more...

        return redirect()->route('users.index');
    }

    public function update(UpdateUserRequest $request, User $user)
    {
        $user->update($request->validated());
        $user->roles()->sync($request->input('roles', []));

        // Also, more actions with that user

        return redirect()->route('users.index');
    }
}

This Controller is too long – the logic should be somewhere else.


Refactoring – Step 1: Service Class

One of the ways to refactor it is to create a specific Service class for everything related to the User, with methods like store() and update().

Note that Laravel doesn’t have php artisan make:service command, you need to create that class manually, as a regular PHP class.

And then, we move that code from Controller, into a Service:

app/Services/UserService.php:

namespace App\Services;

class UserService {

    public function store(array $userData): User
    {
        $user = User::create($userData);

        $user->roles()->sync($userData['roles']);

        // More actions with that user: let's say, 5+ more lines of code
        // - Upload avatar
        // - Email to the user
        // - Notify admins about new user
        // - Create some data for that user
        // - and more...

        return $user;
    }

    public function update(array $userData, User $user): User
    {
        $user->update($userData);
        $user->roles()->sync($userData['roles']);

        // Also, more actions with that user
    }
}

Then, our Controller becomes much shorter – we’re just calling the Service methods.

There are a few ways to do this. The most straightforward one is to create a Service class instance whenever you need it, like this:

use App\Services\UserService;

class UserController extends Controller
{
    public function store(StoreUserRequest $request)
    {
        (new UserService())->store($request->validated());

        return redirect()->route('users.index');
    }

    public function update(UpdateUserRequest $request, User $user)
    {
        (new UserService())->update($request->validated(), $user);

        return redirect()->route('users.index');
    }
}

Refactoring – Step 2: Inject Service

Instead of doing new UserService() every time we need it, we can just insert it as a dependency in the methods where we need it.

Laravel will auto-initialize it, if we provide the type-hint inside the Controller methods:

use App\Services\UserService;

class UserController extends Controller
{
    public function store(StoreUserRequest $request, UserService $userService)
    {
        $userService->store($request->validated());

        return redirect()->route('users.index');
    }

    public function update(UpdateUserRequest $request, User $user, UserService $userService)
    {
        $userService->update($request->validated(), $user);

        return redirect()->route('users.index');
    }
}

We can go even further and inject the Service class into a constructor of the Controller. Then, we have access to the service in whatever Controller methods we need.

use App\Services\UserService;

class UserController extends Controller
{
    private UserService $userService;

    public function __construct(UserService $userService)
    {
        $this->userService = $userService;
    }

    public function store(StoreUserRequest $request)
    {
        $this->userService->store($request->validated());

        return redirect()->route('users.index');
    }

    public function update(UpdateUserRequest $request, User $user)
    {
        $this->userService->update($request->validated(), $user);

        return redirect()->route('users.index');
    }
}

Finally, we can use the PHP 8 relatively new syntax called constructor property promotion, so we don’t even need to declare a private variable, or assign something in the constructor:

use App\Services\UserService;

class UserController extends Controller
{
    public function __construct(private UserService $userService)
    {
    }

    // We can still use $this->userService anywhere in the Controller
}

I have a separate video, specifically on that PHP 8 feature:


That’s it for this article. Of course, there are other ways to separate the code from the Controller – Action classes, Repositories and other patterns – so choose whichever you like, the logic of injecting or initializing that class would be the same.

Laravel News Links

Laravel Controller into Service Class with Injection

https://laraveldaily.com/storage/113/controller-service-injection.png

In this article, I will show you how to shorten Controllers by using Service classes, and different ways to initialize or inject that Service.

First, the “before” situation – you have a Controller with two methods: store() and update():

class UserController extends Controller
{
    public function store(StoreUserRequest $request)
    {
        $user = User::create($request->validated());

        $user->roles()->sync($request->input('roles', []));

        // More actions with that user: let's say, 5+ more lines of code
        // - Upload avatar
        // - Email to the user
        // - Notify admins about new user
        // - Create some data for that user
        // - and more...

        return redirect()->route('users.index');
    }

    public function update(UpdateUserRequest $request, User $user)
    {
        $user->update($request->validated());
        $user->roles()->sync($request->input('roles', []));

        // Also, more actions with that user

        return redirect()->route('users.index');
    }
}

This Controller is too long – the logic should be somewhere else.


Refactoring – Step 1: Service Class

One of the ways to refactor it is to create a specific Service class for everything related to the User, with methods like store() and update().

Note that Laravel doesn’t have php artisan make:service command, you need to create that class manually, as a regular PHP class.

And then, we move that code from Controller, into a Service:

app/Services/UserService.php:

namespace App\Services;

class UserService {

    public function store(array $userData): User
    {
        $user = User::create($userData);

        $user->roles()->sync($userData['roles']);

        // More actions with that user: let's say, 5+ more lines of code
        // - Upload avatar
        // - Email to the user
        // - Notify admins about new user
        // - Create some data for that user
        // - and more...

        return $user;
    }

    public function update(array $userData, User $user): User
    {
        $user->update($userData);
        $user->roles()->sync($userData['roles']);

        // Also, more actions with that user
    }
}

Then, our Controller becomes much shorter – we’re just calling the Service methods.

There are a few ways to do this. The most straightforward one is to create a Service class instance whenever you need it, like this:

use App\Services\UserService;

class UserController extends Controller
{
    public function store(StoreUserRequest $request)
    {
        (new UserService())->store($request->validated());

        return redirect()->route('users.index');
    }

    public function update(UpdateUserRequest $request, User $user)
    {
        (new UserService())->update($request->validated(), $user);

        return redirect()->route('users.index');
    }
}

Refactoring – Step 2: Inject Service

Instead of doing new UserService() every time we need it, we can just insert it as a dependency in the methods where we need it.

Laravel will auto-initialize it, if we provide the type-hint inside the Controller methods:

use App\Services\UserService;

class UserController extends Controller
{
    public function store(StoreUserRequest $request, UserService $userService)
    {
        $userService->store($request->validated());

        return redirect()->route('users.index');
    }

    public function update(UpdateUserRequest $request, User $user, UserService $userService)
    {
        $userService->update($request->validated(), $user);

        return redirect()->route('users.index');
    }
}

We can go even further and inject the Service class into a constructor of the Controller. Then, we have access to the service in whatever Controller methods we need.

use App\Services\UserService;

class UserController extends Controller
{
    private UserService $userService;

    public function __construct(UserService $userService)
    {
        $this->userService = $userService;
    }

    public function store(StoreUserRequest $request)
    {
        $this->userService->store($request->validated());

        return redirect()->route('users.index');
    }

    public function update(UpdateUserRequest $request, User $user)
    {
        $this->userService->update($request->validated(), $user);

        return redirect()->route('users.index');
    }
}

Finally, we can use the PHP 8 relatively new syntax called constructor property promotion, so we don’t even need to declare a private variable, or assign something in the constructor:

use App\Services\UserService;

class UserController extends Controller
{
    public function __construct(private UserService $userService)
    {
    }

    // We can still use $this->userService anywhere in the Controller
}

I have a separate video, specifically on that PHP 8 feature:


That’s it for this article. Of course, there are other ways to separate the code from the Controller – Action classes, Repositories and other patterns – so choose whichever you like, the logic of injecting or initializing that class would be the same.

Laravel News Links

Laravel Database Transactions: 3 Practical Examples

https://laraveldaily.com/storage/116/laravel-database-transactions.png

Database transactions are very useful for multiple database operations, and Laravel has functionality for them. But what would be the practical examples of WHEN you should use them?

In short, transactions are useful for multiple database operations, when you want to make sure that if either of them fails, all of them would be rolled back automatically.

In this article, I will show three typical examples, in Laravel:

  • Creating a new record with many-to-many related records
  • Deleting multiple records for a user
  • Updating summary table after a new record

Let’s get practical.


Example 1. Many-to-Many with Transaction.

Take a look at this typical Controller code:

public function store(StoreUserRequest $request) {
    $user = User::create($request->validated());
    $user->roles()->attach($request->input('roles'));

    return redirect()->route('users.index');
}

As you can see, there’s a new User record, and then multiple roles are attached to the User. But what if something goes wrong in the second sentence?

Let’s imagine that $request->input('roles') is passed not as array but as an invalid string. What happens then?

Laravel Database Transaction Error

And the worst part is not about the error, but the fact that the User record has been actually saved to the database.

In the case of users, it may have a bad consequence of email being already taken, although the registration hasn’t actually been finished, as the users.email field is unique on the database level.

That’s why it’s beneficial to use a Database Transaction here:

use Illuminate\Support\Facades\DB;

// ...

public function store(StoreUserRequest $request) {
    DB::transaction(function() use ($request) {
        $user = User::create($request->validated());
        $user->roles()->attach($request->input('roles'));
    }

    return redirect()->route('users.index');
}

Notice: Keep in mind that you need to pass use ($request) or any other external variable that you need to use inside of the transaction function.

Now, don’t get me wrong: you will still get the same error “Incorrect integer value: ‘abcd’ for column ‘role_id’ at row 1”. But the User creation statement will be rolled back, and you won’t see the user in the database.


Example 2. Deleting Multiple Records for User

Let’s imagine you want to delete the record which has a lot of hasMany/belongsToMany relationships. You need to delete them as well, right? If you haven’t set the cascadeOnDelete() on the DB level in migrations, you need to do it manually.

Something like this:

$profile->avatar->forceDelete();
MediaTag::whereProfileId($profile->id)->delete();
StatusHashtag::whereProfileId($profile->id)->delete();
DirectMessage::whereFromId($profile->id)->delete();
FollowRequest::whereFollowingId($profile->id)
    ->orWhere('follower_id', $profile->id)
    ->forceDelete();
Follower::whereProfileId($profile->id)
    ->orWhere('following_id', $profile->id)
    ->forceDelete();
Like::whereProfileId($profile->id)->forceDelete();

// ... only then delete the profile itself:
$profile->delete();

Imagine what happens if some middle sentence in this code snippet fails. So we have deleted something but not everything?

Of course, compared to the previous example, the consequence isn’t as harsh, because, well, we still want to delete those records anyway, we would just do it later.

But still, the profile would remain active but wouldn’t see some of their data, like username without avatar. Not cool, right?

Just add a few lines of code:

DB::transaction(function() use ($profile) {
    $profile->avatar->forceDelete();
    MediaTag::whereProfileId($profile->id)->delete();
    StatusHashtag::whereProfileId($profile->id)->delete();
    DirectMessage::whereFromId($profile->id)->delete();
    FollowRequest::whereFollowingId($profile->id)
        ->orWhere('follower_id', $profile->id)
        ->forceDelete();
    Follower::whereProfileId($profile->id)
        ->orWhere('following_id', $profile->id)
        ->forceDelete();
    Like::whereProfileId($profile->id)->forceDelete();

    $profile->delete();
});

Example 3. Updating “Summary” Table

Imagine a project with users and financial operations. Usually, they would be called “Transactions”, but to avoid confusion with the subject of the article, I will call them just “Expenses”.

You need to track all Expenses and also the current balance of each user. So, after every purchase, you would do something like this:

Expense::create($expenseDetails);
$user->decrement('balance', $expenseDetails->amount);

Sounds trivial, but in more complex scenarios, you would also need to update some more summary data in other tables, for some reporting.

Here, the consequence of not using DB transactions is huge: users would have more money to spend than they should.

Let’s fix this:

DB::transaction(function() use ($expenseDetails, $user) {
    Expense::create($expenseDetails);
    $user->decrement('balance', $expenseDetails->amount);
});

So, these are just three simple examples of DB Transactions. I hope they will push you towards making your data correct all the time.

Laravel News Links

Don’t Use $request->all(): It’s Insecure

https://laraveldaily.com/storage/118/laravel-request-all.png

Quite often, I see Laravel developers using $request->all() in Controller methods. It may be a security issue, let me show you why.


Why $request->all() is insecure

Let’s imagine you have a regular registration form:

Laravel registration form

This form is submitted to this Controller method:

public function store(StoreUserRequest $request) {
    User::create($request->all());

    return redirect()->route('dashboard');
}

We use a Form Request class with validation, so it doesn’t look harmful, does it? It should save name, email, and password, right?

Notice: I know that the password should be encrypted, but in this article, let’s assume the encryption is done somewhere else, like in Observer or Mutator.

Now, let’s take a look at the $fillable array in the User model.

class User extends Authenticatable
{
    protected $fillable = [
        'name',
        'email',
        'password',
        'is_admin',
    ];

See that is_admin column? It is used to assign the administrator role, and that field should be filled only by other administrators, in some other form than the registration, in a separate admin panel.

But what if I try to call that registration to submit by adding a hidden field called is_admin, directly from my browser, like Chrome dev tools, clicking Inspect?

Laravel registration inspect

Laravel registration hidden field

Guess what: the is_admin will be successfully saved, and I will successfully register myself as an administrator, without anyone’s permission.

So, to “hack” the system, all I would need is to guess the non-visual database fields: it may be called is_admin, it may be role_id, just role, or whatever else. Not that hard to write a script to automate trying all the possible options.

This is happening because $request->all() doesn’t filter or validate anything, it’s just literally all().

So, what to do instead?


Option 1. Form Request and validated()

If you use the Form Request class for the validation, you have the rules() method there:

class StoreUserRequest extends FormRequest
{
    public function rules()
    {
        return [
            'name' => ['required', 'string', 'max:255'],
            'email' => ['required', 'email', 'string', 'max:255'],
            'password' => ['nullable', 'string', 'confirmed', 'min:8'],
        ];
    }
}

Then, in the Controller, you should use the request filtered after that validation. For that, just replace $request->all() with $request->validated().

public function store(StoreUserRequest $request) {
    User::create($request->validated());

    return redirect()->route('dashboard');
}

So, it will fill in only the fields that are present in the rules() method.

Keep in mind, that in this case, you need to add all the needed fields into the rules() array, even if it doesn’t require a specific validation, just add them as nullable or string.


Option 2. $request->only()

Of course, another option is to specify the exact fields to be used. One of the options is to use $request->only():

public function store(StoreUserRequest $request) {
    User::create($request->only('name', 'email', 'password'));

    return redirect()->route('dashboard');
}

Option 3. Field by Field

Finally, the good old way of specifying field by field. The code looks longer, but maybe more readable, with less “hidden” information.

public function store(StoreUserRequest $request) {
    User::create([
        'name' => $request->name,
        'email' => $request->email,
        'password' => $request->password,
    ]);

    return redirect()->route('dashboard');
}

All three options above are valid, it’s just your personal preference, which may also depend on the exact form or situation. The main thing is not to use $request->all(), just forget about that method’s existence, for your safety and security.

Laravel News Links

A Laravel package to manage dynamic servers

https://freek.dev/og-images/38c00d66ffaaa8eb3dd0f18d49a128c9/2344.png

I’m proud to announce that our team has released a new package called laravel-dynamic-servers.

This package can help start and stop servers when you need them. The prime use case is to spin up extra working servers to help you process the workload on queues.

In this blog post, I’d like to introduce the package to you.

Why we’ve created this package

We are currently beta testing the hosted version of Mailcoach: an easy-to-use, affordable, platform to send email campaigns, and we also support drip campaigns if that’s what you need.

One of the important aspects of Mailcoach is privacy for those who need it. All open- and click tracking is optional. But we go farther from that. For GDPR-sensitive organizations, such as the government, our legal experts suggested that we would only use infrastructure located on EU territory and owned by EU-based companies.

I feel that if you ask 100 legal experts for advice on this, you’ll get 100 different suggestions. It might have been okay to stay on AWS, but we wanted to be on the safe side and avoid any American-owned companies.

The first version of Mailcoach ran on AWS Lambda via Laravel Vapor. We migrated it to UpCloud servers, a European-located and owned hosting company. Those servers are provisioned via Laravel Forge.

The significant benefit running servers on AWS infrastructure gave us was the automatic scaling. We need autoscaling when people simultaneously start sending campaigns to large email lists. During our beta, this scenario already played out: our service had to send out hundreds of thousands of emails (via the queue) in a short period.

UpCloud is not a serverless platform but uses regular servers. A traditional solution to autoscale servers and orchestrating server stuff would be to use Kubernetes. That piece of software is also very powerful but also hard to learn.

That’s why we invested time in creating a package that allows us to spin up extra servers to handle queued jobs whenever there is extra workload and to destroy them whenever the work is done.

Using dynamic servers

You can think of laravel-dynamic-servers as a sort of PHP-based version of Kubernetes that has 5% of its features but covers that 80% use case. For most PHP and Laravel developers, this package will also be easier to learn and use.

The package is driver based. It ships with support for UpCloud (because we needed that ourselves), but the community already created a DigitalOcean driver, and creating a driver of your own is easy.

Typically, on your hosting provider, you would prepare a server snapshot that will be used as a template when starting new servers.

After the package is installed and configured, you can use PHP to start and stop servers.

Here’s the most straightforward way to start a server via PHP code:

use Spatie\DynamicServers\Facades\DynamicServers;

DynamicServers::increase();

To start a server, the package will start a queued job that makes an API call to your server provider to spin up a server. It will also dispatch subsequent jobs to monitor the entire starting process of a server.

Stopping one server is equally simple:

DynamicServers::decrease();

In most cases, you would use these methods directly, though. The package also offers a method called ensure. You can pass it the number of servers you want to have available in total.

DynamicServers::ensure(5);

If fewer servers are currently active than the number given, more servers will spin up. The package will destroy a few if there are more servers than that number.

Usually, you would have code that calculates the number of servers you need and pass that number to ensure.

Here’s a simplified version of the calculation logic we used at Mailcoach. We use Horizon’s WaitTimeCalulator class to get the waiting time of the queue.

use Laravel\Horizon\WaitTimeCalculator;
use Spatie\DynamicServers\Facades\DynamicServers;

$waitTimesOfAllQueues = (WaitTimeCalculator::class)->calculate();

$maxWaitTime = max($waitTimesOfAllQueues);

// 1 server for every 5 minutes of wait time
$amountOfServersNeeded = floor($waitTimesOfAllQueues / 60 / 5); 

DynamicServers::ensure($amountOfServersNeeded);

So, when the wait times are long, the number of needed servers will be passed to ensure. When the queues are empty, $amountOfServersNeeded will be zero. When zero is passed to ensure, all dynamic servers will be destroyed.

Of course, this logic should be executed frequently. The package has a method determineServerCount which will be executed every minute through a scheduled command. You would typically use it in a service provider:

use Laravel\Horizon\WaitTimeCalculator;
use Spatie\DynamicServers\Facades\DynamicServers;
use Spatie\DynamicServers\Support\DynamicServersManager;

// in some service provider

DynamicServers::determineServerCount(function (DynamicServersManager $servers) {
	$waitTimesOfAllQueues = (WaitTimeCalculator::class)->calculate();
	
	$maxWaitTime = max($waitTimesOfAllQueues);
	
	// 1 server for every 5 minutes of wait time
	$amountOfServersNeeded = floor($waitTimesOfAllQueues / 60 / 5); 
	
	DynamicServers::ensure($amountOfServersNeeded);
});

Suppose you don’t want to possibly wait for a minute until the next invocation of the schedule. In that case, you could additionally listen to Horizon’s LongWaitDetected event and immediately execute the logic above to increase the server count.

In closing

The package contains a lot more features that were not mentioned in this blog post, such as using multiple server types, rebooting servers, setting a server limit, and much more.

You can see the source code of laravel-dynamic-servers in this repo on GitHub.

Should you send a large campaign via Mailcoach, you can be sure that a couple of servers will be spun up for you behind the scenes.

A special thanks to my colleague Rias who picked up this idea from Jmac’s recent streams and blog post on spawning workers based on queue workload.

This isn’t the first package that our team has built. On our company website, check out all our open source packages in this long list. If you want to support us, consider picking up any of our paid products.

Laravel News Links