How to use models in Laravel

Learn how to use Eloquent models in Laravel with an example, to create powerful web applications.

Using Models in Laravel

Laravel models are used to interact with the associated database table. Models allow you to query for data in your tables, as well as insert new records into the table. Models are typically stored in the app directory.

To create a model, use Artisan's make:model command. For example, to create a model named Post:


php artisan make:model Post

This command will create a Post.php model class in the app directory. Models are created with several methods and properties already included. You can use these methods and properties to query and manipulate the associated database table.

To define relationships between models, the hasMany() and belongsTo() methods can be used. For example, to define a one-to-many relationship between a Post model and a Comment model:


class Post extends Model
{
    public function comments()
    {
        return $this->hasMany('AppComment');
    }
}

class Comment extends Model
{
    public function post()
    {
        return $this->belongsTo('AppPost');
    }
}

The hasMany() and belongsTo() methods allow you to retrieve associated records from the database. For example, to retrieve all comments for a post:


$post = Post::find(1);

$comments = $post->comments;

Models can also be used to insert records into the database. For example, to create a new comment:


$comment = new Comment();
$comment->content = 'This is a comment.';
$comment->post_id = 1;
$comment->save();

Models provide powerful ways to query and manipulate data in Laravel. By using models, you can greatly reduce the amount of code needed to interact with the database.

Answers (0)