Star Trek: Picard’s latest trailer suggests the series will end with a bang

http://img.youtube.com/vi/wo2V1cSVj-w/0.jpg

With New York Comic Con underway this weekend, Paramount shared a new trailer for the final season of Star Trek: Picard. After the previous teasers mostly played up the nostalgia of the principal cast of The Next Generation returning to the franchise, the new trailer finally offers a look at season three’s story. And judging from the clip, Picard will end with a bang.

The trailer opens with Starfleet facing an entirely new threat in the form of an alien vessel called the Shrike. What follows is a fun series of scenes that sees Admiral Jean-Luc Picard recruit his old friends, some of them a little less than willing, to face a villain played by Pulp Fiction’s Amanda Plummer. There’s something satisfying about seeing how characters like Worf have changed in unexpected ways in their later years. Even more unexpected are the two cameos at the end of the trailer. Daniel Davis is back as holographic Professor Moriarty, while Brent Spiner will play Data’s evil Android twin, Lore.

Alongside a new trailer for Star Trek: Picard, Paramount also shared fresh teasers for season five of Discovery and the midseason return of Prodigy. The latter will debut on October 27th, while the former is expected to arrive sometime next year. The final season of Picard will begin streaming on February 16th, 2023.

Engadget

Amazon Is About to Sell This 4K Smart TV for Just $112

https://i.kinja-img.com/gawker-media/image/upload/c_fill,f_auto,fl_progressive,g_center,h_675,pg_1,q_80,w_1200/c4822647607b44b683e658aafba1d9fe.jpg

Photo: Terry Papoulias (Shutterstock)

A slick 55-inch 4K Smart TV for $112? Could that even be a real thing? It might be for Amazon Prime members: Last Thursday, Amazon released some of the deals members can expect to find during its Prime Early Access Sale, a two-day sale intended to kick off the holiday shopping season. And at the top of that list is the Amazon Fire TV Omni Series 55-inch 4K Smart TV (with hands-free Alexa) that will be 80% off its $559.99 market price, for a grand total of $112. (As of this writing, it’s “on sale” for $509.99.)

With anything Amazon-related, a healthy dose of skepticism is both fair and good. They use tricks to encourage shoppers to impulse-buy things they don’t really need or even want, which can then hardly count as a true deal. As Lifehacker staff writer Stephen Johnson has previously said:

In spite of the many, many online guides about how to take advantage of the savings, there’s only one piece of advice you actually need for Prime Day if you want to save money: Don’t buy anything you weren’t planning to buy already. There’s also a corollary: if you do find a bargain on something you wanted anyway, make sure it’s actually a bargain.

Most of the time, the best deals that are worth the hype tend to be Amazon’s own products—as is this TV, which reinforces that idea. So if you were already in the market for a new TV, read the reviews for this specific model to see if it fits your needs. The sale begins Tuesday, Oct. 11. There is no mention of how many will be in stock, so if you’ve decided this deal is for you, add the TV to your cart now, and make sure your address and forms of payments are up to date. Once the sales become live, you’ll be ready to snatch one for yourself.

Lifehacker

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

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

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

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 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

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