Laravel 9: Overview for newcomers
Tags: webdev, beginners, laravel, php
Published: 2022-06-01 16:21:31

Laravel is the most famous and wide-use framework of PHP. 

People say it's easy to use and very enjoyable. However it may feel a bit overwhelming at first, Especially if you're coming from frameworks like Express and Django, "Illuminate" ? "Migrations" ? Oh my!

This article is not a tutorial per se but it aims to give you an introductory of what is all about to familiarize yourself more. I suggest you read the official documentation as well, 

Let's get started!

## Table of contents
- [So what is Laravel ?](#so-what-is-laravel)
- [Setting up Laravel](#setting-up-laravel)
- [Overview of Laravel main components](#overview-of-laravel-main-components)
- [Routing](#routing)
- [Controllers](#controllers)
- [Blade template engine](#blade-template-engine)
- [Working with forms](#working-with-forms)
- [Working with databases](#working-with-databases)
  * [Connecting to database](#connecting-to-database)
  * [migrations](#migrations)
  * [models](#models)
  * [Seeders and factories](#seeders-and-factories)
- [Conclusion](#conclusion)

## So what is Laravel ? 

Before proceeding I want to make something clear, When I started out learning Laravel, I thought it's a backend framework, But in reality Laravel is a fullstack (can be integrated with Front-end frameworks), battery-included or an "out of the box" PHP framework. 

"Out of the box" means built-in features that needs little to no setup to work with. If we take authentication for example, Other frameworks may have you build the whole system from scratch, Where Laravel already got your back. This is a huge plus towards development experience.

That's why when you install Laravel you'll find a structure of folders (similar to Ruby on Rails) instead of a blank folder.

## Setting up Laravel

**Prerequisite**

- PHP 8.0
- OOP PHP principles 
- Basic knowledge of [MVC model](https://en.wikipedia.org/wiki/Model–view–controller)
- composer (optional)


**Installing Laravel**

There are many [options to install Laravel](https://laravel.com/docs/9.x/installation)

The simplest one is to use composer so make sure it's installed on your system.

`composer create-project laravel/laravel project-name`

after installation is complete you can open it like so
`cd project-name`
`php artisan serve // open in localhost:8000`

**what is artisan ?**
artisan is a command line tool included with Laravel, It provides a number of commands that can help you while you build your application easily.

## Overview of Laravel main components  

## Routing
To define a route for your website open `web.php` from the `routes` folder

You use to `Route` class to define a route with a static method (get, post, put, delete)

the static methods accept a URL and a closure (callback function)

```php
use Illuminate\Support\Facades\Route;

Route::get('/', function () {

return 'Hello World';

});
```

You can use URL parameters as well
```php
use Illuminate\Support\Facades\Route;

Route::get('/books/{book}', function ($book) {

return 'The book is' . $book;

});

```

Keep in mind that function parameters names don't matter, But their order do!

```php

use Illuminate\Support\Facades\Route;

Route::get('/books/{book}/{comments}', function ($comments, $book) {

return 'Im not the comments iam the book!' . $comments;

});
```

**passing a view**

 your views can be either `html` or `blade` template engine, We'll talk about `blade` at later time

```php
use Illuminate\Support\Facades\Route;

Route::get('/', function () {

return view('greeting');

});
```

If you're route only returns a view you can use the `view` method

```php

Route::view('/', 'greetings');
```

**passing data to view**

sometimes you may want to render a dynamic data, You can pass your data as the second argument of view method or using the `with` helper

```php

use Illuminate\Http\Request;

Route::get('/user', function (Request $request) {

$user = ['name' => 'joe', 'email' => 'joe@email.com'];

return view('user', ['user' => $user]);

// or
return view('user')->with(['user' => $user]);

});

```

and use it in your view (this is a blade template)
```html

<body>
	<h1>user name is: {{$user->name}}</h1>
	<p>user email is: {{$user->email}}</p>

</body>
```

However putting all the logic inside the routes file will do no good. It's time to talk about controllers

## Controllers  

Controllers are the means to organize request handling logic 

To put it simply, a controller is just a class that has methods that you define which either can be assigned to handle a specific request 

You will find the controllers inside `App\Http\Controllers\`

To create a controller you use an artisan command for that

So open the terminal and type: `php artisan make:controller BookController`

The controller is now in: `App\Http\Controllers\BookController`

Now you're ready to define your methods 

```php
public function index()

{
return view('books');
}
```

Now you're ready to use it inside your route file 

instead of writing the callback function you put your controller inside brackets 

the second element inside the brackets is your controller's method name

Don't forget to import it first!
```php
use App\Http\Controllers\BookController;

Route::get('/books', [BookController::class, 'index']);
```


## Blade template engine
Blade is a template engine that is included with Laravel. 

All Blade templates gets compiled into plain PHP code.

Blade files use the `.blade.php` file extension and are usually inside `resources/views` directory.

**rendering data**
If you've read above about how to pass data to your views you've seen that Blade uses double curly braces to render PHP variables 

```html
<h1>user name is: {{$user->name}}</h1>
<p>user email is: {{$user->email}}</p>
```

**Blade directives**

Blade comes in with handy, straightforward syntax called [Blade directives](https://laravel.com/docs/9.x/blade#blade-directives) to work with PHP control structures such as conditions and loops

- **conditions**
```html
@if(1 + 1 == 2) {
	<h1>yes, 1 + 1 equals 2!</h1>
} else {
	<h1>no, 1 + 1 equals 10!</h1>
}
```

- **loops**

```html
@for ($i = 0; $i < 10; $i++)

The current value is {{ $i }}

@endfor

@while (true)

<p>I'm looping forever.</p>

@endwhile
```

Looping through an array
```html
@foreach ($users as $user)

<p>This is user {{ $user->id }}</p>

@endforeach

@forelse ($users as $user)

<li>{{ $user->name }}</li>

@empty

<p>No users</p>

@endforelse

```

There are many other useful directives such as displaying data if user is authenticated or not, including or re-using other template files... I suggest you check them out

## Working with forms

**CSRF protection**
If you ever worked with forms with PHP, You may have heard the saying "Never trust the user's input". Laravel provides an easy way to prevent CSRF requests

Use the @csrf directive in every form, And you're done! 
```html
<form action="" method="POST">
	@csrf

	<input name="name" type="text" />
	<input name="email" type="email" />
	<input name="password" type="password" />

	<input type="submit" />
</form>
```

**Handling form requests**

Your form actions should point to a route that is defined in `web.php` (see Routing section), that preferably pass the request to a controller (see Controllers section)

Laravel has a Request class to interact with the HTTP request

- **retrieving the inputs**
```php
class UserController extends Controller
{

public function store(Request $request)

{
	// all inputs values as an array
	$inputs = $request->all();

	// specific input value
	$name = $request->input('name');


}

}
```

## Working with databases

### Connecting to database
Connecting to your database is easy! go to `.env` file in the root directory and fill in the fields 

By default laravel uses mysql

```env
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=my_database
DB_USERNAME=root
DB_PASSWORD=
```

And you're done!.

the whole interaction with the database will be through "migrations" and "model"

### migrations

To put it simply, migrations is just a way to create a table and define the schema (columns) of your table, plus a version control system for these columns.

To create a migration type in CLI
`php artisan make:migration create-posts-table`

Inside the `up` function define the properties (the columns):

[Here are all the available column types](https://laravel.com/docs/9.x/migrations#available-column-types)

```php
public function up()

{

	Schema::create('posts', function (Blueprint $table) {

		$table->id();

		$table->string('title');

		$table->longText('body');

		$table->timestamps();

});

}
```

### models

For every table, there is a corresponding model. This model is your middleman to your table. Models are used to retrieve, insert, and delete the rows of the table.

to create a model type in CLI
`php artisan make:model Post`

Keep in mind that Laravel is intuitive about the names, so a `Post` model means there is a `posts` table.

If you doubt that Laravel will get the table name right (like what's the plural of octopus ?! 😂). You can explicitly define the name with the protected table property

```php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Post extends Model

{

protected $table = 'my_posts';

}
```

usually you won't add anything to the model file unless you need to change some [configuration](https://laravel.com/docs/9.x/eloquent#eloquent-model-conventions) or add a [relationship](https://laravel.com/docs/9.x/eloquent-relationships) to other models.

You just use it right away! 

```php

use App\Models\Post

$posts = Post::all(); // get all records

$post = Post::where('title', 'Hello World')->first();


```

### Seeders and factories

In the development stage you may want to have a sample of data in the table to work with. However it would be cumbersome to insert the data manually ,That's where factories and seeders come in.

seeders are just functions that populate the data when executed. There is a default file that comes with the installation, `DBSeeder.php` in `database/seeders` directory: Normally you'll only need that one. 

```php

class DatabaseSeeder extends Seeder {

	public function run()

	{
		Post::factory()
			->count(20)
			->create();
	}

}
```

Factories are the way you generate a fake data records, Laravel uses the [`faker`](https://fakerphp.github.io) package for that.

To create a factory type in CLI
`php artisan make:factory PostFactory`

```php
class PostFactory extends Factory

{

	public function definition()

	{

		return [

			'title' => $this->faker->sentence(),

			'body' => $this->faker->text()
		];

	}

}
```

To generate the data records type in CLI
`php artisan db:seed`

Now go to your database and you'll find the table have 10 rows.

## Conclusion 
I hope this article made you more familiar with Laravel, even for a bit. support me by reacting to this post. It means a lot to me!

If you have any question, or want to point out to something feel free to leave a comment.