DEV Community

Cover image for Laravel for Beginners : a Quick Guide - 4
Kartik Bhat
Kartik Bhat

Posted on

Laravel for Beginners : a Quick Guide - 4

Ok, Hope you understood my previous post on creating a new route and new controller

Now, today I will try to explain how the controller interacts with the model

Model !!

Cool, Model is nothing but an another .php file , say a PHP class; where interaction with a database's table happens actually;

now to interact with database table first we need to create a database and need to configure it with our Laravel application...

I hope you are already running your WAMP/XAMPP server (each time while reading my post don't forgot do this in the beginning, if you server is not running)

Ok, now open MySQL admin present in your server,
in case of WAMP ; hit this URL in your browser

http://localhost/phpmyadmin

you can see this window then,
PHPMYADMIN

by default username will be root and password is nothing (just leave it blank) hit enter (click on GO),

then you will be redirected to this page;
PMADashboard

now, you need to create new database, to do that click on New,
newDBImage

It will prompt you to the page where you need to mention the database name;
Alt Text

enter database name as my-app (our application name :) )

Alt Text

then click on create, it will create a new database; cool :)

Alt Text

Hurray, you just created a new database :)

Ok, Lets configure it with our Laravel app;
Open .env file present inside our Laravel application directory.

initially it looks like this;
Alt Text

then change value of DB_DATABASE to ###my-app### and save :)
Alt Text

You were done with database configuration; Yes it is really simple :)

now, you need to create a table to save some data into the created database, for that you need to create database migration file;

to do that run this command in your command prompt within our Laravel application

php artisan make:migration create_data_table
Enter fullscreen mode Exit fullscreen mode

you can observe a success message too,

Alt Text

this will create new .php file under database -> migrations folder(go and check existence of this file - current time stamp got automatically prepended to the file name)

Alt Text

Again , don't worry about those pre-existing migration files present there, those were created by laravel by default while installing our application

created migration file looks like this,

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateDataTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('data', function (Blueprint $table) {
            $table->id();
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('data');
    }
}

Enter fullscreen mode Exit fullscreen mode

there are two methods up() and down(), on executing up() new table called 'data' will be created and on executing down() 'data' table will be dropped/deleted from the database if it is already exists, for now; do concentrate only on up(),

change content of up() to ,

 Schema::create('data', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name',50);
        $table->integer('age');
        $table->timestamps();
 });
Enter fullscreen mode Exit fullscreen mode

This is required create a table called 'data' with attributes

  • auto incrementing integer primary key 'id'
  • varchar 'name' with max length of 50
  • integer 'age'
  • timestamps; 'created_at' and 'updated_at'

now it time to migrate this schema at our server, to do that run this command (refer correct file name for the data table, here file name is specific to my computer)

php artisan migrate --path=/database/migrations/2021_08_11_165419_create_data_table.php
Enter fullscreen mode Exit fullscreen mode

you can observe its status,

dataTable

Bingo, this will create a new table called 'data' at our MySQL admin panel with those attributes mentioned above;

Open MySQL admin panel, and within our 'my-app' database we can observe 'data' table got migrated/created.

Alt Text

Ok, You are done with database's table creation, Now it is time to create a platform to access data present in the 'data' table, for that we need to create Model File, say a PHP file/class again :)

run this command to create a new Model File at app -> Models folder

php artisan make:model Data
Enter fullscreen mode Exit fullscreen mode

you can observe its status,
Alt Text

now check this file at app->Models folder, it looks like this;

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Data extends Model
{
    use HasFactory;
}
Enter fullscreen mode Exit fullscreen mode

then, you need to mentions attributes of 'data' table here, after adding required attributes this file looks like,

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Data extends Model
{
    use HasFactory;

    protected $fillable = [
        'id',
        'name',
        'age',
        'created_at',
        'updated_at'
    ];
}

Enter fullscreen mode Exit fullscreen mode

Ok, Everything related to database creation and its configuration with our Laravel application got completed,

Now we need to call/utilize/refer this Model file/class in our Data Controller file/Class so that we can interact with the database,

to do so first we need to define/use Class name of Model at our controller,

add this anywhere after 'namespace' declaration (this is usually a first line of our PHP class, so you should add anything after this line itself)

use App\Models\Data;
Enter fullscreen mode Exit fullscreen mode

Now, By using Object of Class Data (our Model Class) we can access our database table 'data' anywhere within our Controller methods.

Eg :

$dataValues = Data::get()
Enter fullscreen mode Exit fullscreen mode

this will fetch all data present under 'data' table of our database 'my-app'

usage of :: is a syntax from Laravel,

Ok, This is all about accessing Database through Model in our Controller, Lets meet in the next concept on displaying a data fetched from database on our UserInterface / Browser / our blade.php file.

Bye :)

Top comments (0)