Laravel 8 Tutorial - Model

In this tutorial, we will learn about models in Laravel.

A model is a class that represents the logical structure and relationship of an underlying data table.

In Laravel, each database table has a corresponding model that allows us to interact with that table.

Models provide a way to retrieve, insert, and update information in your data table.

In our previous tutorial, we created a posts table in the database.

Inside the table, there are some posts.

Now, let's create a model for the Posts table.

Go to the command prompt and run the following command:


php artisan make:model Post

The naming convention for models is that the model name should be in singular form, with no spacing between words, and capitalized.

In this case, the model name is "Post".

The model has been created inside the app\Models directory.

Let's take a look at the Post model.

Go to the app\Models directory and open the Post model file.

Inside the Post model class, specify the table name by typing the following code:


protected $table = 'posts';

Now, let's see how we can use this model inside a controller.

Switch to the PostController and import the Post model first.

Add the following code before the class:


use App\Models\Post;

Now we can use the Post model.

Let's create a method for fetching all the posts from the posts table.


public function getAllPostsUsingModel()
{
$posts = Post::all();
retrun $posts;
}

Now, create a route for this method.

Go to the web.php file and type the following code:


Route::get('/all-posts','[PostController::class, 'getAllPostsUsingModel');

Save the file and go to the browser.

Type the following URL: /all-posts.

Now, you can see all the posts.

So, in this way, you can create and use models in Laravel 8.