CRUD Laravel Beginner Guide Step By Step

Posted on

In this article I will share a basic CRUD Laravel Beginner Guide Step By Step for the first time and I use the Linux Operating System with PopOS (Ubuntu Distro Linux Variant).

Later we will need phpmyadmin for database management. If you haven’t installed phpmyadmin, you can read Install phpMyAdmin Ubuntu Linux Easy Terminal article.

Please read the steps CRUD Laravel Beginner step by step to minimize errors.

PREPARATION

PREPARATION: MVC Concept

Laravel uses the MVC (Model View Controller) concept for CRUD (Create, Read, Update and Delete).

  • Model is a section that deals with database manipulation. All program code related to the database will be stored here.
    Model files will be store in app > Models folder.
  • View is a section that deals with views. All program code related to the view will be stored here. View files will be store in recources > views folder.
  • Controller is the section that manages traffic and programming logic. This section is the link between View and Model. Controller files will be store in app > Http > Controllers folder.

PREPARATION: Install Laravel Project

Now it’s time for us to install new laravel project by downloading the laravel package first through the terminal. Make sure you are connected to the internet and downloaded laravel around 30MB. We will create this project with the name “crud“, use the following command and wait to finish.

composer create-project --prefer-dist laravel/laravel crud

If the crud has been successfully created, please open it with visual studio code or your favorite text editor. You will see as in the following image:

Install Laravel Project Beginner

PREPARATION: Make A Database

Open the .env file, look for the line DB_DATABASE which by default is “laravel”. Please replace with the desired database name.

For example in the tutorial I created the database name with “crud“. So I wrote DB_DATABASE = crud.

Now, open phpmyadmin with address is http://localhost/phpmyadmin/ in your browser. Create a Database with the name “crud” to match the DB_DATABASE = crud in the .env file.

CRUD Laravel Beginner Guide Step By Step

PREPARATION: Make A Table

To create a table, we don’t do it manually in phpmyadmin, but we will use Laravel’s comand “artisan make“.

Open a terminal in your vscode. We will create a migration file with the name “testingname“, But with laravel we have to add the word “create_yourTableNameHere_table” so the command format is:

php artisan make:migration create_testingname_table

If successful you will see output like this:

neon@linux:~/Documents/crud$ php artisan make:migration create_testingname_table

   INFO  Created migration [2022_09_11_155206_create_testingname_table]. 

A file will be created with the name create_testingname_table.php in the database > migrations folder. Look at the following picture:

In this file there are two functions, namely up() and down(). What does it do?

  • up() function is used to create fields/columns.
  • down() function is used to delete a field/column.

We will create some fields in the “testingname” table with names:

  • full_name
  • gender
  • address

Now, copy the following code and paste into the up() function:

$table->string('full_name');
$table->string('gender');
$table->string('address');

You will see it like this:

NOTE:

To create a separate field name, use the underscore “_” as a connector, for example the field name is “full name” so that it becomes “full_name“.

After that, please Save the file, then use the following command in the terminal to create tables and fields in “crud” database automatically by laravel :

php artisan migrate

If successful you will see the following output:

neon@linux:~/Documents/crud$ php artisan migrate

   INFO  Preparing database.  

  Creating migration table ....................................................... 89ms DONE

   INFO  Running migrations.  

  2014_10_12_000000_create_users_table .......................................... 103ms DONE
  2014_10_12_100000_create_password_resets_table ................................. 65ms DONE
  2019_08_19_000000_create_failed_jobs_table ..................................... 72ms DONE
  2019_12_14_000001_create_personal_access_tokens_table ......................... 116ms DONE
  2022_09_11_155206_create_testingname_table ..................................... 40ms DONE

So back to phpmyadmin and reload, in the crud database will create a table with the name testingname along with the full_name, gender and address fields. Look at the picture below:

CRUD Laravel Beginner Guide Step By Step
CRUD Laravel Beginner

NOTE:

The failed_jobs, migrations, password_resets, personal_access_tokens and users tables will be created automatically by Laravel. For now, ignore that table and focus on the testingname table instead.

PREPARATION: Make a Route

A route is used to redirect a link in a web browser to a specific file in Laravel.

