README.md 32.3 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
# How To Build a (Basic) TODO list with Laravel

A tutorial by Dillenn TERUMALAI

---

## Server Requirements

- Composer - Depedency manager for PHP
- PHP >= 7.2.0
- BCMath PHP Extension
- Ctype PHP Extension
- JSON PHP Extension
- Mbstring PHP Extension
- OpenSSL PHP Extension
- PDO PHP Extension
- Tokenizer PHP Extension
- XML PHP Extension

## Installing Laravel

First, we need to install Laravel by using Composer:

```php
composer create-project --prefer-dist laravel/laravel awesome-laravel
```

Once the installation is done, you can directly test your application if PHP is installed locally by typing:

```php
php artisan serve
```

You can access the server at `http://localhost:8000`

## Laravel's Directory Structure

Your directory should contain multiple folders and files. Here is a short description for each.

- **app** contains your models, controllers and most of your future code
- **bootstrap** contains the files that the Laravel framework uses to boot every time it runs
- **config** contains all the configuration files
- **database** contains your migrations and seeders
- **public** is the directory the server points to when it's serving the website
- **resources** contains non-PHP files that are needed, views, language files, sass or JS files
- **routes** contains all the route definitions
- **storage** contains the caches, logs, and compiled system files
- **test** contains unit and integration tests
- **vendor** contains all the composer dependencies
- *env* and *env.example* are files that dictate the environment variables
- *artisan* is the file that allows your tu run Artisan commands from the command line
- *.gitignore* and *.gitattributes* are Git config files
- *composer.json* and *composer.lock* are the config files for Composer
- *phpunit.xml* is a configuration file for PHPUnit
- *server.php* is a backup server that tries to allow less-capable servers to still preview the Laravel application

## Working with Docker - Vessel

Vessel is just a small set of files that sets up a local Docker-based dev environment per project. There is nothing to install globally, except Docker itself.

To install Vessel, simply type this command inside your Laravel project:

```php
composer require shipping-docker/vessel
```

Finally, publish the `command` and Docker files:
```bash
php artisan vendor:publish --provider="Vessel\VesselServiceProvider"
```

### Getting started

```bash
# Run this once to initialize project
# Must run with "bash" until initialized
bash vessel init

# Start vessel
./vessel start

# Stop vessel
./vessel stop
```

Once initialized, four containers will be running:

- PHP 7.3
- MySQL 5.7
- Redis
- NodeJS

## Routing and Controllers

### Router

In Laravel, you define your "web" routes in `routes/web.php` and your "API" routes in `routes/api.php`. In this tutorial, we will focus only on the routes in `routes/web.php`.

Let's create our first route. Modify `routes/web.php` closure to this:

```php
Route::get('/', function () {
    return 'Awesome Laravel!';
});
```

Then hit `http://localhost`!

You should see the message "Awesome Laravel!".

If we look at the structure of the route:

1) The "verb" is **GET**
2) The path defined is root **"/"**
3) The closure return the string **Awesome Laravel!**

We can use any kind of "verb", for example:

```php
Route::post('/', function () {
    return 'This is a post request';
});
```

We can also match any pattern, for example:

```php
Route::get('home', function () {
    return 'This is my Home';
});
```

### Controller

The common option when defining a route is to pass a controller name and method as a string in place of the closure.

```php
Route::get('/', 'HomeController@index');
```

Of course, this controller doesn't exist yet, so type the following to create it:

```bash
php artisan make:controller HomeController
```

This will create `App/Http/HomeController.php`. Open the file and add the `index` function:

```php
public function index()
{
    return 'Hello World!';
}
```

You should see **"Hello World!"** @`http://localhost`.

Nice right? And this is only the beginning!

## Blade Templating

Laravel offers a custom templating engine called Blade. Let's have a look!

Open `resources/views/welcome.blade.php`. First, notice the extension **blade.php**, it is important to always use this extension for any template we will create.

Inside `welcome.blade.php`, you can already see some **"directives"** prefixed with an `@`.

```html
@if (Route::has('login'))
    <div class="top-right links">
        @auth
            <a href="{{ url('/home') }}">Home</a>
        @else
            <a href="{{ route('login') }}">Login</a>
            @if (Route::has('register'))
                <a href="{{ route('register') }}">Register</a>
            @endif
        @endauth
    </div>
@endif
```

