How to create eloquent model in laravel 5

Rakesh Sharma      No Comments  

How to create eloquent model in laravel 5 and use model in controller

How to create eloquent model in laravel 5

What is model :-

The model contains your application’s logic and rules or you can say keeping application’s database interactions.

Laravel provides a beautiful, simple ActiveRecord implementation using Eloquent ORM for working with your database. Using Model you can run query for data in your tables, also insert new records into the table. Today we’ll be see how to create eloquent model in laravel 5 and how to use model function in controller in laravel 5. In laravel 5 you can easily make a model using artisan commands.

Creating eloquent model using artisan

To make a model using artisan command grab your path to laravel application and run below artisan command.

php artisan make:model Your_model_name

This will create a model with given name in app directory. And with below code you will see in new model file.

<?php namespace App;
use Illuminate\Database\Eloquent\Model;
class My extends Model { // My is model name.
}

Specify Table Names in Model :- you can specify your table name in model to get tables information like records, structure, columns etc.

<?php namespace App;
use Illuminate\Database\Eloquent\Model;
class My extends Model { // My is model name.
  protected $table = 'my_table';
}

Creating eloquent model manually

You are free to make model manually and anywhere. Just one step you must use All Eloquent models must be extended Illuminate\Database\Eloquent\Model class. Just create a file like My.php and add below code.

<?php namespace App;
use Illuminate\Database\Eloquent\Model;
class My extends Model { // My is model name.
}

Using model in controller

So When you done with your model and its associated database table, You are ready to use it in your controller. You can retrieve data easily from your database using query builder in laravel 5. So let's start using model. Just use use keyword to include your model in controller and get your defined table data with model class.

<?php namespace App\Http\Controllers;
use App\My; //including model.
use App\Http\Controllers\Controller;
class MyController extends Controller {
    public function index() {
        // Getting all records from model associates table.
        $data = My::all();
        // Returning data on view.
        return view('my.index', ['data' => $data]);
    }
}

Note :- If your model in any subdirectory like app/models/My.php, Then you should use in your controller use App\Models\My.

Now you can easily retrieve your database records by create a eloquent model in laravel 5. To get more information about eloquent model in laravel 5 follow official docs.