Laravel | Eloquent Model Basics

Laravel is an MVC based PHP framework. In MVC architecture, ‘M’ stands for ‘Model’. A Model is basically a way for querying data to and from the table in the database. Laravel provides a simple way to do that using Eloquent ORM (Object-Relational Mapping). Every table has a Model to interact with the table.

Create a Model: To create an Eloquent Model, Laravel provides an Artisan Command as follows:

php artisan make:model Article

After running the command above, a file is created with the name Article.php in the app directory. The file content looks as follows:

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
  
namespace App;
  
use Illuminate\Database\Eloquent\Model;
  
class Article extends Model {
  //
}

chevron_right


Retrieve Data: To retrieve data from the database, we can use two methods as described below:

  • Here, the all() method will return all the data in the table in the form of an array and store it in the $articles variable.
    public function index() {
            
            $articles = \App\Article::all();
    
            return view('gfg')->with('articles', $articles);
    
    }
  • We can also get a particular record by using ‘where()’ as shown below:
    public function index() {
            
            $articles = \App\Article::all()->where('id', 1);
    
            return view('gfg')->with('articles', $articles);
    
    }

Insert Data: To insert data in the database, we will use save() method as shown below:



  • Here, we create a new Article and store it in the $article variable. The topic and content attribute are used to store the data specified in the respective columns in the table. And then ‘save()’ method is used to insert the data in the database. Then a successful message will be shown if the insert is successful.
    public function insert() {
    
        $article = new Article;
    
        $article->topic = "View in Laravel";
        $article->content = "View is the data display at the user end.";
    
        $article->save();
    
        echo "Insert Successful!";
    
    }
  • Note: The created_at and updated_at field in the table will be automatically be inserted with the time stamp.

Update Data: To update data in the database, we will again use save() method as shown below:

  • Here, the find() method is used to specify the record that we want to update in the database. The number in the parenthesis is of id i.e. primary key. Now a new value is given to the topic field of the record which will change the old one. And then ‘save()’ method is used to insert the data in the database. Then a successful message will be shown if the update is successful.
    public function update() {
    
            $article = \App\Article::find(1);
    
            $article->topic = "Laravel";
    
            $article->save();
    
            echo "Update Successful!";
    
    }
  • Note: The updated_at field in the table will be automatically be inserted with the time stamp.

Delete Data: To delete data in the database, we will use delete() method as shown below:

  • Here, the find() method is used to specify the record that we want to delete from the database. The number in the parenthesis is of id i.e. primary key. Then the delete() method is used. Then a successful message will be shown if the delete is successful.
    public function delete() {
    
            $article = \App\Article::find(1);
    
            $article->delete();
    
            echo "Delete Successful!";
    
    }

Below example illustrates each of them:

Example:

  1. Create and Connect to a MySQL Database.
  2. Create a migration using the following Artisan command:
    php artisan make:migration create_articles_table

    And then write the below code in the up() function in the migration file created at database/migrations directory.

    Schema::create('articles', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('topic');
        $table->string('content');
        $table->timestamps();
    });
  3. Now run the migrate command to create migrations:
    php artisan migrate
  4. Now create a model using the below Artisan command:
    php artisan make:model Article

    The Article.php file, which is created in the app directory, should look like as follows:

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    <?php
      
    namespace App;
      
    use Illuminate\Database\Eloquent\Model;
      
    class Article extends Model {
        //
    }

    chevron_right

    
    

  5. Now create a controller using the below Artisan command:
    php artisan make:controller ArticleController

    The ArticleController.php file, which is created in the app/Http/Controllers directory, should look like as follows:

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    <?php
      
    namespace App\Http\Controllers;
      
    use Illuminate\Http\Request;
      
    class ArticleController extends Controller {
        //
    }

    chevron_right

    
    

  6. Now, you will have to change the controller file as below code or copy the code below and paste it in that controller file which was created in the previous step.
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    <?php
      
    namespace App\Http\Controllers;
      
    use App\Article;
    use Illuminate\Http\Request;
      
    class ArticleController extends Controller {
      
        // Retrieve function
        public function index() {
              
            $articles = \App\Article::all();
      
            return view('gfg')->with('articles', $articles);
      
        }
      
        // Insert function
        public function insert() {
      
        $article = new Article;
      
        $article->topic = "View in Laravel";
        $article->content = "View is the data display at the user end.";
      
        $article->save();
      
        echo "Insert Successful!";
      
        }
          
        // Update function
        public function update() {
      
            $article = \App\Article::find(1);
      
            $article->topic = "Laravel";
      
            $article->save();
      
            echo "Update Successful!";
      
        }
          
        // Delete function
        public function delete() {
      
            $article = \App\Article::find(1);
      
            $article->delete();
      
            echo "Delete Successful!";
      
        }
    }

    chevron_right

    
    

  7. Now, create a view with the name ‘gfg.blade.php’ in the ‘resources/views’ directory and the below code in that file.
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    <!DOCTYPE html>
    <html>
    <head>
        <title>GeeksforGeeks</title>
        <style>
            body {
                font-size: 20px;
            }
        </style>
    </head>
    <body>
      
        <h2>Articles Topics</h2>
        <ol>
            @foreach($articles as $article)
                <li>{{ $article->topic }}</li>
            @endforeach
        </ol>
      
    </body>
    </html>

    chevron_right

    
    

  8. Now, create the routes by writing the following in the web.php file in the routes directory.

    Note: Comment or remove any previous routes from the file.

    Route::get('/', 'ArticleController@index');
    
    Route::get('/insert', 'ArticleController@insert');
    
    Route::get('/update', 'ArticleController@update');
    
    Route::get('/delete', 'ArticleController@delete');
  9. Now run the Laravel app using the following Artisan command:
    php artisan serve

Output:

  1. For Index Function:
  2. For Insert Function:

  3. For Update Function:

  4. For Delete Function:

Reference: https://laravel.com/docs/6.x/eloquent




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.