Laravel 9 is the latest version of the Laravel framework, and it comes with a lot of new features and improvements. Here is a basic tutorial on how to create a CRUD (Create, Read, Update, Delete) application in Laravel 9:
- Create a new Laravel project:
composer create-project --prefer-dist laravel/laravel blog
- Create a new migration for the database table:
Copy codephp artisan make:migration create_tasks_table
- Define the fields for the tasks table in the migration file, located in the database/migrations directory:
Copy codepublic function up()
{
Schema::create('tasks', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->text('description');
$table->timestamps();
});
}
- Run the migration to create the tasks table in the database:
Copy codephp artisan migrate
- Create a new model for the tasks table:
Copy codephp artisan make:model Task
- Create a new controller for the tasks resource:
Copy codephp artisan make:controller TaskController --resource
- Define the methods for the CRUD operations in the TaskController:
Copy codepublic function index()
{
$tasks = Task::all();
return view('tasks.index', compact('tasks'));
}
public function create()
{
return view('tasks.create');
}
public function store(Request $request)
{
$validatedData = $request->validate([
'name' => 'required',
'description' => 'required'
]);
Task::create($validatedData);
return redirect('/tasks')->with('success', 'Task created successfully!');
}
public function show(Task $task)
{
return view('tasks.show', compact('task'));
}
public function edit(Task $task)
{
return view('tasks.edit', compact('task'));
}
public function update(Request $request, Task $task)
{
$validatedData = $request->validate([
'name' => 'required',
'description' => 'required'
]);
$task->update($validatedData);
return redirect('/tasks')->with('success', 'Task updated successfully!');
}
public function destroy(Task $task)
{
$task->delete();
return redirect('/tasks')->with('success', 'Task deleted successfully!');
}
- Create views for the tasks resource:
Copy coderesources/views/tasks/index.blade.php
resources/views/tasks/create.blade.php
resources/views/tasks/show.blade.php
resources/views/tasks/edit.blade.php
- Define routes for the tasks resource in the web.php file:
Copy codeRoute::resource('tasks', 'TaskController');
With this basic example, you should be able to create a simple CRUD application in Laravel