laravel 9

Laravel 9 CRUD Application Tutorial Example

Pinterest LinkedIn Tumblr

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:

  1. Create a new Laravel project:
composer create-project --prefer-dist laravel/laravel blog
  1. Create a new migration for the database table:
Copy codephp artisan make:migration create_tasks_table
  1. 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();
    });
}
  1. Run the migration to create the tasks table in the database:
Copy codephp artisan migrate
  1. Create a new model for the tasks table:
Copy codephp artisan make:model Task
  1. Create a new controller for the tasks resource:
Copy codephp artisan make:controller TaskController --resource
  1. 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!');
}
  1. 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
  1. 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