You can install Laravel 5.8 via a global installer or using the Composer Create-Project command.
composer create-project --prefer-dist laravel/laravel laravel58crud
Now, go inside the project and open the project in your favorite editor.
cd laravel58crud code .
#Step 1: Configure the MySQL Database
Now, first, in MySQL, you need to create the database, and then we need to connect that database to the Laravel application. You can also use phpmyadmin to create the database.
I have created a MySQL database called laravel58crud and now write the MySQL credentials inside the .env file. Before creating migrations, We will need to set up our database, assuming you know how to create a database using PHPMyAdmin.
After creating the database, we will add the database credentials to our application. Laravel has a .env environment file that will have all the sensitive data like database details, mail driver details, etc., because it’s not recommended to store such information directly inside the code (environment files are not limited to PHP. They are used in all other significant frameworks).
Values inside the .env files are loaded inside the files from the config directory. .env file is located at the root of our application.
Whenever you make changes to the .env file, then don’t forget to restart the server ( if you are using laravel dev server), and if you are using a virtual host and changes don’t seem to take effect, then just run php artisan config: clear (This command will clear the configuration cache) in your terminal.
DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE=laravel58crud DB_USERNAME=root DB_PASSWORD=root
So now, you will be able to connect to the MySQL database.
Laravel always ships with migration files, so you can generate the tables in the database using the following command.
php artisan migrate
We will create a CRUD operation on Books. So the user can create, read, update, and delete the books from the database. So, let’s create a model and migration files.
#Step 2: Create a model and migration files.
Since we have set up our database, now let’s take a look at database migrations. Migration is used to store the details about a database table and its properties, so you don’t have to manually create all the tables by going to the database interface or something like phpmyadmin.
We can develop migrations using artisan with the “make: migration” command.
Type the following command to create a model and migration files.
php artisan make:model Book -m
In laravel, the name of the model has to be singular, and the name of the migration should be plural so it can automatically find the table name. You can find these migration files in the database/migrations directory.
Laravel, by default, comes with two migrations, namely users and password_resets (all migration files are prepended with a timestamp), which are used for authentication.
If you want to create a migration but have a different table name in mind, then you can explicitly define the table name with “ — create” flag:
It will create a Book.php file and [timestamp]create_books_table.php migration file.
Now, open the migration file inside the database >> migrations >> [timestamp]create_books_table file and add the following schema inside it.
public function up() { Schema::create('books', function (Blueprint $table) { $table->bigIncrements('id'); $table->string('book_name'); $table->string('isbn_no'); $table->integer('book_price'); $table->timestamps(); }); }
When you open the create_books_table.php, you will see two methods, up() and down(). The up() is used for creating/updating tables, columns, and indexes. The down() method is used for reversing the operation done by the up() method.
Inside up() method, We have Schema: create(‘table_name’, callback) method, which will be used for creating a new table. Inside the callback, we have $table->bigIncrements(‘id’), which will create an auto_increment integer column with a primary key, and the argument ‘id’ is the name of the column.
Second one is $table->timestamps() which will create two timestamp columns created_at and updated_at. created_at will be filled when a row is created and updated_at when a row is updated.
We will add two columns, title, and body (for the sake of simplicity), but if you want to know the types of the available columns, then see the list.
Now, create a table in the database using the following command.
php artisan migrate
The above command will run the migrations and create all the tables. Then, it will execute the up() method.
If you want to reverse the migrations, you can use migrate: rollback command, which will execute down() method like php artisan migrate rollback.
So, in the database, the table is created successfully.
Now, add the fillable property inside the Book.php file.
// Book.php <?php namespace App; use Illuminate\Database\Eloquent\Model; class Book extends Model { protected $fillable = ['book_name', 'isbn_no', 'book_price']; }
We can specify properties to modify the behavior of a model. For example, we can write the $table property, which is used to determine the table’s name that this model will interact with.
By default, It will define the table name as the plural of the model name, e.g., books table for Book model and users table for the User model.
When you don’t want to use timestamps on your table, you will also have to specify the $timestamps property and set it to false in your Model because Laravel expects your table to have created_at and updated_at timestamp columns.
#Step 3: Create routes and controller
First, create the BookController using the following command.
php artisan make:controller BookController --resource
Note that we have also added a — resource flag which will define six methods inside the BookController, namely:
- Index (used for displaying a list of Books)
- Create (will show a view with a form for creating a Book)
- Store (used for creating a Book inside the database. Note: create method submits to store method)
- Show (will display a specified Book)
- Edit (will show a form for editing a Book. Form will be filled with the existing Book data)
- Update (Used for updating a Book inside the database. Note: edit submits to update method)
- Destroy (used for deleting a specified Book)
Now, inside routes >> web.php file, add the following line of code.
<?php // BookController.php Route::get('/', function () { return view('welcome'); }); Route::resource('books', 'BookController');
We can pass dynamic parameters with {} brackets, and you might have noticed that show, update, and destroy has the same URL but different methods, so it’s legit. Just like — resource flag, laravel has a method called resource() that will generate all the above routes.
You can also use that method instead of specifying them individually like above.
Actually, by adding the following line, we have registered multiple routes for our application. We can check it using the following command.
php artisan route:list
Okay, now open the BookController.php file, and you can see that all the functions declarations are there.
<?php // BookController.php namespace App\Http\Controllers; use Illuminate\Http\Request; class BookController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { // } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { // } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { // } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show($id) { // } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function edit($id) { // } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update(Request $request, $id) { // } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { // } }
#Step 4: Create the views
Inside resources >> views folder, create the following three files.
- create.blade.php
- edit.blade.php
- index.blade.php
Also, inside the views folder, we need to create a layout file. So create one file inside the views folder called layout.blade.php. Add the following code inside the layout.blade.php file.
<!-- layout.blade.php --> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Laravel 5.8 CRUD Example Tutorial</title> <link href="{{ asset('css/app.css') }}" rel="stylesheet" type="text/css" /> </head> <body> <div class="container"> @yield('content') </div> <script src="{{ asset('js/app.js') }}" type="text/js"></script> </body> </html>
So basically, this file is our main template file, and all the other view files will extend this file. Here, we have already included Bootstrap 4 by adding the app.css.
The next step would be to code the create.blade.php file. So write the following code inside it.
<!-- create.blade.php --> @extends('layout') @section('content') <style> .uper { margin-top: 40px; } </style> <div class="card uper"> <div class="card-header"> Add Book </div> <div class="card-body"> @if ($errors->any()) <div class="alert alert-danger"> <ul> @foreach ($errors->all() as $error) <li>{{ $error }}</li> @endforeach </ul> </div><br /> @endif <form method="post" action="{{ route('books.store') }}"> <div class="form-group"> @csrf <label for="name">Book Name:</label> <input type="text" class="form-control" name="book_name"/> </div> <div class="form-group"> <label for="price">Book ISBN Number :</label> <input type="text" class="form-control" name="isbn_no"/> </div> <div class="form-group"> <label for="quantity">Book Price :</label> <input type="text" class="form-control" name="book_price"/> </div> <button type="submit" class="btn btn-primary">Create Book</button> </form> </div> </div> @endsection
Okay, now we need to open the BookController.php file, and on the create function, we need to return a view, which is the create.blade.php file.
// BookController.php public function create() { return view('create'); }
Save the file and start the Laravel development server using the following command.
php artisan serve
Go to the http://localhost:8000/books/create.
You can see something like this.
#Step 5: Add Validation rules and save data
In this step, we will add the Laravel Validation.
Now, the first step inside the BookController.php is that import the namespace of the Book model inside the BookController.php file.
// BookController.php <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Book;
Now, write the following code inside the BookController.php file’s store() function.
// BookController.php public function store(Request $request) { $validatedData = $request->validate([ 'book_name' => 'required|max:255', 'isbn_no' => 'required|alpha_num', 'book_price' => 'required|numeric', ]); $book = Book::create($validatedData); return redirect('/books')->with('success', 'Book is successfully saved'); }
Here, what we have done is first check for all three fields of the form.
If the incoming data fails any of the rules, then it will directly go to the form with the error messages.
The store method has a $request object as a parameter that will be used to access form data. The first thing you want to do is validate the form data. We can use the $request->validate() method for validation, which will receive an array of validation rules.
Validation rules are an associative array. Key will be the field_name and value with being the validation rules. The second parameter is an optional array for custom validation messages. Rules are separated with the pipe sign “|.”
We are using the most basic validation rules. First is “required,” which means the field_name should not be empty (the “nullable” rule is vice versa), “string” means it should be a string value, “min” is the limit of minimum characters for a string in an input field and “max” is the maximum characters. “unique: table, column” with seeing if the same value does not exists in the database (comes handy for storing emails or any other unique data).
If validation fails, then it will redirect us back. After validation, we are creating a new book and save that book in the database.
We need to loop through the error messages inside the create.blade.php file, which we have already done it.
If you leave all the form fields empty, you will find an error message like this image.
Now, if you fill the form fields correctly, then it will create a new row in the database. Thus, I have created a new book.
Some Methods for accessing form-data:
$request->input('field_name'); // access an input field
$request->has('field_name'); // check if field exists
$request->title; // dynamically access input fields
request('key') // you can use this global helper if needed inside a view
Helpful redirecting methods:
return redirect('/books'); // to a specific url
return redirect(url('/books')); // to a specific url with url helper
return redirect(url()->previous()); // to a previous url
return redirect()->back(); // redirect back (same as above)
#Step 6: Display the data.
We need to write the BookController’s index function to return the index view with the data fetched from the database. Write the following code inside the index() function.
// BookController.php public function index() { $books = Book::all(); return view('index', compact('books')); }
Okay, now create the file called index.blade.php inside the views folder and add the following code.
<!-- index.blade.php --> @extends('layout') @section('content') <style> .uper { margin-top: 40px; } </style> <div class="uper"> @if(session()->get('success')) <div class="alert alert-success"> {{ session()->get('success') }} </div><br /> @endif <table class="table table-striped"> <thead> <tr> <td>ID</td> <td>Book Name</td> <td>ISBN Number</td> <td>Book Price</td> <td colspan="2">Action</td> </tr> </thead> <tbody> @foreach($books as $book) <tr> <td>{{$book->id}}</td> <td>{{$book->book_name}}</td> <td>{{$book->isbn_no}}</td> <td>{{$book->book_price}}</td> <td><a href="{{ route('books.edit',$book->id)}}" class="btn btn-primary">Edit</a></td> <td> <form action="{{ route('books.destroy', $book->id)}}" method="post"> @csrf @method('DELETE') <button class="btn btn-danger" type="submit">Delete</button> </form> </td> </tr> @endforeach </tbody> </table> <div> @endsection
Here, we have looped through the books array and display the data in the tabular format.
Also, we have added two buttons for the edit and delete operation.
#Step 7: Create Edit and Update Operation
First, we need to add the following code inside the BookController.php file’s edit function.
// BookController.php public function edit($id) { $book = Book::findOrFail($id); return view('edit', compact('book')); }
Now, create a new file inside the views folder called edit.blade.php and add the following code.
<!-- edit.blade.php --> @extends('layout') @section('content') <style> .uper { margin-top: 40px; } </style> <div class="card uper"> <div class="card-header"> Edit Book </div> <div class="card-body"> @if ($errors->any()) <div class="alert alert-danger"> <ul> @foreach ($errors->all() as $error) <li>{{ $error }}</li> @endforeach </ul> </div><br /> @endif <form method="post" action="{{ route('books.update', $book->id) }}"> <div class="form-group"> @csrf @method('PATCH') <label for="name">Book Name:</label> <input type="text" class="form-control" name="book_name" value="{{$book->book_name}}"/> </div> <div class="form-group"> <label for="price">Book ISBN Number :</label> <input type="text" class="form-control" name="isbn_no" value="{{$book->isbn_no}}"/> </div> <div class="form-group"> <label for="quantity">Book Price :</label> <input type="text" class="form-control" name="book_price" value="{{$book->book_price}}"/> </div> <button type="submit" class="btn btn-primary">Update Book</button> </form> </div> </div> @endsection
In this file, you can show the values of the particular row using its unique id inside the form fields.
So, when you hit this URL: http://localhost:8000/books/1/edit, you will see something like the below image.
Now, add the following code inside the BookController’s update() function.
// BookController.php public function update(Request $request, $id) { $validatedData = $request->validate([ 'book_name' => 'required|max:255', 'isbn_no' => 'required|alpha_num', 'book_price' => 'required|numeric', ]); Book::whereId($id)->update($validatedData); return redirect('/books')->with('success', 'Book is successfully updated'); }
So now, you can edit and update the data into the database successfully.
#Step 8: Create Delete Functionality
Write the following code inside the BookController’s destroy function.
// BookController.php public function destroy($id) { $book = Book::findOrFail($id); $book->delete(); return redirect('/books')->with('success', 'Book is successfully deleted'); }
Now, go to this URL: http://localhost:8000/books and try to delete the book.
You can see that you have successfully deleted the book.
So, our complete BookController.php code looks like below.
<?php // BookController.php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Book; class BookController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { $books = Book::all(); return view('index', compact('books')); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { return view('create'); } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { $validatedData = $request->validate([ 'book_name' => 'required|max:255', 'isbn_no' => 'required|alpha_num', 'book_price' => 'required|numeric', ]); $book = Book::create($validatedData); return redirect('/books')->with('success', 'Book is successfully saved'); } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show($id) { // } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function edit($id) { $book = Book::findOrFail($id); return view('edit', compact('book')); } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update(Request $request, $id) { $validatedData = $request->validate([ 'book_name' => 'required|max:255', 'isbn_no' => 'required|alpha_num', 'book_price' => 'required|numeric', ]); Book::whereId($id)->update($validatedData); return redirect('/books')->with('success', 'Book is successfully updated'); } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { $book = Book::findOrFail($id); $book->delete(); return redirect('/books')->with('success', 'Book is successfully deleted'); } }
So, we have completed a Laravel 5.8 CRUD operations tutorial with an example from scratch.
If you are interested in the FrontEnd framework like Vue.js, check out my Vue Laravel CRUD example and Angular Laravel Tutorial Example.
I have put this code on Github so you can check it out as well.
Thanks for the clear and concise tutorial.
thanks ….
it helped me a lot
Clear and concise. Thank you.
Hello
Thank you so much, have really learned a lot
Krunal,
Great tutorial, not too complex, does exactly what it says. Has been a go-to reference work while developing an intranet for my employer.
Just to let you know, there are a couple of typos in the edit.blade.php code in step 7, the labels for isbn_no and book_price are for ‘price’ and ‘quantity’ respectively (rather than ‘isbn_no’ and ‘book_price’).
Nice tutorial especially for those who are beginners. Thanks for sharing this informative article of Laravel programming. Lots of things are to be learned about in this. Keep up the good work.
Awesome. Thank you for this tutorial. I’ve learned a lot and I just bookmarked this page. Coming from Node.js, it was not really difficult to follow along. I realize that things are so similar.
Very good tutorial for begineers.
Method validate does not exist.
Thanks for the tutorial! 😀
I hope you can create tutorial about creating API using laravel
please send me at raijin.ec@gmail.com
Hi,
I am looking a tutorial on Laravel which provide interface to both web and mobile along with authentication.
Thanks
thank you guys
Thanks of This Simple Tutorial.
Thank you, you really helped me with this tutorial.
how to order by id desc?
BookController Book::all();
I found your article and it works for me,i recommend this basic crud tutorial for all newbie in laravel.You make this tutorial more clearly and easy .Keep it up bro
Hi there to every one, the contents existing at this website are actually
amazing for people knowledge, well, keep up the good work fellows.
Hi, I find that the data inputs disappear when validation fails and the user is returned to the form.
My issue is here https://stackoverflow.com/questions/61062666/how-can-i-return-to-a-form-after-request-validate-errors-with-the-input-data