Eloquent ORM Basic Usage

Eloquent ORM is a convenient way to interact with database and each database table has a corresponding Model.

TODO List

  • Use schema builder or migration to structure table.

  • Set up Model.

  • Run sql query with Eloquent ORM style.

Migrate new table :

php artisan make:migration create_books_table –table=books

Check migrartion file database/migrations/filename

<?php

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

class CreateBooksTable extends Migration {

	/**
	 * Run the migrations.
	 *
	 * @return void
	 */
	public function up()
	{
		Schema::create('books', function(Blueprint $table)
		{
			$table->increments('id');
            		$table->string('title');
            		$table->text('description');
            		$table->string('author');
			$table->timestamps();
		});
	}

	/**
	 * Reverse the migrations.
	 *
	 * @return void
	 */
	public function down()
	{
		Schema::drop('books');
	}

}

Now, Table books has 5 columns id, title, description, author and timestamps(). Above schema builder has automatically added id and timstamps().  

Set Up Model : 

php artisan make:model Book

find it App\Book.php

<?php namespace App;

use Illuminate\Database\Eloquent\Model;

class Book extends Model {

    protected $table = 'books';

}

Model has a variable $table assigning value is 'books', Thats how laravel know which model belongs to which table.

Our model name is Book and Table name is books(plural form of Book), Laravel is enough smart to understand to model correspondence table.

Run Query : 

<?php
Route::get('book', function(){
	//returns all books in table
	App/Book::all();				//Select * from books;
});

Route::get('book', function(){
	//find keyword is use for primary keys
	App/Book::find(1);				//Select * from books where id=1;
});

Route::get('book', function(){
	//get() keyword is returning collection of author = john. 
	App/Book::where('author', 'john')->get();		//Select * from books where author='john';
});

Route::get('book', function(){
	//first() keyword is returning first record. 
	App/Book::where('author', 'john')->first();
});

Route::get('book', function(){
	//add a new record in table with passing through array. 
	App/Book::create( [ 'title'='Harry Potter', 'description'='xyz','author'='J. K. Rowling' ] )
});

Route::get('book', function(){
	//There are collection of records in descending order by id, Set limit for 10 records. 
	App/Book::where('author', 'john')→orderBy('id', 'DESC')->take(10)->get();
});

 

Something to say? Tell us in comment section.