[Learning Laravel] Model & Migrations
Introduction
This will be a series of posts on different topics on Laravel. I recently started learning Laravel, so I’m going to write a post whenever I see something that’s cool or encounter a new feature of Laravel.
- What is Laravel [link]
- Laravel Routes
- Learn Blade Template
- Controllers 101
- Migrations & Models
Migration
Migration creates a schema, table in your database. Another great thing about migration is that we are able to see our migration history. It is like a version control but for databases
Also, we can make sure everyone on the project has the same data structure with one simply migration command.
There are two ways we can create migrations. First is through make:migration command. Second, we can add a -m option after our model and Laravel will also create a migration file for us.
php artisan make:migration create_users_table
php artisan make:model User -m
If something happens, we can always roll back and fix it
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->increments('id');
$table->string('title');
$table->mediumText('body');
$table->timestamps();
});
}public function down()
{
Schema::dropIfExists('posts');
}
Model
Model deals with the computing and SQL query selection. Models deals with the heavy lifting of our app.
Anything that deals with the database are generally written in our Model.
Relationships
Models build relations between tables. In this case, we create a relationship between phone and user. So a user has one phone and the phone belongs to a user.
// User model
public function phone()
{
return $this->hasOne('App\Phone');
}
// User phone
public function user()
{
return $this->belongsTo('App\User');
}
Once relationship is established we can write simple queries such as
$user = User.find(1);
user()->phone
Laravel also offers query build so we can write query commands easier. We can use query builder when we have more complicated queries that ORM can not do.
{
return static::selectRaw('year(created_at) year, monthname(created_at) month, count(*) published')->groupBy('year', 'month')->orderByRaw('min(created_at) desc')->get(->toArray();
}
Conclusion, model deals with the interaction with our database. So let’s try to keep our computing logic in the model.