By default, if we use the php artisan serve command, then Laravel will give the address http://127.0.0.1:8000 and will display in your browser like the following page:

CRUD Laravel Beginner

Back in vscode, open the routes > web.php. Look at the following picture:

Inside the web.php file, on lines 16 to 18, are the default routes.

The character “/” means root which refer to the Home page.

The way to read the program code is “if you access “/“, display the data in the welcome file view”.

Where is the “welcome” file?

You can find it in resources > views > welcome.blade.php as shown in the following picture:

NOTE:

By default, laravel format view file is .blade.php not .php, cause Laravel have a template engine. For now, we will not use the template engine because we will focus on CRUD (Create, Read, Update and Delete).

We will create a page for crud project, but not on the “/” root link, instead we will use the “/crud” link in the address http://127.0.0.1:8000/crud.

Now, under line 18 of the web.php file, add the following code and Save the file:

Route::get('/crud', [CrudController::class, 'index']);

So you will see something like in the following picture:

Notice the route we just created, will refer to a controller with the name CrudController and run the index function.

You can change the name of the controller as you wish, as long as the name matches the name of the controller that will be created later.

PREPARATION: Make A Controller

To create a controller file in laravel, we will use the “artisan make” command. The name of the controller file that we want to create is CrudController, then use the following command:

php artisan make:controller CrudController

If successful, you will see output like this:

neon@linux:~/Documents/crud$ php artisan make:controller CrudController

   INFO  Controller created successfully.  

Then the CrudController file will be created in app > Http > Controllers > CrudController.php as shown below:

Because on the route we want to run the index function, by default there is no function available in the controller, so copy the following code:

public function index()
    {
        return view('crudpage');
    }

paste it into the class CrudController extends Controller as shown in the following and save the file:

Later, if we access at http://127.0.0.1:8000/crud then the route will direct us to the CrudController.php and will run the index() function. Then the index function will display the crudpage file.

NOTE:

In the route section we create Route::get(‘/crud’, [CrudController::class, ‘index’]);
The CrudController file contains return view(‘crudpage’);

It means:
When we access http://127.0.0.1:8000/crud
Laravel will redirect us to the CrudController.php file
The CrudController.php file will redirect us to the view crudpage.blade.php file.

Now a CrudController has been created. In order for the controller to be recognized by the Route file, we must add the controller location in the web.php file (route).

Open the web.php file and add the following code before the route line:

use App\Http\Controllers\CrudController;

So with this code it tells in the route that the CrudController is in the app > Http > Controllers folder. Look at the following:

PREPARATION: Make A View

We will create a view file to display the form and data in the browser. Go to resources folder and Right click on views then new File. Give name crudpage.blade.php, then fill it with the following code and save the file:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Crud Page</title>
</head>
<body>
    <h1>CRUD TESTING</h1>
</body>
</html>

Look at the following:

Now, on the terminal use the following command to run localhost:

php artisan serve

Back in the browser, use the address http://127.0.0.1:8000/crud. If a page like this appears, that mean is successful for preparation section.

CRUD Laravel Beginner

CREATE

CREATE: Make Input Form

To make it easier for us to input or create data, we will create an input form and a submit button. To do that, add the following code in the <body> in the crudpage.blade.php file:

<form action="/create" method="post">
        {{csrf_field()}}
        <input type="text" id="full_name" name="full_name" placeholder="Full name">
        <input type="text" id="gender" name="gender" placeholder="Gender">
        <input type="text" id="address" name="address" placeholder="Address">
        <input type="submit" value="Save">
    </form>

So it will look like in the following:

NOTE:

{{csrf_field()}} is a Laravel built-in function to generate tokens automatically. Its function is to protect our web from CSRF attacks. The token value will be generated randomly every time there is data transmission, and the token will accompany the data sent, making it very difficult for data forgery attacks to be carried out.

In the browser open https://127.0.0.1/8000/crud, then the form will look like this:

CRUD Laravel Beginner Guide Step By Step

When the Save button is pressed, our website will go to http://127.0.0.1:8000/create. But now, an error will appear if the save button is clicked, because we haven’t created a route for the “/create” address so the laravel doesn’t know what to display. Therefore, next we will create a route create.