Blade's `@if ($condition)` compiles to <?php if ($condition)> (don't forget to always end your `@if` with an `@endif`). There are a lot of directives such as `@auth`, `@for`, `@foreach` ...

To use <?php echo $string>, simply use double brackets:

```php
{{ 'This is a string' }}
```

## Database

### Migrations

Modern frameworks like Laravel make it easy to define your database structure with code-driven migrations. Every new table, column, index, and key can be defined in code.

To build our **TODO** application, let's start by creating two migration files:

```bash
php artisan make:migration create_categories_table
php artisan make:migration create_todos_table
php artisan make:migration create_tags_table
php artisan make:migration create_tag_todo_table
```

We now have three migration files in `database/migrations`:

- ####-##-##-####_create_categories_table.php
- ####-##-##-####_create_todos_table.php
- ####-##-##-####_create_tags_table.php
- ####-##-##-####_create_tag_todo_table.php

Let's modify the content of these files:

```php
# create_categories_table.php

Schema::create('categories', function (Blueprint $table) {
    $table->bigIncrements('id');
    $table->string('title');
    $table->timestamps();
});
```

```php
# create_todos_table.php

Schema::create('todos', function (Blueprint $table) {
    $table->bigIncrements('id');
    $table->string('task');
    $table->boolean('done')->default(false);
    $table->unsignedBigInteger('category_id')->nullable();
    $table->foreign('category_id')
        ->references('id')->on('categories')
        ->onUpdate('cascade')
        ->onDelete('cascade');
    $table->timestamps();
});
```

```php
# create_tags_table.php

Schema::create('tags', function (Blueprint $table) {
    $table->bigIncrements('id');
    $table->string('title');
    $table->timestamps();
});
```

```php
# create_tag_todo_table.php

Schema::create('tag_todo', function (Blueprint $table) {
    $table->unsignedBigInteger('tag_id');
    $table->foreign('tag_id')
        ->references('id')->on('tags')
        ->onUpdate('cascade')
        ->onDelete('cascade');
    $table->unsignedBigInteger('todo_id');
    $table->foreign('todo_id')
        ->references('id')->on('todos')
        ->onUpdate('cascade')
        ->onDelete('cascade');
});
```

The table `categories` contains:

- **id**
- **title**
- **updated_at**
- **created_at**

The table `todos` contains:

- **id**
- **task**
- **done**
- **category_id** which is foreign key pointing to the table *"categories"* (1:1)
- **updated_at**
- **created_at**

The table `tags` contains:

- **id**
- **title**
- **updated_at**
- **created_at**

The table `tag_todo` (N:N) contains:

- **tag_id** -> *"tags"* -> id
- **todo_id** -> *"todos"* -> id

#### Running the migrations

To run your migration, you need to type:

```bash
./vessel artisan migrate
```

Because we are using docker and each part of our application is in a container, any artisan command that will interact with the cache or the database needs to be called using `./vessel artisan` instead of `php artisan`.

### Models

For this part, we will use Eloquent ORM (Object-relational mapping) which is a database abstraction layer that provides a single interface to interact with mutliple database types.

Let's create our models. As you may expect, we need three models:

- Category
- Todo
- Tag

Let's create them by typing:

```bash
php artisan make:model Category
php artisan make:model Todo
php artisan make:model Tag
```

We now have our three models in `app`.

Let's start with `Category.php`. By default, Model should be named after the singular of the table name and using SnakeCase. It will then guess the name of the table by adding an **'s'** but for **category** it is a bit more complicated. That is why we can manually define the name of the table.

```php
# Category.php

class Category extends Model
{
    protected $table = 'categories';

    public function todos()
    {
        return $this->hasMany('App\Todo');
    }
}
```

Also by default, Eloquent will assume that each table has a primary key columns named `id` and expects `created_at` and `updated_at` columns to exist on your table. Of course, this can be manually defined.

Then let's modify `Todo.php`. Here, we need define relationships with both tables **categories**(1:1) and **tags**(1:N).

```php
# Todo.php

class Todo extends Model
{
    public function category()
    {
        return $this->belongsTo('App\Category');
    }

    public function tags()
    {
        return $this->belongsToMany('App\Tag');
    }
}
```

```php
# Tag.php

class Tag extends Model
{
    public function todos()
    {
        return $this->belongsToMany('App\Todo');
    }
}
```

## Controllers

Now we need to define a controller for our **todos** to handle any kind of request (GET,PATCH,DELETE...)

