Eloquent is an ORM (Object Relational Mapper). An ORM maps an object in your database, like a table row, to an object in PHP code. This is Laravel’s Active Record implementation.
Now an important thing to remember the Class is the singular form of the Table name. For example:
- jobs -> Job
- comments -> Comment
- job_listings -> JobListing
Now if for example you have a table called “jobs” and “jobs_listings” if you call from the Job Eloquent Class it will automatically reach for the “jobs table”. As mentioned before you can either just change the name of the class but there’s another way, where you can choose a unique table name. Here’s how:
class Job extends Model {
protected $table = 'job_listings';
}So what you do is add a protected property called “table” and assign it “job_listings”.
Create new database row
Important! This is written inside the command prompt under: “php artisan tinker“
You can of course also create a new table. You can simply run this code:
App\Models\Job::create(['title' => 'Acme Director', 'salary' => '$1,000,000']);Now when you try this code just so you will get the following error:
Illuminate\Database\Eloquent\MassAssignmentException Add [title] to fillable property to allow mass assignment on [App\Models\Job].The reason for this is, that since you always assume that a user is trying to do something bad or damaging to the site. For example he might be trying to change the “author_id” for a certain post, that could be very bad. To prevent that Laravel automatically refused to execute such code to protect you / your website or well more so it ignores that request.
Though this isn’t really a problem as long your 100% aware of what’s in the code, meaning what gets changes, created or deleted.
Now you could just disable this feature or basically make an exception for certain
Here’s how (code editor):
class Job extends Model {
protected $table = 'job_listings';
protected $fillable = ['title', 'salary'];
}What you do is add a protected property called “fillable” and assign which attributes you want to enable multiple to be changes of at the same time. In this case it is “title” and “salary”. Now if you run the code above again it will / should work.
Delete database row
And there’s also a simple way to delete a created row.
First you need to assign in to a variable, like so:
$job = App\Models\Job::find(4);Then you can just call this command to delete the row:
$job->delete();Create new Model
Now above we we used a pre-existing Job class that we converted into an Eloquent model. But usually you will start from scratch, so we will go over how to do that.
Well firstly we need to create a new Model:
If you run this code in your command prompt you will see a list of different commands and what they do:
php artisan help make:modelDescription:
Create a new Eloquent model class
Usage:
make:model [options] [--] <name>
Arguments:
name The name of the model
Options:
-a, --all Generate a migration, seeder, factory, policy, resource controller, and form request classes for the model
-c, --controller Create a new controller for the model
-f, --factory Create a new factory for the model
--force Create the class even if the model already exists
-m, --migration Create a new migration file for the model
--morph-pivot Indicates if the generated model should be a custom polymorphic intermediate table model
--policy Create a new policy for the model
-s, --seed Create a new seeder for the model
-p, --pivot Indicates if the generated model should be a custom intermediate table model
-r, --resource Indicates if the generated controller should be a resource controller
--api Indicates if the generated controller should be an API resource controller
-R, --requests Create new form request classes and use them in the resource controller
--test Generate an accompanying Test test for the Model
--pest Generate an accompanying Pest test for the Model
--phpunit Generate an accompanying PHPUnit test for the Model
-h, --help Display help for the given command. When no command is given display help for the list command
--silent Do not output any message
-q, --quiet Only errors are displayed. All other output is suppressed
-V, --version Display this application version
--ansi|--no-ansi Force (or disable --no-ansi) ANSI output
-n, --no-interaction Do not ask any interactive question
--env[=ENV] The environment the command should run under
-v|vv|vvv, --verbose Increase the verbosity of messages: 1 for normal output, 2 for more verbose output and 3 for debugNow if you run:
php artisan make:model JobIt will create a new Eloquent model called Job in this location: app\Models
Or if you run:
php artisan make:model Job -mYou will create a new Eloquent model called Job in this location: app\Models and a new migration here: database\migrations
Now to keep in mind this migration doesn’t have any instructions on what to create so you will have to adjust that manually in your code editor.
This is the default code for the Eloquent model and migration (read more about migrations here):
Eloquent Model:
<?php
namespace App\Models;
// use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Job extends Model
{
// use HasFactory (so you can use a Factory)
}migration:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('job_listings', function (Blueprint $table) {
$table->id();
// $table->string('title'); (an example of what you might want to add)
// $table->string('salary');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('job_listings');
}
};Eloquent Relationship
(Might be easier to understand if you read Factories first) Eloquent Relationships are defined in the Model used to access data from a different table inside the database.
Here’s how you can do that (command prompt inside a tinker session):
$job = App\Models\Job::first();
// then call the function
$job->employer;
// now you can access properties inside the employer tabel
$job->employer->name;You call the function, not as a function but instead as a property like (title, salary, etc.), Laravel realizes that there isn’t a property called “employer” and assumes that your trying to access the employer relationship.
Here’s how it will look in the code editor:
public function category()
{
return $this->belongsTo(Category::class);
}All different Relationship:
- hasOne ->
- 1:1, One person owns exactly one passport, and each passport belongs to one person.
- belongsTo ->
- 1:m, A Comment belongs to a Post
- hasMany ->
- m:1, A post can have many Comments
- hasOneThrough ->
- 1:1, A patient is registered with one hospital, and that hospital has one chief doctor (medical director). You want
patient->primaryDoctorwithout first loading the hospital.
- 1:1, A patient is registered with one hospital, and that hospital has one chief doctor (medical director). You want
- hasManyThrough ->
- m:1, A country has many users, and each user writes many blog posts. You’d like
country->postsdirectly.
- m:1, A country has many users, and each user writes many blog posts. You’d like
- belongsToMany ->
- m:m, Students enroll in multiple courses, each course has multiple students.
Pivot / Relationship tables
Pivot tables are a table that exist of two or more foreign keys. So they are used to create a connection between 2 different tables.
For example you have a table with different Jobs and a list with different Tags. This will be a “belongsToMany” Relationship because a Job can have multiple different Tags but the Tag can also have multiple different Tags.
Now you will need a table for it, as for the name usually just name it “Model1_Model2” in this example “job_tag”. Here’s how the migration file can look like:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('tags', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->timestamps();
});
Schema::create('job_tag', function (Blueprint $table) {
$table->id();
$table->foreignIdFor(\App\Models\Job::class, 'job_listing_id')->constrained()->cascadeOnDelete();
$table->foreignIdFor(\App\Models\Tag::class)->constrained()->cascadeOnDelete();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('tags');
Schema::dropIfExists('job_tag');
}
};
Now in this migration file there are two tables being created. The reason for that is because it was done at the same time (the “tags” table and the “job_tag” table), but it can just as well be in a separate migration file.
You might notice that in the call for the foreign key of the Job class there’s extra text, that’s because Laravel defaults to the “jobs” table that exists as well. But we want the “job_listings” table or well the id and that’s what that is for to specify which table we want.
Now you also need functions in your PHP code so you can access the other table. Here’s how:
// The Job Model (app->Models->Job.php)
public function tags()
{
return $this->belongsToMany(Tag::class, foreignPivotKey: 'job_listing_id');
}
// The Tag Model (app->Models->Tag.php)
public function jobs()
{
return $this->belongsToMany(Job::class, relatedPivotKey: 'job_listing_id' );
}Now normally you don’t need the foreign / related PivotKey but as mentioned above this is needed in this case because Laravel defaults to the “jobs” table but we want the “job_listings” table and that what the Pivot does it specifies that we want the “job_listing_id” well from the “job_listings” table of course.
