Popular PHP web application framework Laravel is renowned for its beautiful syntax and resources for creating powerful web apps. Making a CRUD (Create, Read, Update, Delete) application is one of the most frequent tasks in web development, and Laravel makes it simple to do so. In this tutorial, we’ll go over how to create a straightforward CRUD application in Laravel. The scaffolding and required files for our application will be created using the command-line interface (CLI).
Install Laravel first
Installing Laravel is the first step in creating our CRUD application.
We’ll utilize the Laravel installer for this, which can be installed by issuing the command:
composer global require laravel/installer
Step 2: Create a new Laravel project
Once Laravel is installed, we can create a new project using the following command:
laravel new crud-app
This will create a new directory called “crud-app” that contains all of the necessary files for our application.
Step 3: Create a model and migration
In order to interact with a database, we need to create a model and a corresponding migration. In this example, we will create a model for “Task” and run the migration to create the necessary table in the database.
PHP artisan make:model Task -m
This command will create a new model called Task and a corresponding migration file in the “database/migrations” directory.
Step 4: Define the schema for the tasks table
Once the migration file is created, we can define the schema for the tasks table. In this example, we will keep it simple and only add a “name” and a “completed” field.
public function up()
{
Schema::create('tasks', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->boolean('completed')->default(0);
$table->timestamps();
});
}
Step 5: Run the migration
We may start the migration to construct the tasks table in the database once the schema has been defined.
php artisan migrate
Step 6: Create a controller
Now that the model and migration are set up, we can create a controller to handle the different actions of our CRUD application.
php artisan make:controller TaskController --resource
This command will create a new controller called TaskController with all the necessary methods for a CRUD application.
Step 7: Define routes
We need to define the routes for our application in the “web.php” file. This file is located in the “routes” directory.
Route::resource('tasks', 'TaskController');
This will create routes for the different actions of our CRUD application.
Step 8: Create views
Finally, we need to create views for our application. In this example, we will create a view for the “index” action that will display a list of tasks, a view for the “create” action that will allow the user to create a new task, and a view for the “edit” action that will allow the user to edit an existing task.
php artisan make:view tasks.