home.social

#fromzerotohero — Public Fediverse posts

Live and recent posts from across the Fediverse tagged #fromzerotohero, aggregated by home.social.

fetched live
  1. Stasera ore 21.30 nuovo episodio live coding su Twitch di **Delphi spiegato al mio gatto. 🏛️🐈**

    Questa volta parliamo di UI, di componenti e di tool dell'IDE per creare un'app funzionante al 100%.

    Conoscenze minime richieste: zero.
    Partecipate e fate tutte le domande che volete. 😉

    Ciao... anzi, miao! 😸

    Segui la live sul mio canale Twitch:
    👉 twitch.tv/compilaquindiva

    #Programmazione #Delphi #Tutorial #Coding #Live #Twitch #FromZeroToHero

  2. Contents

    Prerequisite

    Before we begin setting up our project, we need to ensure a webdriver is installed on our dev environment. We will be using Laravel Dusk for web interaction tests which will use a headless version of the Chrome browser. If you are using Homestead, you can go ahead and set “webdriver” to true and provision your server.

    Learn more about Laravel Homestead or DDEV with Docker for local Laravel development.

    When running through your provisioning script, it will download and install the Chrome driver ready to be used via Dusk.

    Testing is very much an optional part of development, but it is highly recommended you try it out since many companies and developers are looking at TDD and testing as a requirement.

    Creating the project

    First you need to create our application. If you have Homestead running, then you can SSH into your box and cd into your code directory. Here you can run laravel new blog or you can use composer create-project --prefer-dist laravel/laravel blog if you don’t have the Laravel installer setup. Now you can open the project using your favourite editor.

    Don’t forget to setup the database and point your server configuration to the new project.

    Now you have your project setup, we can move on and create everything needed for user authentication including registering and logging in a user.

    Backend AuthenticationCreating your first PHPUnit tests

    Next, we will be adding some tests for user authentication. You will need to run php artisan make:test UserLoginTest which will create UserLoginTest.php in your tests/Feature directory.

    If you run ./vendor/bin/phpunit you can see how the command works. Your test will pass because of the boilerplate code, but you’ll be removing that and updating it with some real tests.

    Delete the “testExample” method and replace it with this code…

    use RefreshDatabase; public function testUserLogsInSuccessfully() { $user = User::factory()->create([ 'email' => '[email protected]', 'password' => Hash::make('secret') ]); $response = $this->post('/login', [ 'email' => '[email protected]', 'password' => 'secret' ]); $response->assertRedirect('/home'); $this->assertTrue(Auth::check()); $this->assertTrue(Auth::user()->is($user)); } public function testUserLogsInUnsuccessfully() { $user = User::factory()->create([ 'email' => '[email protected]', 'password' => Hash::make('secret') ]); $response = $this->post('/login', [ 'email' => '[email protected]', 'password' => 'incorrect-password' ]); $response->assertSessionHasErrors(['email']); $this->assertFalse(Auth::check()); }

    use RefreshDatabase; tells PHPUnit that in order to run our test, we need to have our tables setup and empty in order to continue.

    Inside of testUserLogsInSuccessfully method, we create a user factory inside the database with the email “[email protected]” and password “secret“. The response is then sending a post request to “/login” with what will be the correct email and password. The test should then expect to receive a redirect to “/home“. The next assertion expects Auth::check() to be true and finally, the last assertion expects the correct authenticated user to match the user within the database and that will return true.

    The testUserLogsInUnsuccessfully will create the same user, but we will purposely use the incorrect details and expect our response to return an error with our email address. It will then check the authentication has failed, which will be true.

    Replace your use statements with this code

    use App\Models\User;use Illuminate\Foundation\Testing\RefreshDatabase;use Illuminate\Foundation\Testing\WithFaker;use Illuminate\Support\Facades\Auth;use Illuminate\Support\Facades\Hash;use Tests\TestCase;

    And now you can run ./vendor/bin/phpunit to run the test suite. Of course this will fail and you’ll see why soon.

    First off, we need to add a database connection into our phpunit.xml file. Open it up and add the following before the closing tag.

    When we run our tests, we will be using sqlite in memory. This means that a database will never be created on our system and once tests are finished, all the data will be cleared.

    Laravel version 7 and 8

    From Laravel version 7, all controller files within the auth directory have been removed and placed into laravel/ui. For the purposes of this course, we’re going to recreate these ourselves, however to begin we will need to enter the following composer require laravel/ui in order to get started.

    Authentication Routes

    First thing you need to do is add the authentication routes. Head over to routes/web.php and add…

    Authentication Controllers

    Next, you need to create the home controller file in app/Http/Controllers/HomeController.php or by running the artisan command php artisan make:controller HomeController if you run the latter command, then remove the code and add the folowing…

    middleware('auth'); } /** * Show the application dashboard. * * @return \Illuminate\Contracts\Support\Renderable */ public function index() { return view('home'); }}

    Within the app/Http/Controllers directory we’ll create a new folder called Auth. Inside our Auth directory, we want to make the following controllers with the following code.

    ConfirmPasswordController.phpmiddleware('auth'); }}LoginController.phpmiddleware('guest')->except('logout'); }}RegisterController.phpmiddleware('guest'); } /** * Get a validator for an incoming registration request. * * @param array $data * @return \Illuminate\Contracts\Validation\Validator */ protected function validator(array $data) { return Validator::make($data, [ 'name' => ['required', 'string', 'max:255'], 'email' => ['required', 'string', 'email', 'max:255', 'unique:users'], 'password' => ['required', 'string', 'min:8', 'confirmed'], ]); } /** * Create a new user instance after a valid registration. * * @param array $data * @return \App\User */ protected function create(array $data) { return User::create([ 'name' => $data['name'], 'email' => $data['email'], 'password' => Hash::make($data['password']), ]); }}ResetPasswordController.php

    If you run ./vendor/bin/phpunit your PHPUnit tests should pass and you have finished this part of the course. If your test fails, it will display an error which will help you fix the test. Be sure not to change the test, but update the code the test is relying on to get the test to green.

    Adding Laravel Dusk for browser tests

    We will be creating this app using TDD which involves creating the tests first to describe our application and having them fail at first. We will then write the application code that will get tests passing. In order to do this you should install Dusk as it will be a part of your testing suite via composer require --dev laravel/dusk.

    If you’re not using Homestead and don’t have the Chrome driver set up, you might be able to run php artisan dusk:chrome-driver and chmod -R 0755 vendor/laravel/dusk/bin/ to ensure permissions are set correctly.

    Once composer has installed the dependancy, you can go ahead a run php artisan dusk:install which will create DuskTestCase.php and ExampleTest.php plus a bunch of other boilerplate code in our tests directory.

    If you’re not using Homestead, you may need to change your DuskTestCase.php inside your tests directory. If you’re like me and you’re running Laravel on DDEV, then go ahead and update it to the following…

    return RemoteWebDriver::create( 'http://selenium-hub:4444/wd/hub', DesiredCapabilities::chrome()->setCapability( ChromeOptions::CAPABILITY, $options ) );

    You may also find this blog post of interest.

    To ensure everything runs correctly, you will need to run php artisan dusk which will run our ExampleTest.php. It may take a moment to run, but with any luck you should see a green passing test.

    If you receive any errors, then please visit the prerequisites to ensure everything has been installed correctly. Go ahead and delete ExampleTest.php as it will no longer be needed.

    Frontend AuthenticationCreating your first Laravel Dusk tests

    With Dusk setup and ready to go, you can create your first test by running php artisan dusk:make UserLoginTest.php.

    Closing thoughts

    This has mostly been boilerplate Laravel authentication as we are trying to replicate a traditional Laravel app. In the next episode, you’ll be looking at implementing the frontend authentication and registration using Laravel Dusk.

    #from-zero-to-hero #laravel #php #tutorial

    https://michaelbrooks.co.uk/laravel-from-zero-to-hero-01-user-authentication/

  3. Contents

    What is Laravel?

    Laravel is a web application framework with expressive, elegant syntax. We’ve already laid the foundation — freeing you to create without sweating the small things. – laravel.com

    Laravel is a web framework built with PHP and gives you the tools you need to create a website.

    Why Choose Laravel?

    Laravel makes PHP development an absolute joy. PHP also gives you so many options since there’s plenty of other frameworks around such as Symfony, Slim, Cake and many more. Laravel has clear, concise documentation and answers most of your worries.

    It covers a broad range of issues which you might come across when developing in any language, but they don’t all come bundled together. Laravel is very well pieced together, and Taylor has managed to keep the core compact while allowing you to expand on the framework through Composer packages.

    Laravel’s packages are very easy to install and have plenty of documentation to cover them as well. If you can’t find your answer then Laravel has an absolutely fantastic community who are always helpful and love to help newcomers.

    Routing

    Routing is one of Laravel’s core concepts and allows you to set out your app’s structure. Firstly, you have web.php where you can place all your web requests, this is where you’ll find frontend and form request/responses. Secondly, their api.php which is where you’ll place any API requests. Representational state transfer aka REST is the most popular architectural choice for creating APIs which we’ll learn more about in the future.

    For the first section of our course, we’ll be using web requests/responses and later move over to JSON API requests/response where it will all become clear.

    From the above code, you can see a web route in its simplest form. Firstly, we’re creating a get request so when someone visits example.com/ they’re asking to get the information for the page, they’ll then see the text “Hello World” which is being returned from our closure function.

    There any many other route methods which help us deal with web and API requests. These include the following…

    Route::get($uri, $callback);Route::post($uri, $callback);Route::put($uri, $callback);Route::patch($uri, $callback);Route::delete($uri, $callback);Route::options($uri, $callback);List of all route form method

    A lot of our requests will be more complex and we’ll want to separate the logic from our routes file. This can be done through controllers, if we wanted to move the above code from closure to a controller we will need to create our first controller.

    Head over to app/Http/Controllers and create a file called HelloWorldController.php then add the following code.

    And we’ll edit our web.php as follows

    As you can see, we’ve removed our closure and swapped it out for the HelloWorldController and pointed it to the index method. The method then returns the same ‘Hello World’ as before, but now the logic has been separated. As your code becomes more complex, it makes sense to separate logic from one another.

    Blade Templating

    This brings us over to Blade templating which is a template language for our frontend code. Blade templates are just as expressive as the rest of the Laravel framework and make frontend development a joy.

    Hello, {{ $name }}

    Blade templating in it’s simplest form

    For our next example, we’ll create a new dynamic route. It’s dynamic because it will accept user input and output it as HTML.

    Let’s start by updating our current route to accept user

    In our index method of HelloWorldController.php let’s update to accept our name input and return the output.

    public function index($name){ return 'Hello ' . $name;}

    Now when you head to example.com/welcome/Michael you’ll see the text “Hello Michael”, but we still haven’t use Blade templating.

    Let’s update our index method to return a blade template

    public function index($name){ return view('welcome', ['name' => $name]);}

    Head over to resources/views and open welcome.blade.php. You’ll see there’s already code in this file since it’s Laravel’s default. Go ahead and delete everything inside and add the code from below.

    Hello {{ name }}

    Now when you visit example.com/welcome/Michael you’ll see a similar result to before, but now we can add as much HTML code as we like and we can also add CSS and JavaScript to the mix as well. You can also create templates for specific pages much more.

    Eloquent and the Query Builder

    If you need to interact with a database, you can do this with Eloquent.

    $user = new User();$user->username = 'awesome_user';$user->password = 'shh, this is a secret';$user->save();Creating a new user and saving details to the database

    Or maybe you like to create your own database queries.

    DB::insert('INSERT INTO users (username, password) VALUES ("awesome_user", "shh, this is a secret")');// or using the query builderDB::table('users')->insert([ 'username' => 'awesome_user', 'password' => 'shh, this is a secret']);Create raw queries or the query builder

    As with any raw queries, you must always be careful with user input and the potential for SQL injection vulnerabilities.

    $username = $request->input('username');$password = $request->input('password');// Not okay - NEVER DO THIS!!!DB::insert("INSERT INTO users (username, password) VALUES ($username, $password)");// Escaping user input - DO THIS!!!DB::insert('INSERT INTO users (username, password) VALUES ?, ?', [$username, $password]);Unsafe SQL queries compared to safe SQL queriesWhat are Tests?

    Tests are apart of every programming language. PHPUnit is the most popular package for testing in PHP, but there is also Codeception, PEST, Dusk, Behat and many more.

    There are also different types of tests, the most popular are:

    • Unit testing tests a specific chunk of code.
    • Behaviour-driven describes what a user should expect in a much more readable and business-friendly way.
    • Frontend testing where you test how your site should behave in a web browser.

    Laravel developers mostly use PHPUnit for backend unit testing and Dusk for frontend tests. We will be covering both and it will be up to you whether you want to carry these tests out within your projects, but it is highly recommended you do.

    What is TDD?

    TDD stands for Test Driven Development and it’s the practice of creating tests BEFORE you create anything else. The practice will look a little something like this…

    Create a test for a specific task
    Run the test
    Test fails
    The failed test will say why it failed
    Write code for that error
    Run test which may pass or fail
    If the test fails, write more logic

    When the test eventually passes, you can move onto another test and repeat the process. It may seem pointless and it may seem tedious, but once you get the hang of it, you’ll see the benefits.

    Why should I test my code?

    Say your senior developer comes up to you and requests a change in logic. Your code has no tests and there are no specifications to how it should currently work. You try your hardest to understand the logic and you think you know what’s going on.

    You try to implement the change and introduce new bugs into the code. You’re unaware of said bugs because there are currently no tests implemented and as far as you can tell, everything works as expected.

    You create a Pull request and your senior tests your code. They find bugs which you weren’t aware of and ask you to fix them. You take a look, fix the bugs they found and create a new PR. He reviews it again and finds the bugs are fixed, but unfortunately, they find another bug. You fix that bug and cross your fingers everything works as expected.

    With this new PR, your senior reviews the code and approves your work. It’s taken a couple of back and forths which could have been easily avoided if you had tests running.

    Now we have the exact same situation, but with a test suite. After receiving the request, you look at the tests and run them to ensure everything is working in its current state (which it should be).

    All tests come back green and you begin to update the tests for your new logic. Once you update the tests, you run them and make sure it should fail since nothing has been implemented yet. It comes back red and tells you why it failed. You write some code and the test fails again but gives you a reason.

    You follow these steps until your logic is complete and all tests pass. You push your code and create a PR. An automated test suite picks up on your PR and runs its automated tests. Everything comes back green again and your senior gives it one last review to ensure it’s up to coding standards.

    Everything looks good and your senior is happy to merge and eventually pushes it to production.

    The second scenario had a lot less friction between you and the senior and they are now a lot happier with your work.

    Closing thoughts

    I hope this gave you more insight into the Laravel framework and the TDD methodology we will be using from now on in this course. This episode is open to the public, but if you want to see future posts for this course, you will need to sign up using the form below.

    If you have any questions, then you can use the comments section below or hit me up on Twitter or Facebook.

    #from-zero-to-hero #laravel #tutorial

    https://michaelbrooks.co.uk/laravel-from-zero-to-hero-00-an-introduction-to-laravel/