CREATE: Make Create Route

Open routes > web.php file, then add the following code:

Route::post('/create', [CrudController::class, 'create']);

So it will look like this:

Now, route “/create” has been created. Later if we access the address http://127.0.0.1:8000/create, it will go to the ‘create’ function in CrudController. But the create function is not yet available, let’s create it.

CREATE: Make Create Function In Controller

Open the CrudController.php file in the app > Http > Controllers folder. Then add the following code:

public function create(Request $request)
    {
      
    }

The create function has been created, but there is no content yet. We need to create a model to define the database and fields. Later, in this create function will be entered the command to save data to the database.

CREATE: Make A Model

To create the model, we will use the “artisan make” command. We will create a model and we will name it with “Crud“. To create a model name, the first letter is capitalized.

Now open a terminal and use the following command:

php artisan make:model Crud

If successful it will output like this:

neon@linux:~/Documents/crud$ php artisan make:model Crud

   INFO  Model created successfully.  

The Crud model file will be created in app > Http > Models > Crud.php as shown below:

In the class Crud extends Model, please fill in the following variables:

protected $table = 'testingname';
protected $fillable = ['full_name', 'gender', 'address'];

testingname is the name of the table, full_name, gender and address is the name of the field in the table testingname. Look at the following picture:

NOTE:

Laravel has a feature called Eloquent. With this feature, we can easily manipulate the database. In Eloquent there are several special attributes. Some of them that we are currently using are $table and $fillable.
-> $table is special variable used to register table names
-> $fillable is special variable used to register data to the field
Both variables ($table and $fillable) will run when we call create() on the controller.

Naming the name on the input form should be the same as the field name, so that the data entered into $fillable will match the field. For example, in the form input name we give name=”full_name” and in the $fillable variable we use full_name for the field name

The model has been completed. To be able to connect the model into the controller, we must add the path address of the model to CrudController.php:

use App\Models\Crud;

So that the data can be saved to the database, we have to add some code inside the create function in the CrudController.php file. copy the following code:

Crud::create($request->all());
return redirect('/crud')->with('success', 'Insert data successfully');

you will see changes like this:

CRUD Laravel Beginner Guide Step By Step

How to read the line “Crud::create($request->all());” are:

Access the Crud class in the Crud Model file, then run the create($request->all()) function to save all the data in the $table and $fillable variables to the database. By default you don’t see the SQL command here to save data to the database, because the SQL function has been in the create() function.

CREATE: Insert Data

Now, back to browser at http://127.0.0.1:8000/crud, and enter any data. For example I fill in some data and press the Save button.

After pressing the Save button, now open http://localhost/phpmyadmin. As in the picture below, the data written on the form has been successfully entered into the database.

CRUD Laravel Beginner Guide Step By Step
CRUD Laravel Beginner

READ

READ: Edit Controller

To retrieve data from database in Laravel is very easy. Now open the CrudController.php file, then you go to the index function. Please change the line return view(‘crudpage’); with the following two lines of code:

$getData = Crud::all();
return view('crudpage', ['data' => $getData]);

So it will be like this:

CRUD Laravel Beginner Guide Step By Step

Look at line 13 above, where we will use the Crud::all() command to retrieve all data from the database and store it in the $getData variable.

Then, on line 14, the data in the $getData variable will be copied to the alias ‘data‘.

This ‘data‘ alias later on the view page (crudpage.blade.php) will become a $data variable. By $data will do foreach() to split the data and retrieve it one by one.

READ: Edit View File

Now let’s go to crudpage.blade.php file. On this file all data from the database will be displayed.

The data will be displayed in table format. Now, go to crudpage.blade.php, under </form> add the following code:

<br>
    <table>
        <tr>
            <th>Name</th>
            <th>Gender</th>
            <th>Address</th>
        </tr>

        @foreach($data as $d)
        <tr>
            <td>{{$d->full_name}}</td>
            <td>{{$d->gender}}</td>
            <td>{{$d->address}}</td>
        </tr>
        @endforeach

    </table>

After that, reload the address http://127.0.0.1:8000/crud and you should see results like this:

CRUD Laravel Beginner Guide Step By Step

