Laravel 7 CRUD is the essential operation to learn laravel step by step for beginners. Let’s see how to build small web applications that insert, read, update, and delete data from a database. We can upgrade your old versions by going to this link.
Laravel 7 crud project overview
Step 1: Install Laravel 7.
Step 2: Configure a MySQL database.
Step 3: Create routes and migration files.
Step 4: Create the model, route, controller, and view file.
Step 5: Configure the bootstrap and create the views for Laravel
Step 6: Display the data to the frontend.
Step 7: Edit and update a data to a database.
Step 8: Write a logic to delete the data from a database inside the controller file.
Now, go inside the laravel7crud folder. You need to install the frontend dependencies for frontend scaffolding using the following command.
cd laravel7crud
npm install
Step 2: Configure the MySQL Database
I have created the MySQL database called laravel7crud and now write the MySQL credentials inside the .env file. Before creating the migrations, we need to set up the MySQL database, assuming you know how to create a database using PHPMyAdmin.
My .env config for MySQL Database is the following.
Please don’t write your username and password other then .env file because it is created for putting secret credentials.
Sponsored Content
Recommended byLaravel always ships with default migration files, so you able to generate the tables in the database using the following command.
php artisan migrate
If you find an error like: [Illuminate\Database\QueryException]SQLSTATE[42000]: Syntax error or access violation: 1071 Specified key was too long; max key length is 767 bytes (SQL: alter table users add unique users_email_unique(email))
Then you should follow the below steps.
Here what you have to do is, edit your AppServiceProvider.php file, and inside the boot, the method sets a default string length.
use Illuminate\Support\Facades\Schema;
public function boot()
{
Schema::defaultStringLength(191);
}
We have already set up MySQL database, now let’s look at the database migrations. Migration is used to save the details in the database table, and it’s the properties, so you don’t have to manually generate all the tables by going to a database interface or something like phpmyadmin.
We can create the migrations using artisan with “make: migration” command.
Type the following command to create the model and migration files.
php artisan make:model Corona -m
In laravel, the name of the model has to be singular, and the name of a migration should be the plural so it can automatically find the table name.
It will create the Corna.php file and [timestamp]create_coronas_table.php migration file.
Now, write the following code inside [timestamp]create_coronas_table.php file.
public function up()
{
Schema::create('coronas', function (Blueprint $table) {
$table->id();
$table->string('country_name');
$table->string('symptoms');
$table->integer('cases');
$table->timestamps();
});
}
One thing which specifically changes from Laravel 6 to Laravel 7 is that now we explicitly define id() column name, which means it is the primary key and automatically auto-increment sets to 1.
Now, again run the migration using the following command.
If you need to reverse the migrations, you can use a migrate: rollback command, which will execute the down() function like php artisan migrate:rollback.
Now, add the fillable property inside the Corona.php file.
<?php
// Corona.php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Corona extends Model
{
protected $fillable = ['country_name', 'symptoms', 'cases'];
}
We can specify all the properties to modify the behavior of a model.
We can write the $table property, which is used to determine the name of the table that this model will interact with future operations.
Step 3: Create routes and controller
Now, we need to create a controller.
First, create the CoronaController using the following command.
Just like — resource flag, laravel has the method called resource() that will generate all the above routes. You can also use the method instead of specifying them individually like above.
Actually, by adding the following code line, we have registered the multiple routes for our app. We can check it using the following command.
Okay, now we need to open the CoronaController.php file, and on the create() method, we need to return the view, and that is the create.blade.php file.
// CoronaController.php
public function create()
{
return view('create');
}
Go to a http://localhost:8000/coronas/create or http://laravel7crud.test/coronas/create
Now, add the CoronaController.php is that import the namespace of the Corona model inside the CoronaController.php file.
<?php
// CoronaController.php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Corona;
Now, write the following code inside the CoronaController.php file’sstore() function.
// CoronaController.php
public function store(Request $request)
{
$validatedData = $request->validate([
'country_name' => 'required|max:255',
'symptoms' => 'required',
'cases' => 'required|numeric',
]);
$show = Corona::create($validatedData);
return redirect('/coronas')->with('success', 'Corona Case is successfully saved');
}
Here, what we have done is, first check for all four fields of the form.
If the incoming data fail 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 which will be used to access form data.
The first thing you want to do is validate the form of data.
We can use the $request->validate() function for validation, which will receive the array of validation rules.
Validation rules[] is the 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 a pipe sign “|.” We are using the most basic validation rules.
If the validation fails, then it will redirect back to the form page with error messages. After the validation, we are creating the new case and save that case in the database.
We need to loop through that error messages inside the create.blade.php file, which we have already done it.
If you leave all the form fields empty, then you will find the error message like this image.
Now, if you fill the form fields correctly, then it will create a new row in the database. I have created a new Case.
Step 7: Display the data
Now, we need to write the CoronaController’s index function to return the index view with data fetched from the database. Write the following code inside the index() function.
// CoronaController.php
public function index()
{
$coronacases = Corona::all();
return view('index', compact('coronacases'));
}
Okay, now create a file called index.blade.php inside the views folder and add the following code.
Go to any edit page of the listing data. Like, go to the: http://laravel7crud.test/coronas/1/edit or whatever URL of yours.
Now, add the following code inside the CoronaController’s update() function.
// CoronaController.php
public function update(Request $request, $id)
{
$validatedData = $request->validate([
'country_name' => 'required|max:255',
'symptoms' => 'required',
'cases' => 'required|numeric',
]);
Corona::whereId($id)->update($validatedData);
return redirect('/coronas')->with('success', 'Corona Case Data is successfully updated');
}
So now, you can update all the data into the database.
Step 9: Create Delete Functionality
Write the following code inside the CoronaController’s destroy function.
// CoronaController.php
public function destroy($id)
{
$coronacase = Corona::findOrFail($id);
$coronacase->delete();
return redirect('/coronas')->with('success', 'Corona Case Data is successfully deleted');
}
Go to the URL: http://laravel7crud.test/coronas and try to remove the Corona Case data.
You can see that you have successfully removed the case.
So, our complete CoronaController.php code looks like below.
<?php
// CoronaController.php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Corona;
class CoronaController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$coronacases = Corona::all();
return view('index', compact('coronacases'));
}
/**
* 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([
'country_name' => 'required|max:255',
'symptoms' => 'required',
'cases' => 'required|numeric',
]);
$show = Corona::create($validatedData);
return redirect('/coronas')->with('success', 'Corona Case 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)
{
$coronacase = Corona::findOrFail($id);
return view('edit', compact('coronacase'));
}
/**
* 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([
'country_name' => 'required|max:255',
'symptoms' => 'required',
'cases' => 'required|numeric',
]);
Corona::whereId($id)->update($validatedData);
return redirect('/coronas')->with('success', 'Corona Case Data is successfully updated');
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
$coronacase = Corona::findOrFail($id);
$coronacase->delete();
return redirect('/coronas')->with('success', 'Corona Case Data is successfully deleted');
}
}
So, we have completed a Laravel 7 CRUD operations example from scratch.
If you are interested in the FrontEnd Javascript framework like Vue with Laravel or Angular with Laravel, then check out the guides like Vue Laravel CRUD example and Angular Laravel Tutorial Example.
I have put the whole crud operation code on Github so you can check it out as well.
I am using Laravel Valet to install Laravel 7, but if you are not using Valet, then also you can create the Laravel 7 project by updating the Composer globally.