Tagged: Laravel, Laravel Blog, PHP
- This topic has 0 replies, 1 voice, and was last updated 1 year, 3 months ago by
Chinomnso.
- AuthorPosts
- January 13, 2020 at 4:31 pm #83868Spectator@chinomnso
In the previous article in this series, we worked with partials which help us to keep common page elements in separate files and call them up later. This makes our code organized and easy to work with.
Laravel is database-driven. Therefore, we must learn how to set up a database for our project. In previous articles, I’ve written about Controllers and Views. In this article, we will first talk briefly about Models.
“M” stands for “Model” in MVC. Models in Laravel provide a simple way to interact with your database. Each table in your database has a corresponding model with which you can interact with the table. Using models, you can query tables for data and insert data into them.
Creating A Database
To create a database, start XAMPP and start the Apache and MySQL modules. Then load http://localhost/phpymyadmin in your browser. Click New at the top of the left pane in the PHPMyAdmin window. Enter the desired name of the database and click Create.
So far in this series, we haven’t needed a database connection to do anything. However, prior to working with models, you must set up a connection to a database. So, navigate to config and open database.php. The file contains code for connecting with different database systems. But I’m working with MySQL, so we will be editing the MySQL section of this file. Edit the DB_HOST, DB_DATABASE, DB_USERNAME, and DB_PASSWORD values to correspond to your environment set up. The following snippet is from my project.
12345678910111213141516171819'mysql' => ['driver' => 'mysql','url' => env('DATABASE_URL'),'host' => env('DB_HOST', '127.0.0.1'),'port' => env('DB_PORT', '3306'),'database' => env('DB_DATABASE', 'laravel'),'username' => env('DB_USERNAME', 'root'),'password' => env('DB_PASSWORD', ''),'unix_socket' => env('DB_SOCKET', ''),'charset' => 'utf8mb4','collation' => 'utf8mb4_unicode_ci','prefix' => '','prefix_indexes' => true,'strict' => true,'engine' => null,'options' => extension_loaded('pdo_mysql') ? array_filter([PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'),]) : [],],Creating A Model
Models are stored in the
app
directory. However, they can be placed anywhere, as long as they can be auto-loaded according to directives in the composer.json file. Models extend the Illuminate\Database\Eloquent\Model class.To create a model, use the following command in your terminal:
1php artisan make:model Post --migrationSince we are working on a blog application, I named the model Post. The corresponding table will store the posts on our blog. The
--migration
suffix generates a migration that corresponds to the model that has just been created. I’ll talk about migrations shortly. Navigate to app and you should see a new file, Post.php. Open it, and you should have something like this:12345678910<?phpnamespace App;use Illuminate\Database\Eloquent\Model;class Post extends Model{//}The command that created the model shown above created a class named Post that extends a built-in class called Model. Although this is just skeletal, the model opens up lots of possibilities and puts much power in your hands to help you interact with the corresponding table.
Migrations
Migrations provide version control features for your database, allowing you to make changes to your application’s database schema. The good thing is that Laravel offers database agnostic support for handling tables across all database systems supported by Laravel.
A migration class contains two methods, namely
up
anddown
. Theup
method is used to add new tables, indexes or columns to your database, while thedown
method is used to roll back the operations performed by theup
method.When we created the post model, a migration was created too because of the
--migrate
option we added to the command. That migration can be found in the database/migrations directory, with a timestamp prefixed to create_posts_table.php as the filename. You would also notice other migrations: the Users migration and the Password Resets migration. They are part of Laravel’s installation, and they handle authentication. If you open the migration corresponding to the model we created, you should see something like this:123456789101112131415161718192021222324<?phpuse Illuminate\Support\Facades\Schema;use Illuminate\Database\Schema\Blueprint;use Illuminate\Database\Migrations\Migration;class CreatePostsTable extends Migration {/** * Run the migrations. * * @return void */public function up() {Schema::create('posts', function (Blueprint $table) {$table->bigIncrements('id');$table->timestamps();});}/*** Reverse the migrations.** @return void*/public function down(){Schema::dropIfExists('posts');}}You will notice that Laravel created a boilerplate for our table creation. I won’t start explaining the basics of database design now because I assume you have already been writing PHP. To learn more about Laravel’s Schema class, check out Laravel’s official documentation. It provides a list of the different column types that you can use when building tables and how you can use them. The proposed table has been seeded with id, an auto-increment field, and timestamps(), a function to create columns to hold timestamps indicating when each post was made and updated. Edit the migration file we are working on to look like this:
1234567891011121314151617181920212223242526<?phpuse Illuminate\Support\Facades\Schema;use Illuminate\Database\Schema\Blueprint;use Illuminate\Database\Migrations\Migration;class CreatePostsTable extends Migration {/** * Run the migrations. * * @return void */public function up() {Schema::create('posts', function (Blueprint $table) {$table->increments('id');$table->string('title');$table->text('body');$table->timestamps();});}/*** Reverse the migrations.** @return void*/public function down(){Schema::dropIfExists('posts');}}Open up your terminal and run the following command:
1php artisan migrateYou would notice that all three migrations were run: the one just created, and the other two that are there by default. In PHPMyAdmin, click on the database on which you are working and you will see that tables have been created. Now, click on the posts table and you will see that the
timestamps()
function created two columns: created_at and updated_at. That’s Laravel showing off its power. You didn’t have to specify those tables by yourself.You would also notice that a migrations table has been created too. That is how Laravel keeps track of migrations. You may want to open it up and take a look at what’s in there.
The stage has been set to create posts and display them on the website because we now have a database table where the posts will be stored. We are going to learn how to do this in subsequent articles.
- AuthorPosts
- You must be logged in to reply to this topic.