First let's create the controller using the `--reource` option that will automatically create a method for each of the available resource operations (CRUD).

```bash
php artisan make:controller TodoController --resource
```

The structure of the file is the following:

```php
class TodoController extends Controller
{
    public function index()
    {
        //
    }
    public function create()
    {
        //
    }
    public function store(Request $request)
    {
        //
    }
    public function show($id)
    {
        //
    }
    public function edit($id)
    {
        //
    }
    public function update(Request $request, $id)
    {
        //
    }
    public function destroy($id)
    {
        //
    }
}
```

Now, we need to fill these functions. To do so, we will need to use Eloquent ORM to work with our `Todo.php` model.

Let's start with `index()`:

Here, the function is supposed to return all the rows of the table **todos**. We can write this by simply typing:

```php
public function index()
{
    return Todo::all();
}
```

Don't forget to add `use App\Todo;` at the beginning of the file to be able to directly call `Todo` model.

Let's check the result, but before we need to setup the routes and by using a resourceful route to the controller, it's really easy. In your `routes/web.php` file, just add:

```php
Route::resource('todos', 'TodoController');
```

We can check that our routes have been properly set up by typing:

```bash
php artisan route:list
```

And we can see that we have all the needed routes. Now, let's check in a browser what happens if we go to `http://localhost/todos`.

We see nothing, but this is completely normal as our table doesn't contain any data. So let's add manually some data by using any MySQL application (I use Sequel Pro on MacOS).

If we hit `http://localhost/todos`, we can see the added row(s). Nice!

What if we go to `http://localhost/todos/1`, let's configure the function `show($id)` before:

```php
public function show($id)
{
    return Todo::find($id);
}
```

We can see the specific **todo** with the corresponding **id**.

As you can see, Eloquent is really easy to use. But what about relationships? Let's add two categories (*Home*, *Work*) and five tags (*Groceries*, *Admin*, *Family*, *Development*, *Holidays*) with Sequel Pro. Let's modify the **category_id** to match `1` or `2`. And finally, in the table **tag_todo**, let's create 4 rows (`(2,1)`, `(4,1)`, `(3,2)`, `(5,2)`).

But if we hit `http://localhost/todos`, we see the category_id but that is not convenient at all. So, let's modify our `index()` function:

```php
public function index()
{
    return Todo::with(['category', 'tags'])->get();
}

public function show($id)
{
    return Todo::with(['category', 'tags'])->find($id);
}
```

This returns the category and all the tags linked to each todo, awesome right?

Let's define our functions to:

