How to Use Models in Laravel?

Laravel provides us Models to handle database operations in such a way that we can create, update, delete and find records without knowing SQL queries. Lets say we have a table called products. It has following columns as name, price, description. So our app/Product.php model will look like this.

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Product extends Model
{
    protected $fillable = ['name', 'price', 'description'];
}

Now we have an array of products which we want to add in products table.

$products = [
	[ 'name' => 'Purel', 'price' => 120, 'description' => 'this is a hands sanitizer.' ],
	[ 'name' => 'Clinell', 'price' => 10, 'description' => 'this is a soap gel.' ],
	[ 'name' => 'Lysol', 'price' => 110, 'description' => 'this is a cleaner.' ],
];

If array indices are consistent with column names in our table then we can simply add them all in one go using this model query.

foreach ($products as $product) {
   Product::create( $product );
}

We can select all products using either of these queries.

$products = Product::get();
$products = Product::all();

Now if you have id and want to find product then.

$product = Product::findOrFail($id);

If we want to search on the basis of name then.

$product = Product::where('name', 'purel')->get();

It will return a collection but if we are sure that we want only 1 record then we can use this.

$product = Product::where('name', 'purel')->first();

If we want to edit then we can do this.

$product = Product::findOrFail($id);
$product->name = "updated name";
$product->save();

and we can delete by finding and then calling delete() method.

$product = Product::findOrFail($id);
$product->delete();

I hope now you can use models in Laravel to easily handle database queries. If you have any problem please leave a comment.