Laravel for Beginners : a Quick Guide - 4
Tags: laravel8, php, mvc
Published: 2021-08-12 04:42:17

Ok, Hope you understood my previous post on [creating a new route and new controller] (https://dev.to/kartikbhat/laravel-for-beginners-a-quick-guide-3-1bjd)

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/41v4tv2z2if6ddxwecc3.png)

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/j97sm4tm2teczlleihg9.png)

now, you need to create new database, to do that click on **New**,
![newDBImage](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tr3h2oed9si4axeyus94.png)

It will prompt you to the page where you need to mention the database name;
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2gf31bkbbchxuzc56l3b.png)

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

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/awdymtq8orq8jzmq5yhe.png)

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

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/51fb7tmv7z42pnl1qq3n.png)

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dz07z1c6qh524zncbbb1.png)

then change value of **DB_DATABASE** to ###my-app### and save :)
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3cc79l8n8spmsefzvh0o.png)

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
```

you can observe a success message too,

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ga0vsmcnbf5h1t6pttd0.png)


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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8xph2o4o4b60vl2yf30o.png)

> 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');
    }
}

```

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();
 });
```

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
```
you can observe its status,

![dataTable](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/29h28rcfuxncz1ndhp7c.png)

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0rlpt58his21swsg6fhq.png)

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
```
you can observe its status,
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/z0t0nc1mqlp5jik9bc5x.png)

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;
}
```

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'
    ];
}

```

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;
```
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()
```

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 :)