Eloquent ORM Model, CRUD operations,
Laravel includes Eloquent, an object-relational mapper (ORM) that interact with database. Each database table has a corresponding "Model" that is used to interact with that table.
Eloquent models allow you to insert, update, and delete records from the table as well.
You can create model using
Model stays app\Models directory
php artisan make:model Flight
php artisan make:model Flight --migration //model with migration
php artisan make:model Flight --factory //model with factory
php artisan make:model Flight --seed //model with seeder
php artisan make:model Flight --controlle//model with controller
# Shortcut to generate a model, migration, factory, seeder, policy, controller, and form requests...
php artisan make:model Flight --all
Created Model look like
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Flight extends Model
{
//
}
by default flights table created. If you want custom you can use
class Flight extends Model
{
protected $table = 'my_flights'; //custom table name
protected $primaryKey = 'flight_id'; //custom primary key
public $incrementing = false; //if need increment false
public $timestamps = false; //timestamps not add
protected $guarded = []; // allow all fields to insert /update
protected $attributes = [ //default value of delayed column
'delayed' => false,
];
}
_____________________________
Eloquent return data as Illuminate\Database\Eloquent\Collection,
>>1.Get data: use below command in controller or view
$data = \App\Models\User::all(); //return all users in users table using model User
foreach ($data as $key => $user) {
echo $user->name;
}
>> GET data using where
$data = \App\Models\User::where('email', '[email protected]')
->orderBy('id')
->take(10)
->get(); //take means only 10 rows return
>> Nested if condition
\App\Models\User::where('email', '[email protected]')
->where(function($query) {
$query->where('typeis', 'like', 'admin%')
->orWhere('typeis', "like", "%"."super admin"."%");
});
>> Count data
$count = \App\Models\User::where('votes', '>', 100)->count();
OR
$count = \App\Models\User::where('votes', 100)->count();
>> JSON Selection
public function user_det($name){
$names = \App\Models\User::where('name', 'like', $name.'%')
->selectRaw('name')
->distinct()
->take(10)
->get()->toArray();
if($names){
return response()->json(['flag' => true, 'locations' => $names],200);
}else{
return response()->json(['flag' => false, 'locations' => ""],200);
};
}
>> Get column values
$user_names= \App\Models\User::distinct()->pluck('name');
Insert Data
Before Insert data must add this in model: It helps prevent unintended or malicious modification of model attributes. protected $fillable is a property in Laravel's Eloquent models that is used to specify which attributes on the model can be mass-assigned using the create() and update() methods.
protected $fillable = [
'name',
'email',
];
$user = new \App\Models\User;
$user->name = "MR DUMMY";
$user->email = "[email protected]";
$user->password = "[email protected]";
$user->save();
OR
$flight = \App\Models\User::create([
'name' => 'name to Paris',
'email'=>"[email protected]",
'password'=>"mrbbbbb"
]);
UPDATE
$user = \App\Models\User::find(1); //get user by ID
$user->name = 'Rizwan AG';
$user->save(); //update
OR
\App\Models\User::where('email', "[email protected]")
->update(['name' => "R GONDAL"]);
updateOrCreate
$user = \App\Models\User::updateOrCreate(
['email' => '[email protected]'],
['name' => "updated rizi","password"=>"123","email"=>"[email protected]"]
);
//if email [email protected] exist update the name,password, and email else, insert
DELETE
$user = \App\Models\User::find(1);
$user->delete();
//OR
\App\Models\User::destroy(1); //ONLY primary key accepted
\App\Models\User::destroy([1, 2, 3]);
//OR CONDITION
$deleted = \App\Models\User::where('email', '[email protected]')->delete();
soft-deleting: NOT DELETE BUT deleted_at colum add:
https://laravel.com/docs/9.x/eloquent#soft-deleting
Truncate Table
\App\Models\User::truncate();
pruning-models: periodically delete records ie delete daily users that not verify there emails
ACCESS MODEL FUNCTION IN CONTROLLER
Step 1: Define a Public Function in the Model
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
public function getUserByName($name)
{
return $this->where('name', $name)->first();
}
public static function getUserByEmail($email)
{
return self::where('name', $email)->first();
}
}
Step 2: Access the Public Function in the Controller
class UserController extends Controller
{
public function getUserByName($name)
{
$userModel = new \App\Models\User(); // Create an instance of the User model
$user = $userModel->getUserByName("ABC");
$user = \App\Models\User::getUserByEmail("[email protected]"); // WITHOUT creating user instance we can access static function
}
}
https://laravel.com/docs/9.x/eloquent#pruning-models