Laravel 8 model queries

9 Dec

Laravel 8 model queries


Create a model
php artisan make:model App\Models\Customer

If we would like to create a migration along with model.
php artisan make:model App\Models\Customer -m

If we would like to crate a seeder
php artisan make:model App\Models\Customer -s

If we would like to create a controller
php artisan make:model App\Models\Customer -c

if we need migration, seed and controller
php artisan make:model App\Models\Customer -cms


Default model class will be

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Customer extends Model
{
    //
}

Now it’s better to add one more line
protected $guarded = [‘id’];


<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Customer extends Model
{
     // id cannot be mass assignable
     protected $guarded = ['id'];
}

Save data from a controller.

Open your controller.
app/Http/Controllers/CustomerController.php

and add

use App\Models\Customer;

then

$customer = Customer::create([
‘name’ => ‘Customer 1’,
‘address’ => ‘Address1’,
’email’ => ‘customer1@domain1.com’,
‘phone’ => ‘98989898’
]);

Now the final code will be

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Models\Customer;

class CustomerController extends Controller
{

    public function index(Request $request)
    {

            $customer = Customer::create([
            'name' => 'Customer 1',
            'address' => 'Address1',
            'email' => 'customer1@domain1.com',
            'phone' => '98989898'
        ]);
    }

}

That will save one row.

To test add a row
to the routes/web.php
Route::get(‘/test_insert’, [App\Http\Controllers\CustomerController::class, ‘index’])->name(‘test_insert’);

then take
http://127.0.0.1:8000/test_insert

Laravel update from a controller

Assume we have to update name of of customer with id=1

public function update(Request $request)
    {
        $customer = Customer::find(1);
        $customer->name = 'Updated name';
        $customer->save();

    }

to the routes/web.php
Route::get(‘/test_update’, [App\Http\Controllers\CustomerController::class, ‘update’])->name(‘test_update’);

then take
http://127.0.0.1:8000/test_update

Laravel delete from a controller

public function delete(Request $request)
    {
        $customer = Customer::find(1);
        $customer->delete();

    }

Route::get(‘/test_delete’, [App\Http\Controllers\CustomerController::class, ‘delete’])->name(‘test_delete’);

Select all record from Laravel controller

public function show(Request $request)
    {
            $customers = Customer::all();
            foreach ($customers as $customer) {
                echo $customer->name;
            }   
    }

Route::get(‘/test_show’, [App\Http\Controllers\CustomerController::class, ‘show’])->name(‘test_show’);

Leave a Reply

Your email address will not be published. Required fields are marked *