PHP Monitor 5.0 for macOS is Here

https://laravelnews.imgix.net/images/phpmon-5-0-featured.png?ixlib=php-3.3.1

PHP Monitor, the lightweight native Mac app to manage PHP and Laravel Valet, has released v5.0!

The author Nico Verbruggen announced the release yesterday:

Here are some of the highlight features summarized from the release notes:

  • Link a folder in Valet
  • Site list performance improvements
  • Faster and improved site search
  • Site list displays project type (i.e., Laravel, WordPress, etc.) from composer.json
  • Brew services status in the dropdown menu (PHP, Nginx, Dnsmasq, etc.)
  • See project’s PHP version requirement at a glance in the site list
  • Compatibility status per site
  • Change PHP versions from the compatibility status on the sites list
  • Automatic update of PHP INI changes
  • Alfred integration
  • Sponsor awareness – a one-time message to sponsor the author

One of my favorite features added is linking a folder and securing it (adding HTTPS) during creation:

PHP Monitor folder linking example

Linking a folder makes it convenient to manage projects via the UI and visualize the requirements for all your sites in one place. The site list updates in v5.0 are insane!

On his blog, the author has written about the 5.0 release with insider details. I recommend giving it a read and following the author for future updates.

To get started, check out the GitHub project for documentation and installation instructions. Since this project is free and open-source, you can support the creator by sponsoring his work.

Laravel News

Rudy Giuliani Shocker: Revealed as Contestant on Fox’s ‘Masked Singer,’ Triggers Liberal Judges to Walk Off

https://www.louderwithcrowder.com/media-library/image.jpg?id=29228886&width=980

If you watch FOX’s "The Masked Singer" and are worried about spoilers… Whoops, too late! Rudy Guliani was revealed as one of the masked singers and two of the liberal judges were pissed. First, if you are unfamiliar with the show–I’ve never watched and am going off of this Deadline article–this is the masked singer.


Preview: The Good, The Bad, And The Cuddly | Season 7 | THE MASKED SINGER

youtu.be

Celebrities dress up as furries and sing songs. Other celebrity judges have to guess who the celebrity is. On a taping for the debut episode, one of those celebrities is Rudy Guiliani. If you want to know what furry he was or what song he sang, you’ll have to tune in to the show. OR, you can not care. What’s making the story trend is that two leftist judges, Robin Thicke and Ken Jeong, walked off in protest.

Robin Thicke is best known as being Alan Thicke’s less talented son, and for that one song where he stole the melody from Marvin Gaye. That one song people say is kinda rapey. Except, now, the people who call it rapey won’t care as much after Thicke stuck it to a Trump associate by walking off a stage. Ken Jeong is best known from this gif:

Rudy Guliani is, as you all know, the former Mayor of New York City and a frequent guest on the Louder with Crowder program. He’s also friends with Donald Trump and was in the news for some legal challenge that if mentioned will cause Facebook to immediately slap this post with a "fact" check. I’ll just say those legal challenges are most likely what triggered Thicke and Jeong. That, and how dare Fox normalize someone who has a different opinion than them. Leftists hate it when that happens.

If you were wondering why Rudy is trending today, I hope this clears things up.

The Louder with Crowder Dot Com Website is on Instagram now! Follow us at @lwcnewswire and tell a friend!


Steak-FIGHT at the Golden Corral! Crowder & Dave Rip on it for 10 minutes! | Louder With Crowder

youtu.be

Louder With Crowder

Optimus Prime Wants You to Go the Hell to Sleep

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/ba009492ecde73f47b299db909a23498.jpg

You can now have Optimus Prime read you a bedtime story. This is not a sentence I expected to write today, and yet, it is now an inescapable fact that you can go to bed listening to the dulcet tones of the leader of the Autobots… as he describes the horrible wars that enveloped his home planet Cybertron before coming to Earth. Sweet dreams!

