DEV Community

Cover image for Laravel 9: Overview for newcomers
m0nm
m0nm

Posted on

Laravel 9: Overview for newcomers

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 ?

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
  • composer (optional)

Installing Laravel

There are many options to install Laravel

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)

use Illuminate\Support\Facades\Route;

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

return 'Hello World';

});
Enter fullscreen mode Exit fullscreen mode

You can use URL parameters as well

use Illuminate\Support\Facades\Route;

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

return 'The book is' . $book;

});

Enter fullscreen mode Exit fullscreen mode

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


use Illuminate\Support\Facades\Route;

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

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

});
Enter fullscreen mode Exit fullscreen mode

passing a view

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

use Illuminate\Support\Facades\Route;

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

return view('greeting');

});
Enter fullscreen mode Exit fullscreen mode

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


Route::view('/', 'greetings');
Enter fullscreen mode Exit fullscreen mode

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


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]);

});

Enter fullscreen mode Exit fullscreen mode

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


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

</body>
Enter fullscreen mode Exit fullscreen mode

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

public function index()

{
return view('books');
}
Enter fullscreen mode Exit fullscreen mode

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!

use App\Http\Controllers\BookController;

Route::get('/books', [BookController::class, 'index']);
Enter fullscreen mode Exit fullscreen mode

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

<h1>user name is: {{$user->name}}</h1>
<p>user email is: {{$user->email}}</p>
Enter fullscreen mode Exit fullscreen mode

Blade directives

Blade comes in with handy, straightforward syntax called Blade directives to work with PHP control structures such as conditions and loops

  • conditions
@if(1 + 1 == 2) {
    <h1>yes, 1 + 1 equals 2!</h1>
} else {
    <h1>no, 1 + 1 equals 10!</h1>
}
Enter fullscreen mode Exit fullscreen mode
  • loops
@for ($i = 0; $i < 10; $i++)

The current value is {{ $i }}

@endfor

@while (true)

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

@endwhile
Enter fullscreen mode Exit fullscreen mode

Looping through an array

@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

Enter fullscreen mode Exit fullscreen mode

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!

<form action="" method="POST">
    @csrf

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

    <input type="submit" />
</form>
Enter fullscreen mode Exit fullscreen mode

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
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');


}

}
Enter fullscreen mode Exit fullscreen mode

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

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=my_database
DB_USERNAME=root
DB_PASSWORD=
Enter fullscreen mode Exit fullscreen mode

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

public function up()

{

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

        $table->id();

        $table->string('title');

        $table->longText('body');

        $table->timestamps();

});

}
Enter fullscreen mode Exit fullscreen mode

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


namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Post extends Model

{

protected $table = 'my_posts';

}
Enter fullscreen mode Exit fullscreen mode

usually you won't add anything to the model file unless you need to change some configuration or add a relationship to other models.

You just use it right away!


use App\Models\Post

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

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


Enter fullscreen mode Exit fullscreen mode

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.


class DatabaseSeeder extends Seeder {

    public function run()

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

}
Enter fullscreen mode Exit fullscreen mode

Factories are the way you generate a fake data records, Laravel uses the faker package for that.

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

class PostFactory extends Factory

{

    public function definition()

    {

        return [

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

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

    }

}
Enter fullscreen mode Exit fullscreen mode

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.

Top comments (1)

Collapse
 
soulsbane profile image
Paul Crane

This was a great introduction to Laravel. Simple and to the point. Great job!