- create a **todo** (we need the *task*, the *category_id* and the *tag_id*'s) -> `store(Request $request)`
- update a **todo** (we need the *id*, from *undone* to *done* or the opposite) -> `update(Request $request, $id)`
- delete a **todo** (we need the *id*) -> `destroy($id)``

```php
public function store(Request $request)
{
    $category = \App\Category::find($request->category); //We retrieve the row of the category
    $todo = new Todo;                                    //We create a new model of Todo
    $todo->task = $request->task;                        //We set it's task field to the request's task field
    $todo->category()->associate($category);             //We associate our Todo with the category
    $todo->save();                                       //We save it in the Database
    $todo->tags()->attach($request->tags);               //We create links between our Todo and tags
    return $todo;
}

public function update(Request $request, $id)
{
    $todo = Todo::find($id);    //We retrieve the row of the todo
    $todo->done = !$todo->done; //We switch its status
    $todo->save();              //We update the row
    return $todo;
}

public function destroy($id)
{
    return Todo::destroy($id); //We destroy our row by using the id
}
```

As you can see, Eloquent allow easy-to-read code and has already all the functions that we need.

By default, Laravel automatically generates a CSRF "token" for each active user session managed by the application. This token is used to verify that the authenticated user is the one actually making the requests to the application.

The `VerifyCsrfToken` **middleware**, which is included in the web middleware group, will automatically verify that the token in the request input matches the token stored in the session.

So we need to specify that we want to exclude URIs From CSRF Protection. To do so, open `App\Http\Middleware\VerifyCsrfToken` and modify the content:

```php
protected $except = [
    'http://localhost/*'
];
```

Now, we can use a REST client (Insomnia or Postman) to create a new todo. Don't forget to set your headers properly:

- **Accept**: application/json
- **Content-Type**: application/json

And let's send the following as our request (`POST http://localhost/todos`):

```json
{
	"task": "Buy gifts for the kids",
	"category": 1,
	"tags": [1,3]
}
```

The server send back the created **todo** and we can check in our database (with Sequel) that the row and its relationships has been properly added.

What about `update(Request $request, $id)` and `destroy($id)`. Let's test those with our REST client:

- `PUT http://localhost/todos/1` -> the column **done** changed to 1 (`true`) for the first row
- `DELETE http://localhost/todos/2` -> the second row has been deleted from the table **todos**

It works!

## Views

Now that we set up the server, let's build our view. Views (or templates) are files that describe what some particular output should look like. Of course, we are going to use **Blade templates**.

Let's start by creating our view. Create a file called `todos.blade.php` inside `resources/views`.

Paste this code:

```html
<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <title>Laravel</title>

        <!-- Fonts -->
        <link href="https://fonts.googleapis.com/css?family=Nunito:200,600" rel="stylesheet">
        <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

        <!-- Styles -->
        <style>
            html, body {
                background-color: #fff;
                color: #636b6f;
                font-family: 'Nunito', sans-serif;
                font-weight: 200;
                height: 100vh;
                margin: 0;
            }

            .full-height {
                height: 100vh;
            }

            .flex-center {
                align-items: center;
                display: flex;
                justify-content: center;
            }

            .position-ref {
                position: relative;
            }

            .top-right {
                position: absolute;
                right: 10px;
                top: 18px;
            }

            .content {
                text-align: center;
                width: 50%;
            }

            .title {
                font-size: 84px;
            }

            .m-b-md {
                margin-bottom: 30px;
            }
        </style>
    </head>
    <body>
        <div class="flex-center position-ref full-height">
            @if (Route::has('login'))
                <div class="top-right links">
                    @auth
                        <a href="{{ url('/home') }}">Home</a>
                    @else
                        <a href="{{ route('login') }}">Login</a>

                        @if (Route::has('register'))
                            <a href="{{ route('register') }}">Register</a>
                        @endif
                    @endauth
                </div>
            @endif

            <div class="content">
                <div class="title m-b-md">
                    {{ "My TODO's" }}
                </div>

                <div class="container-fluid">

                    <!-- Our list separated in 3 parts: creation form, categories and todos -->
                    <ul class="list-group">

                        <!-- CREATION FORM -->
                        <li class="list-group-item">
                            <form action="http://localhost/todos" method="POST">
                                <div class="form-row">
                                    <div class="col">
                                        <input type="text" class="form-control" id="task" name="task" placeholder="My new todo...">
                                    </div>
                                </div>
                                <div class="form-row pt-2">
                                    <div class="col">
                                        <select class="custom-select" id="category" name="category">
                                            @foreach($categories as $category)
                                                <option value="{{ $category->id }}">{{ $category->title }}</option>
                                            @endforeach
                                        </select>
                                    </div>
                                    <div class="col">
                                        <select class="custom-select" id="tags" name="tags[]" multiple>
                                            @foreach($tags as $tag)
                                                <option value="{{ $tag->id }}">{{ $tag->title }}</option>
                                            @endforeach
                                        </select>
                                    </div>
                                </div>
                                <div class="form-row pt-2">
                                    <div class="col">
                                        <button type="submit" class="btn btn-outline-dark btn-block">Create</button>
                                    </div>
                                </div>
                            </form>
                        </li>

                        <!-- CATEGORIES LABELS -->
                        @foreach($categories as $category)
                            <li class="list-group-item d-flex justify-content-between align-items-center active">
                                {{ $category->title }}
                            </li>

                            <!-- TODOS FILTERED BY USING THE CATEGORY ID -->
                            @foreach($todos->where('category_id', $category->id) as $todo)
                                <li class="list-group-item d-flex justify-content-between align-items-center">
                                    <div class="d-flex align-items-center">
                                        {{ $todo->task }}
                                        @foreach($todo->tags as $tag)
                                            <span class="badge badge-info ml-2">{{ $tag->title }}</span>
                                        @endforeach
                                    </div>
                                    <div class="row">

                                        <!-- UPDATE FORM -->
                                        <form action="{{ 'http://localhost/todos/'.$todo->id }}" method="POST">
                                            @method('PUT')
                                            <button type="submit" class="btn {{ $todo->done ? 'btn-success' : 'btn-outline-success' }}">{{ $todo->done ? 'done' : 'undone' }}</button>
                                        </form>

                                        <!-- DELETE FORM -->
                                        <form action="{{ 'http://localhost/todos/'.$todo->id }}" method="POST">
                                            @method('DELETE')
                                            <button type="submit" class="btn btn-danger ml-2">&times;</button>
                                        </form>

                                    </div>
                                </li>
                            @endforeach

                        @endforeach
                    </ul>
                </div>
            </div>
        </div>
    </body>
</html>
```

We will get back to it, but before, let's configure our `TodoController.php` to properly use the view and inject the data.

```php
public function index()
{
    $categories = \App\Category::all();     //We retrieve all the rows from categories
    $tags = \App\Tag::all();                //We retrieve all the rows from tags
    $todos = Todo::with(['category', 'tags'])->orderBy('id', 'desc')->get();    //We retrieve all the rows from todos with relationships
    return view('todos')->with(compact('categories', 'tags', 'todos'));     //We return the view (todos.blade.php) and we inject the data
}

public function store(Request $request)
{
    ...
    return redirect()->action('TodoController@index'); //We now redirect to the index function
}

public function update(Request $request, $id)
{
    ...
    return redirect()->action('TodoController@index'); //We now redirect to the index function
}

public function destroy(Request $request, $id)
{
    ...
    return redirect()->action('TodoController@index'); //We now redirect to the index function
}
```

That means that afer a `POST`, `PUT` or `DELETE` request, we will get back to our **todos** page.

Let's get back to our view. Our list is divided into three parts:

- TODO creation form
- Categories labels
- TODOs
    - Task
    - TODO update form
    - TODO deletion form

If we go to the `<!-- CATEGORIES LABELS -->` block, we see that we use the directive `@foreach()`to loop through the categories. Then we can just echo (`{{ }}`) the category's **title**.

Then for the `<!-- TODOS FILTERED BY USING THE CATEGORY ID -->` block, we are calling `$todos` but we are filtering the todos by using the `category_id`, nice no?

Finally we have three forms:

```html
<!-- CREATION FORM -->
<form action="http://localhost/todos" method="POST">
    <div class="form-row">
        <div class="col">
            <input type="text" class="form-control" id="task" name="task" placeholder="My new todo...">
        </div>
    </div>
    <div class="form-row pt-2">
        <div class="col">
            <select class="custom-select" id="category" name="category">
                @foreach($categories as $category)
                    <option value="{{ $category->id }}">{{ $category->title }}</option>
                @endforeach
            </select>
        </div>
        <div class="col">
            <select class="custom-select" id="tags" name="tags[]" multiple>
                @foreach($tags as $tag)
                    <option value="{{ $tag->id }}">{{ $tag->title }}</option>
                @endforeach
            </select>
        </div>
    </div>
    <div class="form-row pt-2">
        <div class="col">
            <button type="submit" class="btn btn-outline-dark btn-block">Create</button>
        </div>
    </div>
</form>
```

So a `POST` request to `http://localhost/todos`. Then one `<input>` field and two `<select>` fields. We see again the `@foreach()` directive to populate the options of the two `<select>` fields.

```html
<!-- UPDATE FORM -->
<form action="{{ 'http://localhost/todos/'.$todo->id }}" method="POST">
    @method('PUT')
    <button type="submit" class="btn {{ $todo->done ? 'btn-success' : 'btn-outline-success' }}">{{ $todo->done ? 'done' : 'undone' }}</button>
</form>
```

A `PUT` request to `http://localhost/todos/${id}` (thanks to the direct `@method('PUT')`). Then a single submit button that we customize based on the **done** value of our todo (we previsouly wrote a foreach loop).

```html
<!-- DELETE FORM -->
<form action="{{ 'http://localhost/todos/'.$todo->id }}" method="POST">
    @method('DELETE')
    <button type="submit" class="btn btn-danger ml-2">&times;</button>
</form>
```

A `DELETE` request to `http://localhost/todos/${id}` (thanks to the direct `@method('DELETE')`). Then a single submit button to send the request.

Let's hit `http://localhost/todos`, to check our web application. Everything should work properly ;).

## Authentication (Optional)

What if we could control the access to `/todos` page with some authentication protocol. That sounds complicated right? Not for Laravel!

First, let's add the php package with composer and then use the built-in command of artisan to implement the authentication:

```bash
composer require laravel/ui --dev
php artisan ui vue --auth
```

The first command installs the package and the second command create all of our views and add the routes for **auth** to `web.php`.

If we go to `resources/views`, we see two new folders called `layouts` and `auth`, and a new file called `home.blade.php`.

Let's make a quick change to `layouts/app.blade.php` to use Bootstrap CDN as we will not use **NPM** in our tutorial.

```html
<!-- Scripts -->
<script src="{{ asset('js/app.js') }}" defer></script>

<!-- Fonts -->
<link rel="dns-prefetch" href="//fonts.gstatic.com">
<link href="https://fonts.googleapis.com/css?family=Nunito" rel="stylesheet">

<!-- Styles -->
<link href="{{ asset('css/app.css') }}" rel="stylesheet">
````

to

```html
<!-- Scripts -->
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>

<!-- Fonts -->
<link rel="dns-prefetch" href="//fonts.gstatic.com">
<link href="https://fonts.googleapis.com/css?family=Nunito" rel="stylesheet">

<!-- Styles -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
```

Then, let's adapt our `todos.blade.php` to use this layout. Replace the content with:

```html
@extends('layouts.app')

@section('content')
    <div class="container-fluid">
        <div class="h1 text-center">
            {{ "My TODO's" }}
        </div>

        <!-- Our list separated in 3 parts: creation form, categories and todos -->
        <ul class="list-group">

            <!-- CREATION FORM -->
            <li class="list-group-item">
                <form action="http://localhost/todos" method="POST">
                    <div class="form-row">
                        <div class="col">
                            <input type="text" class="form-control" id="task" name="task" placeholder="My new todo...">
                        </div>
                    </div>
                    <div class="form-row pt-2">
                        <div class="col">
                            <select class="custom-select" id="category" name="category">
                                @foreach($categories as $category)
                                    <option value="{{ $category->id }}">{{ $category->title }}</option>
                                @endforeach
                            </select>
                        </div>
                        <div class="col">
                            <select class="custom-select" id="tags" name="tags[]" multiple>
                                @foreach($tags as $tag)
                                    <option value="{{ $tag->id }}">{{ $tag->title }}</option>
                                @endforeach
                            </select>
                        </div>
                    </div>
                    <div class="form-row pt-2">
                        <div class="col">
                            <button type="submit" class="btn btn-outline-dark btn-block">Create</button>
                        </div>
                    </div>
                </form>
            </li>

            <!-- CATEGORIES LABELS -->
            @foreach($categories as $category)
                <li class="list-group-item d-flex justify-content-between align-items-center active">
                    {{ $category->title }}
                </li>

                <!-- TODOS FILTERED BY USING THE CATEGORY ID -->
                @foreach($todos->where('category_id', $category->id) as $todo)
                    <li class="list-group-item d-flex justify-content-between align-items-center">
                        <div class="d-flex align-items-center">
                            {{ $todo->task }}
                            @foreach($todo->tags as $tag)
                                <span class="badge badge-info ml-2">{{ $tag->title }}</span>
                            @endforeach
                        </div>
                        <div class="row">

                            <!-- UPDATE FORM -->
                            <form action="{{ 'http://localhost/todos/'.$todo->id }}" method="POST">
                                @method('PUT')
                                <button type="submit" class="btn {{ $todo->done ? 'btn-success' : 'btn-outline-success' }}">{{ $todo->done ? 'done' : 'undone' }}</button>
                            </form>

                            <!-- DELETE FORM -->
                            <form action="{{ 'http://localhost/todos/'.$todo->id }}" method="POST">
                                @method('DELETE')
                                <button type="submit" class="btn btn-danger ml-2">&times;</button>
                            </form>

                        </div>
                    </li>
                @endforeach

            @endforeach
        </ul>
    </div>
@endsection
```

If you type `php artisan route:list`, you can see that a lot of routes has been added which are related to the authentication process (**register**, **login**, **logout** ...). Nice right? You can also see that in the last column `Middleware`, we have a new parameter called `auth`. `auth` is convenient middleware that checks if the user is authenticated and if not, redirect him to the login page. So let's try to go to `http://localhost/home`. We are redirect to the login page. What about our `todos` page? We can still access it, because we didn't add the middleware. Open `routes/web.php` and update our **todos** routes:

```php
Route::resource('todos', 'TodoController')->middleware('auth');
```

Let's try again to access `http://localhost/todos`, you can't. All the resources routes are now accessible only if you are authenticated. 

Create a new user and try again to access `http://localhost/todos`. Now it works. Congratulations, you just set up an authentication system in a few minutes!