Laravel 5.2 Eloquent Insert Row or Add Record

Introduction to Eloquent

Most of applications code is based on Object Oriented Design but the database contains tables and relations and return set of rows instead list of objects. So there is inhereit mismatch between application code and database artifacts. Different Lanaugage provide object relational mapping (ORM) technologies that fill this mismatch gap. Eloquent is ORM that is used by Laravel.

Eloquent is used to interact with the database to perform select, insert, update and other database operations. We create model calsses corresponding to every table. Each Model class help in performaing database related operations with associate table. You must know what are migrations and how setup database for Laravel applications to proceed further.

Create Model Class

By default the model classes are located in 'App' folder. If you see you Laravel application's App folder you will see a User.php file, its already created model class by Laravel. Migration for users table are also created created by default, as user is a part of many projects. Lets create another model class Book along with migration so that we can also create a table to store books records by running the migration.

Point your Command Prompt to project folder and type below command to create Model class:

C:\wamp\www\laraveltutorials> php artisan make:model Book

It will create a model class Book in App\Book.php file. If you open your model class, it would look like this.

namespace App;
use Illuminate\Database\Eloquent\Model;

class Book extends Model {

}

Create Books Migration

Please note, I have already created and run migration for books table, here is the migration code:

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateBooksTable extends Migration
{
public function up() {
Schema::create('books', function (Blueprint $table) {
$table->increments('id');
$table->string('title');
$table->string('author');
$table->string('publisher');
$table->integer('publish_year');
$table->boolean('available');
$table->timestamps();
});
}

public function down() {
Schema::drop('books');
}
}

Defining Fillable Attributes in Book Model Class

You see, its empty, but by extending the Model base class, we have incorporated all the database interaction functionality in the class. By default all of the Book attributes are open to initialize to insert new record in books table. Laravel discourge keeping all attribtues open or fillable. So we define an attribute called fillable in the model class that contains the names of table columns that can be set when inserting a new record. Columns which are not fillable are not effected when adding new record i.e. default values are used for those columns. For example, we don't want user to send the value of id attribute as its auto generated primary key. Lets make some fields fillable:

namespace App;
use Illuminate\Database\Eloquent\Model;

class Book extends Model {

protected $fillable = ['title', 'author', 'publisher', 'publish_year'];
}

Eloquent send values of only fillable attribtues when inserting a new record in table. The id, available, created_at and updated_at columns would contain default values.

Defining routes for BooksController

Let’s set a route to show all records and to handle submit request to add new book record in database. Add follwing into your routes.php file located at App\Http

Route::get('/books', 'BooksController@index');
Route::post('/books','BooksController@create');

BooksController

Here I create BooksController.

C:\wamp\www\laraveltutorials> php artisan make:controller BooksController

You see, I have also added two methods index and create, the index method returns the current books after getting from Book model and create mothod handle post request to insert new books record into books table. Here is the controller code:

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Book;

class BooksController extends Controller
{
public function index()
{
$books = Book::all();
return view('books/index', ['books' => $books]);
}

public function create(Request $request)
{
$data = $request->all();
Book::create($data);
return redirect('books');
}
}


You see how straight forward its is to fetch all books and insert a new book.

View to Display Current Records and Add New Record 

Here is the contents of resources\views\books\index.blade.php file:

<!DOCTYPE HTML>
<html>

<body>
<h3>List of Current Books </h3>
<ol>
@foreach($books as $book)
<li>{{$book->title}} - By {{$book->author}}</li>
@endforeach
</ol>

<h3> Add New Book </h3>

<form method="post" action="books">

<input type="hidden" name="_token" value="{{ csrf_token() }}">

<label>Title</label>
<input type="text" name="title">

<label>Author</label>
<input type="text" name="author">

<label>Publihser</label>
<input type="text" name="publisher">

<label>Publish Year</label>
<input type="text" name="publish_year">

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

</body>

</html>

Comments

Post a Comment