Add And Store Data In Laravel 8

Parami Liyanapathirana
2 min readJan 21, 2022
Photo by Mohammad Rahmani on Unsplash

Hii Everyone,

Today, I talk about how to store data from form to database by using Laravel.

Laravel is a famous PHP web development framework.

We all know Laravel is based on MVC architecture. MVC means

M-model

V-view

C-controller

As an example, I use a Library management system. Librarian enter detail of books and the detail stored in the database.

View, controller, and model are named as follows.

addBooks.blade.php ->view

Books.php -> model

BooksController.php -> controller

Screenshot by author

I used Visual Studio Code as a code editor.

1. Model

In my database, a book has the following properties.

Name, Author, Publisher, File

php artisan make:model Books

‘Books’ is my model name.

id is the primary key of our table. it is an auto-increment variable.

$fillable — all fields in the database can change at once when updating.

Create a route for adding data.

It is the get method. “add ” is the function name of our controller.

Then create the route for storing data.

It is the post method. “store ” is the function name of our controller.

GET and POST methods are common usually used HTTP methods. POST method sends data to the database.

GET method requests data.

Migration file

2. Controller

PHP artisan make: model NAME -m -cr

The above command is used for creating a model, controller, migration.

We must import our model to BooksController.php

use App\Models\Books;

I create a folder in resources named ‘pdfs’.

‘move(‘pdfs’,$filename)’ in 7 lines means we pass the file to the ‘pdfs’ folder.

‘$data->save();’ in line 12 all data store in our database.

‘return redirect(‘/’);’ in 13 line means after finished storing again connect to welcome page.

3. View

So I created a form to collect the data.

We upload books as pdf or documents or word files. Because we must use enctype=” multipart/form-data” to upload files. our form method is “post”.

So we want to upload the file because the input type of that element is the file.

We can use Bootstrap for creating the form also. I use it to get blue color in Add button.

Screenshot by author

Thanks for reading!

--

--

Parami Liyanapathirana

Undergraduate of Faculty Of Information Technology, University Of Moratuwa.