1. 程式人生 > >How To Use A Laravel Model

How To Use A Laravel Model

A Laravel Model makes it very easy to store, read (retrieve), update and delete (CRUD) a resource in a Laravel application. In this post, I am going to show you how to use a laravel model to manage blog posts. I touched on this in my previous post when I talked about using laravel resource controllers

here. The Eloquent ORM included with Laravel provides a beautiful, simple ActiveRecord implementation for working with your database. Each database table has a corresponding “Model” which is used to interact with that table.

how to use laravel model

In my post on laravel resource controllers, I mentioned that you use resource controllers to manage resources. Often, the resources would be stored in a database. That involves using tables to insert, update, query, delete and other operations that make up CRUD. Using our Post as an example (a blog post like the one you are reading right now), we will learn how to create a model for it.

How To Use a Laravel Model – Example Code

Our Post model will extend Eloquent (that makes it an Eloquent model) – which provides most of the methods we will need to work with resources.

Post.php

12345678 classPostextendsEloquent{protected$table="posts"}

I have explicitly told Eloquent which table to use above even though I didn’t have to. Eloquent will use the lowercase plural version of the class name; in this case – posts for the table name. Awesome right? That is all you need to have a working model in laravel.

Soft Delete In Laravel Model

One great feature that I like is Soft Deletes.

Soft deletes enable you to delete a blog post without actually deleting it from your table; instead, it adds a deleted_at column. Here is how you can add that functionality to your model.

12345678910111213141516 useIlluminate\Database\Eloquent\SoftDeletingTrait;classPostextendsEloquent{useSoftDeletingTrait;protected$table="posts";protected$dates=['deleted_at'];}

Mass Assignment in Laravel Models

When you create a Post, you could pass an array of attributes – title, body, author, tags into the constructor of your laravel model. They will then be inserted into the table through mass assignment. This can be a problem security-wise. Why? Someone could insert anything they want into your database – including sql commands. To avoid such a security risk, Eloquent lets you set a protected attribute called $fillable; here is how we do it in our Post laravel model.

12345678910111213141516171819 useIlluminate\Database\Eloquent\SoftDeletingTrait;classPostextendsEloquent{useSoftDeletingTrait;protected$table="posts";//only allow the following items to be mass-assigned to our modelprotected$fillable=array('title','author','body','tag');protected$dates=['deleted_at'];}

There are more attributes you could set for your model, but for now, let us move on to the next step.

Using Laravel Model Create Method

Once you have defined your laravel model, you can create an instance and set the attributes then save it to the database; creating tables is not necessarily covered in this post – will do so in my next post. It is very easy using migrations. Here is how we use the laravel Model Create method to create new resources in your controller.

BlogPostController.php

1234567891011121314151617181920212223242526272829303132333435363738 classBlogPostControllerextendsBaseController{//this is from my previous post on laravel resource controllerspublicfunctionindex(){}publicfunctioncreate(){}publicfunctionshow($id){}publicfunctionstore(){//get input from a form and create your model then save to db$post=Post::create(array('title'=>Input::get('title'),'author'=>Auth::user()->first,'body'=>Input::get('body'),'tag'=>Input::get('tag')));if($post->save()){returnRedirect::route('posts.index');}}publicfunctionedit($id){}publicfunctionupdate($id){}publicfunctiondestroy($id){}}

Fetching Posts From the Database

After storing your blog posts in a table, you can easily fetch and pass them to the view. Here is how you do that in your controller:

1234567891011121314151617181920 classBlogPostControllerextendsBaseController{//this is from my previous post on laravel resource controllerspublicfunctionindex(){//fetch all posts stored in db (those not deleted).$posts=Post::all();//fetch all including soft deleted posts$posts=Post::withTrashed()->get();//fetch only trashed/deleted posts$posts=Post::onlyTrashed()->get();}}

Restore My Soul

If you accidentally deleted a post, you can easily restore it by using this simple method;

12345678910111213 classBlogPostControllerextendsBaseController{publicfunctionrestorePost($id){Post::withTrashed()->where('id',$id)->restore();}}

How awesome is that huh?

I feel like I should stop here and let you digest what we have talked about so far. Next post will show you how to use laravel migrations to create tables – pretty easy stuff. I hope you will join me as I do that probably tomorrow. You can learn more about laravel models here.

If you found this post helpful to you, please consider sharing with your friends using the buttons below and dropping me a line through the comments or even contact me. Thank you for stopping by and keep being awesome!