To clarify, you’ll need to have access to the immensely popular meditation/relaxation/sleep assistance app Calm—specifically, the Calm Kids iteration—to hear Optimus narrate a “Sleep Story,” which the company describes as being “soothing tales that mix music, sound fx, and incredible voice talent to help you drift into dreamland.” The story is titled “History of the Transformers,” which doesn’t seem like a tale that would be easy to drift off to given that the vast majority of it has to do with the endless wars between the Autobots and the Decepticons.

That said, Optimus, as per the classic cartoons and modern live-action movies, is played by Peter Cullen, whose deep, low, soothing voice seems absolutely tailor-made to lull just about anyone to sleep, no matter what he was reading. You can get a too-brief 30-second preview of the Sleep Story over at Calm, and hear for yourself.

The press release adds, “This never-before-heard Transformers story tells the history of the Autobots and Decepticons, taking listeners deeper into the More-Than-Meets-the-Eye themes of the iconic franchise, exploring bravery, leadership, friendship, and STEM.” I’m very curious about how much importance will be placed on science, technology, engineering, and mathematics in the recording, given that 1) virtually all of the STEM in Transformers is made up, and 2) I don’t know much you’re going to learn about these sciences while you are literally falling asleep. There’s not a chance in hell that any fact I heard would remain in my mind come daybreak, no matter what robot told it to me

“History of the Transformers” is available now in the Calm Kids app. If we’re lucky, the next release will be terrorist leader Cobra Commander reading a bedtime story about the time he created an entire game show just to make G.I. Joe feel dumb.


Wondering where our RSS feed went? You can pick the new up one here.

Gizmodo

Database transaction middleware in Laravel

https://nico.orfanos.dev/card.png

Why transactions are a good thing.

Let’s say that in your application all users have to belong to a team. And in your createUser action, you create a user and then you assign this user a team.