For the moment, we don’t use CSS, it’s all pure html so that you newbies can understand how Laravel works on CRUD websites.

UPDATE

UPDATE: Add Edit Button

To update data, we must add an edit button on each data. To do that, in the table on the view page crudpage.blade.php, please add the following code:

<td><a href="/crud/{{$d->id}}/edit">Edit</a></td>

So it will be like in the following:

CRUD Laravel Beginner Guide Step By Step

After that, reload the address http://127.0.0.1:8000/crud and you should see results like this:

UPDATE: Add Edit Route

Later, when we click “Edit”, Laravel will direct us to the “/edit” page and will display an update form. To do that, we will add a route to define the “/edit” address.

Open the web.php file, then add the following route line:

Route::get('/crud/{id}/edit', [CrudController::class, 'edit']);

You’ll see it look like this:

This route will take us to the CrudController and will run the edit function. For that, let’s create an edit function in the controller.

UPDATE: Add Edit Function in Controller

Now, open the CrudController.php file, then add the following code:

 public function edit($id)
    {
        $getDataById = Crud::find($id);
        return view('/edit', ['d' => $getDataById]);
    }

If you see Inside this function, there is a command Crud::find($id). find() is laravel default command to get data by id. Then the data will be stored in the $getDataById variable. The data will be sent to the edit view page and stored in the alias ‘d’ name.

UPDATE: Add Edit View File

Since we will display the edit form on a different page from the input form, we will create a view file named edit.blade.php. Right-click on the resources -> views then New File and name it edit.blade.php and fill it with the following program lines:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Edit Page</title>
</head>

<body>
    <h1>EDIT PAGE</h1>

    <form action="/crud/{{$d->id}}/update" method="post">
        {{csrf_field()}}
        <input type="text" id="full_name" name="full_name" value="{{$d->full_name}}">
        <br>
        <br>
        <input type="text" id="gender" name="gender" value="{{$d->gender}}">
        <br>
        <br>
        <input type="text" id="address" name="address" value="{{$d->address}}">
        <br>
        <br>
        <input type="submit" value="Save">
    </form>
</body>

</html>

Then it will look like this:

Now, reload the address http://127.0.0.1:8000/crud and click “Edit” on the data, it will open a new page like the following:

When the Save button is pressed, it will redirect to the address “/update“. But it can not work because there is no route. For that let’s create a route “/update“.

UPDATE: Add Update Route

Reopen the web.php file in the routes folder. Then add the following line of code:

Route::post('/crud/{id}/update', [CrudController::class, 'update']);

This route will direct us to the update function in the CrudController controller. Let’s create an update function.

UPDATE: Add Update Function In Controller

Open the CrudController.php file, then add the following line of function:

public function update(Request $request, $id)
    {
        $getDataById = Crud::find($id);
        $getDataById->update($request->all());
        return redirect('/crud');
    }

Then it will look like this:

CRUD Laravel Beginner Guide Step By Step

Now, you can test your data by editing or updating. You will see the changes.

Now, how about to deleting data?

DELETE

DELETE: Add Delete Button

To be able to delete data, we need to add a delete button on each data. This is similar to the Edit button above. We will add in crudpage.blade.php with the code:

<td><a href="/crud/{{$d->id}}/delete" onclick="return confirm('Are you sure?')">Delete</a></td>

Look at the following picture:

CRUD Laravel Beginner Guide Step By Step

DELETE: Add Route Delete

When we click the delete button, our website will lead to the address “/delete“. Therefore, we have to add route delete in the web.php file with the following code:

Route::get('/crudTest/{id}/delete', [CrudtestController::class, 'delete']);

See the following image:

CRUD Laravel Beginner Guide Step By Step

DELETE: Add Delete Function in Controller

We have to add a function in the CrudController.php file to delete data. Then add it with the following code:

public function delete($id)
    {
        $getDataById = Crud::find($id);
        $getDataById->delete();
        return redirect('/crud');
    }

See the following image:

CRUD Laravel Beginner Guide Step By Step

Done.

Now, your CRUD Laravel Beginner hase been completed. I hope this CRUD Laravel Beginner Guide Step By Step article can be useful for you

Leave a Reply

Your email address will not be published.