$user = User::create(['email'=> '[email protected]'); $user->teams()->attach($team->id); //Throws an exception

If you get an Exception while attaching the Team to the User, your application ends with a wrong state where you have a User which hasn’t a Team assigned.

This is simple to fix in this case, but it can be more complex in other cases and by using database transactions will yourself these state fixes. Because, when using database transactions, if the team assignment throws an exception, your application will also prevent the user creation.

How to implement write transactions in Laravel

Database transactions are good practice for all write actions. Therefore we create a global middleware for this, using the following command.

$ php artisan make:middleware DatabaseTransaction

and we change the handle method like below:

//app/Http/Middleware/DatabaseTransaction.php public function handle($request, \Closure $next) { if (!in_array($request->method(),['POST','PUT','PATCH','DELETE'])) { return $next($request); } DB::beginTransaction(); try { $response = $next($request); } catch (\Exception $e) { DB::rollBack(); throw $e; } if ($response->getStatusCode() > 399) { DB::rollBack(); } else { DB::commit(); } return $response; }

This code will check if we make a write operation by checking if the request method of the request is a write one, and start a transaction. If within the write request something goes wrong it will roll back the transaction.

The only thing left to do is to register the middleware to our web middleware group in the app/Http/Kernel.php.

//app/Http/Kernel.php protected $middlewareGroups = [ 'web' => [ // ... \App\Http\Middleware\DatabaseTransaction::class ], ];

Now your application will use this DatabaseTransaction middleware on every request.

What to keep in mind

Once you have fully integrated database transactions in your applications, there is this one thing that you need to watch out for when dispatching jobs. If you dispatch a job and later your application rolls back, your job will still be processed by your queue.

For that reason, Laravel has the afterCommit method which you can chain after the dispatch. This way you are safe that the dispatch will only run if the response was successful.

So if you also are sending an email after the user creation, your code should look like this:

$user = User::create(['email'=> '[email protected]'); $user->teams()->attach($team->id); dispatch(new SendWelcomeEmail($user))->afterCommit();

Final words

The accuracy, completeness, and reliability of your database data are viable things for your application. Using database transactions in Laravel is easy for us to take advantage of them.

Laravel News Links

Comic for February 01, 2022

https://assets.amuniversal.com/45d192405d30013a93c2005056a9545d

Thank you for voting.

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

Dilbert Daily Strip

An Easier Way to Navigate: Company Gives Every Location on Earth a Three-Word Code

https://s3files.core77.com/blog/images/1235230_81_111998_fvwb6ugBw.jpg

Unless you drive a new Ford, Mercedes-Benz, Tesla, Land Rover or Lamborghini, you may not be aware that those automakers have embraced a new, easier and more precise way to navigate by voice. All five companies have incorporated or are incorporating what3words technology.

To explain, what3words is a company that simply "divided the world into 3 metre squares and gave each square a unique combination of three words," they write. "It’s the easiest way to find and share exact locations."

"Street addresses weren’t designed for 2022. They aren’t accurate enough to specify precise locations, such as building entrances, and don’t exist for parks and many rural areas. This makes it hard to find places and prevents people from describing exactly where help is needed in an emergency."

You say the three words representing your destination aloud, and the car punches that precise spot into the nav. You can also download what3words as an app. It’s not limited to just English, either; it’s available in 50 languages and they’re working on more.

I think it’s a brilliant idea. I’m a native New Yorker, and could ask my native friends to meet me in Manhattan on the northwest corner of 37th and 5th. But newcomers to the city would be flummoxed by such directions, which also happen to be a mouthful. To be able to boil it down to three short words and have the phone figure out the rest would be tremendously helpful.

In a rural situation, too. My wife and I now live on a 47-acre farm in the South. She’s also a native New Yorker and down here, we are the ones at a disadvantage; we struggle to describe specific locations on the property, whereas the locals fluently use ground features, tree species and natural conformations as descriptive landmarks. It would be much easier if I could tell my wife that I’m off to clear the fallen tree at Pancake Monkey Zilch.

As for how to discover the three words for a given location, you must first look it up on the map in their app the conventional way, then click on the desired square to learn the words. Then you can save the location, or remember or write the words down.

Years and years ago, I was in Manhattan and waiting for the light at the northeast corner of Lafayette and Houston. A woman had come out of the nearby subway and was clearly lost. She pulled out her cell phone and called someone. "I don’t know where I am," she said. "Can you find me? …But I don’t know where I am!"

Across the street was a gigantic billboard for the then-popular video game, Grand Theft Auto.

"I’m in front of Grand Theft Auto," the girl said into the phone.

If I was a genius, I’d have been inspired by the moment, and started what3words first. Instead, I am a blogger writing about them.

Core77

Laravel Livewire for Beginners – Full 2021 Guide


If you’ve been coding with Laravel for some time, you must have heard about the ‘magical’ Laravel Livewire package. Livewire is a truly awesome (and almost magic) way to create interactive interfaces and communicate ‘realtime’ with your Laravel backend. And it does this all in a very simple way. In this article I’ll show you the basics of Laravel Livewire, so that you will be up-and-running with Livewire in no-time🚀

The combination of simplicity and power is what makes Laravel Livewire so awesome and why it is used by so many developers. It is especially a good alternative to the Laravel + Inertia + Vue combination, in particular if you’re still used to the ‘Vue-magic’, but feel that Vue is too much of a hassle to set up.

The basics of Livewire

The first thing you should know is that Livewire works with so-called components. That means that you can have a search component, an edit component, you name it. Each Livewire component consists of (in most cases) two files:

  • The component class file
  • The Blade file with the markup (the HTML)

Additionally, you could also have a test for each component, but that’s something you should care about later (but don’t forget it!😄).

Installing Livewire

First, you need to install Laravel Livewire. To do so, run the following composer command:

composer require livewire/livewire

Next, you need to load a Livewire JavaScript file and a Livewire CSS file. Without loading those files on a page, you cannot use Livewire. Luckily, Livewire makes this really easy for us. All you need to do is adding the below two Blade directives in your Blade files and make sure that these directives are loaded on every page.

The best place to put them is normally in your layouts/app.blade.php file:

<html>
   <head>
      ...
      @livewireStyles
   </head>
   <body>
      ...
      @livewireScripts
   </body>
</html>

Creating Livewire components

Now it’s time to create our first Livewire component! The best way to create a Livewire component is to run the following artisan command, similar to the regular Laravel artisan commands:

php artisan make:livewire ComponentName

This will create two files, the file with the Livewire logic and the Blade layout:

  • App\Http\Livewire\ComponentName.php
  • resources/views/livewire/component-name.blade.php

You can also create a Livewire component in a namespace:

php artisan make:livewire Dashboard/ComponentName

The above command creates the following two files:

<?php

namespace App\Http\Livewire;

use Livewire\Component;

class ComponentName extends Component
{
    public function render()
    {
        return view('livewire.component-name');
    }
}
<div>
    
</div>

With just these two files you can create great interactive Livewire components!

Creating a Livewire search component

So, what’s so special about Livewire? The special ‘magic’ thing about Livewire is that it allows (almost) realtime communication between your server (the backend) and the frontend. This means that you could have a variable, change it in your PHP and the frontend automatically updates with the new values.

Imagine that you have a page in your Laravel app with tabs. You could have a variable that holds the name of the current tab. In your frontend Blade files, you could do an @if() condition to show the correct markup. Changing the variable for example on click, the markup would automatically change without reloading the page!🤯

The Livewire website has a great example on their homepage that shows the power of Livewire, so let’s start with that.

use Livewire\Component;

class SearchUsers extends Component
{
    public $search = '';
 
    public function render()
    {
        return view('livewire.search-users', [
            'users' => User::where('username', $this->search)->get(),
        ]);
    }
}
<div>
   <input wire:model="search" type="text" placeholder="Search users..."/>

   <ul>
       @foreach($users as $user)
           <li></li>
       @endforeach
   </ul>
</div>

So, what do we see here? We see that we have a variable in our Livewire component, called $search. Every variable (or property or attribute) that you declare as public on the Livewire class, is available to the frontend and it updates realtime.

The frontend has an <input> element where people enter their search query. The value of this input element is ‘connected’ to the value of the public $search property. And the $users variable that is passed to the frontend, depends on the public $search. So if the value of public $search changes, the value of $users changes and the frontend also updates – without a page reload. Magic, right?

Make sure your template file has one <div> root element

A thing that’s good to know is that your Blade template file may only contain a single <div> als root element. This means that all your own code is always inside a single <div>. I’m saying it here, before you find yourself debugging this issue.

PS: you are not restricted to a <div> element, but a div is the most common one. As long as it’s only one root element.

How to display a Livewire component

Now that you’ve got an idea of how a Livewire component looks like, you might be wondering how to display it on a page. There are multiple ways to display a component, so you can choose one of the following ways to include a Livewire component in a Blade file:

<livewire:search-users />

@livewire('search-users')

@livewire(App\Http\Livewire\SearchUsers::class)

You can also add data to each Livewire component:

@livewire('search-users', [ 'company' => $company ])
// Add the following public property to your SearchUsers component. Livewire will map the $company automatically to the correct property.

public Company $company;


// If you want more control over how the properties are stored, you can also accept them in the mount() method:

public Company $myCompany;

public function mount(Company $company) {
   $this->myCompany = $company;
}

You can also use Livewire as a full-page component. That means that this would work:

use App\Http\Livewire\SearchUsers; 

Route::get('/{organization}/users/search', SearchUsers::class);
public function render()
{
   return view('livewire.search-users', [
          'users' => User::where('username', $this->search)->get(),
       ])->extends('layouts.app');
}

Checkout the Livewire docs for more information if you’re interested in using fullpage components.

Using Actions

Another very handy thing is the use of Livewire actions. Livewire actions mean you can define a public function on your component and call this action from the frontend. For example, if a user clicks on a button.

This example comes from the docs and I think that it’s a great example that shows the power of Livewire really well:

class ShowPost extends Component
{
   public Post $post;

   public function like()
   {
       $this->post->addLikeBy(auth()->user());
   }
}
<div>
    <button wire:click="like">Like Post</button>
</div>

As a summary, Livewire will now call the like() function every time the users click the <button>. You can add a wire:click="" directive to every element you want, so it is not limited to buttons and <a href="">s.

Using forms with Laravel Livewire

Next, I would like to talk about forms in Livewire. The way Livewire handles forms might classify as one of the most powerful Livewire features. It wouldn’t surprise me if it is one of the most commonly used features.

Let’s see how it works.

First, we have the Blade file. Just like in ‘regular’ non-Livewire HTML, each form is wrapped in a <form> tag. The big difference is that a Livewire form doesn’t have the action="", type="" and method="" tags.

So how do we tell Livewire where to send the information to?

We can do so with the wire:submit.prevent attribute. Adding this attribute to the <form> looks like this: <form wire:submit.prevent="save"> . It tells Livewire: ‘when the form is submitted, prevent the normal submit action and call the save() function instead.

Let’s see this in action. We start by modifying our Blade file so that it contains a very simple form, asking for just an e-mailaddress.

<div>
    <form wire:submit.prevent="save">

        <input type="email" wire:model="email" placeholder="Email">

        <button type="submit">Submit form</button>

    </form>
</div>

Next, let’s add the function save() to the Livewire component:

public function save()
{
    $this->validate();

    $user = User::create([
        'email' => $this->email,
    ]);

    dump('User created successfully!');
}

Let’s also add a public property called $email and make sure to set a default value like an empty string, '' . If the field is optional, you can also make the variable type nullable by adding a ? before the type and assigning a default value of null.

public string $email = '';
public ?string $email = null; // Optional field

This property will always contain the value of the input field, because we bind these values together with the wire:model="email" attribute on the input.

You see that we’re using the $this->validate() method. This should always be the first method in your save() function, because it will run all the validation rules. If the validation fails, it stops the flow of the code.

So how do we define those rules?

To do so, add a protected $rules property to the Livewire component. (See the power of favouring convention over configuration?)

protected $rules [
   'email' => 'required|email'
];

Now, we are almost ready to start using our first Livewire component. We only need a place to display potential error messages.

You can use the @error directive for that. Now our Blade file should look like this:

<div>
    <form wire:submit.prevent="save">

        <input type="email" wire:model="email" placeholder="Email">
        @error('email') <span class="error"></span> @enderror

        <button type="submit">Submit form</button>

    </form>
</div>

If you want to customize the error messages or the attribute names, checkout the documentation.

Realtime form validation & Livewire lifecycle hooks

Another cool feature I want to show you, is the realtime validation feature. How is that possible?

Livewire allows you to add specific function to the component, like updatedVARIABLENAME(), updatingVARIABLENAME(). Those functions are called lifecycle hooks. You can add them for each variable, and each time that variable is updated, this function will run.

So if we want to validate the $email input every it changes – realtime as the user is typing – we can use a lifecycle hook for that:

public function updatedEmail($value)
{
    $this->validateOnly('email');
}

You can also use a more generic lifecycle hook, which runs on every property update. This is in particular handy if you have long forms and you don’t want ten functions all doing the same validation over and over.

public function updated($propertyName)
{
    $this->validateOnly($propertyName);
}

Next steps

As you’ve seen, Livewire allows PHP-developers to implement pretty amazing interactivity in their Laravel-apps, without developers needing to write a single line of JavaScript.

For developers like me, who have much more feeling with PHP then with JavaScript, Livewire saves so much time.

Now that you know the basics of Livewire, I’d recommend to start using it as much as possible, in order to experience the full power of Livewire. There’s so much more I didn’t tell here, so start using it, take a dive in the documentation later and enjoy!⚡️

Laravel News Links