laravel 10 crud using ajax

laravel 10 crud using ajax

Laravel is a popular PHP framework that provides an easy way to build web applications. Laravel 10 is the latest version of the framework that offers several new features and enhancements. One of the most common operations in web applications is CRUD (Create, Read, Update, Delete). In this article, we will discuss how to implement Laravel 10 CRUD operations using AJAX.

Step 1: Set up Laravel 10 Firstly, you need to set up Laravel 10 on your local machine. You can install it via composer or download the source code from the official Laravel website. Once you have set up Laravel, create a new project using the following command:

laravel new laravel-ajax-crud

Step 2: Database Configuration Next, configure your database connection in the .env file. Laravel 10 uses the .env file to store the environment-specific configuration options such as database credentials. Open the .env file and update the following configuration options:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel_ajax_crud
DB_USERNAME=root
DB_PASSWORD=

Step 3: Model and Migration After configuring the database, create a new model and migration for the tasks table using the following command:

php artisan make:model Task -m

This command will create a new model and migration file in the app/Models directory and database/migrations directory, respectively.

Next, open the migration file and update the up method to add the necessary columns to the tasks table:

Schema::create('tasks', function (Blueprint $table) {
    $table->id();
    $table->string('title');
    $table->text('description')->nullable();
    $table->timestamps();
});

Step 4: Controller and Routes Now, create a new controller for the Task model using the following command:

php artisan make:controller TaskController

Next, open the TaskController and add the following methods to perform CRUD operations:

use App\Models\Task;

public function index()
{
    $tasks = Task::latest()->paginate(5);

    return view('tasks.index', compact('tasks'))
        ->with('i', (request()->input('page', 1) - 1) * 5);
}

public function store(Request $request)
{
    $request->validate([
        'title' => 'required',
        'description' => 'nullable',
    ]);

    Task::create($request->all());

    return response()->json(['success' => 'Task created successfully.']);
}

public function edit(Task $task)
{
    return response()->json($task);
}

public function update(Request $request, Task $task)
{
    $request->validate([
        'title' => 'required',
        'description' => 'nullable',
    ]);

    $task->update($request->all());

    return response()->json(['success' => 'Task updated successfully.']);
}

public function destroy(Task $task)
{
    $task->delete();

    return response()->json(['success' => 'Task deleted successfully.']);
}

Next, define the routes for these methods in the routes/web.php file:

use App\Http\Controllers\TaskController;

Route::resource('tasks', TaskController::class);

Step 5: Blade Template Next, create a new Blade template for the index method using the following command:

php artisan make:view tasks.index

php artisan make:view tasks.index

blade.php` file and add the following HTML code to display the tasks list and form to create and update tasks:

<div class="container">
    <div class="row">
        <div class="col-lg-12">
            <div class="pull-right">
                <button type="button" class="btn btn-success" data-toggle="modal" data-target="#createTaskModal">
                    Create Task
                </button>
            </div>
        </div>
    </div>
    <br>

    <table class="table table-bordered">
        <thead>
            <tr>
                <th>Title</th>
                <th>Description</th>
                <th width="280px">Action</th>
            </tr>
        </thead>
        <tbody>
            @foreach ($tasks as $task)
            <tr>
                <td>{{ $task->title }}</td>
                <td>{{ $task->description }}</td>
                <td>
                    <a class="btn btn-primary edit-task" data-id="{{ $task->id }}">Edit</a>
                    <a class="btn btn-danger delete-task" data-id="{{ $task->id }}">Delete</a>
                </td>
            </tr>
            @endforeach
        </tbody>
    </table>

    {!! $tasks->links() !!}
</div>

<!-- Create Task Modal -->
<div class="modal fade" id="createTaskModal" tabindex="-1" role="dialog" aria-labelledby="createTaskModalLabel">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title" id="createTaskModalLabel">Create Task</h4>
            </div>
            <div class="modal-body">
                <form id="create-task-form" name="create-task-form">
                    <div class="form-group">
                        <label for="title">Title</label>
                        <input type="text" name="title" id="title" class="form-control" required>
                    </div>
                    <div class="form-group">
                        <label for="description">Description</label>
                        <textarea name="description" id="description" class="form-control"></textarea>
                    </div>
                    <div class="form-group">
                        <button type="submit" class="btn btn-success">Create</button>
                        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

<!-- Edit Task Modal -->
<div class="modal fade" id="editTaskModal" tabindex="-1" role="dialog" aria-labelledby="editTaskModalLabel">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title" id="editTaskModalLabel">Edit Task</h4>
            </div>
            <div class="modal-body">
                <form id="edit-task-form" name="edit-task-form">
                    <input type="hidden" name="task_id" id="task_id">
                    <div class="form-group">
                        <label for="edit-title">Title</label>
                        <input type="text" name="title" id="edit-title" class="form-control" required>
                    </div>
                    <div class="form-group">
                        <label for="edit-description">Description</label>
                        <textarea name="description" id="edit-description" class="form-control"></textarea>
                    </div>
                    <div class="form-group">
                       
<button type="submit" class="btn btn-success">Update</button>
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
</div>
</form>
</div>
</div>
</div>

</div>

In the above code, we are displaying the tasks in a table format using the `@foreach` loop. We are also creating two modals – one for creating a new task and one for editing an existing task.

Next, we need to create a JavaScript file to handle the AJAX requests. Create a new file called app.js inside the public/js directory and add the following code to it:

$(document).ready(function () {

    // Create Task
    $('#create-task-form').on('submit', function (event) {
        event.preventDefault();
        var formData = $(this).serialize();
        $.ajax({
            url: '{{ route("tasks.store") }}',
            type: 'POST',
            data: formData,
            success: function (data) {
                $('#createTaskModal').modal('hide');
                location.reload();
            }
        });
    });

    // Edit Task
    $('body').on('click', '.edit-task', function () {
        var task_id = $(this).data('id');
        $.get('{{ route("tasks.index") }}/' + task_id + '/edit', function (data) {
            $('#edit-task-form').find('#task_id').val(data.id);
            $('#edit-task-form').find('#edit-title').val(data.title);
            $('#edit-task-form').find('#edit-description').val(data.description);
            $('#editTaskModal').modal('show');
        });
    });

    // Update Task
    $('#edit-task-form').on('submit', function (event) {
        event.preventDefault();
        var task_id = $('#edit-task-form').find('#task_id').val();
        var formData = $(this).serialize();
        $.ajax({
            url: '{{ route("tasks.index") }}/' + task_id,
            type: 'PUT',
            data: formData,
            success: function (data) {
                $('#editTaskModal').modal('hide');
                location.reload();
            }
        });
    });

    // Delete Task
    $('body').on('click', '.delete-task', function () {
        var task_id = $(this).data('id');
        if (confirm("Are you sure you want to delete this task?")) {
            $.ajax({
                url: '{{ route("tasks.index") }}/' + task_id,
                type: 'DELETE',
                success: function (data) {
                    location.reload();
                }
            });
        }
    });
});

In the above code, we are using jQuery to handle the AJAX requests. We have added event listeners for the create, edit, and delete buttons.

Finally, we need to update our web.php file to define the routes for our CRUD operations. Open the routes/web.php file and add the following code to it:

Route::resource('tasks', 'TaskController');

In the above code, we are using Laravel’s Route::resource() method to define the routes for our CRUD operations.

That’s it! We have now implemented a basic CRUD system for tasks using Laravel 10 and AJAX. You can run the application using the following command:

php artisan serve

Visit http://localhost:8000/tasks in your web browser to see the application in action.

Note: Remember to run the migration to create the tasks table in your database before running the application. You can do this by running the following command:

Conclusion In this article, we have learned how to create a simple CRUD system using Laravel 10 and AJAX. We have used Laravel’s built-in routing and controller features to handle the HTTP requests, and jQuery to handle the AJAX requests.

By using AJAX, we can create a more responsive and dynamic user experience. Instead of reloading the entire page, we can update only the necessary parts of the page using JavaScript.

FAQ : laravel 10 crud using ajax

Q1: What is Laravel?
Ans: Laravel is a popular PHP web framework that offers an elegant syntax and a variety of helpful tools and features for building web applications.

Q2: What is CRUD?
Ans: CRUD stands for Create, Read, Update, and Delete. It’s a set of operations commonly used in web applications for managing data.

Q3: What is AJAX?
Ans: AJAX stands for Asynchronous JavaScript and XML. It’s a technique used to send and receive data from a web server without refreshing the entire web page.

Q4: How can I create CRUD operations in Laravel 10 using AJAX?
Ans: Here are the general steps to create CRUD operations using AJAX in Laravel 10:

  • Create a new Laravel project or use an existing one.
  • Set up a database connection in your .env file and run migrations to create the necessary tables.
  • Create a model for the data you want to manage.
  • Create a controller with methods for each of the CRUD operations you want to perform.
  • Create routes to point to each of the controller methods.
  • Create the views for your CRUD operations using HTML, CSS, and JavaScript. Use AJAX to send requests to your controller methods.
  • Test your application and make any necessary adjustments.
  • There are many tutorials and resources available online that can guide you through the process of creating CRUD operations using AJAX in Laravel 10.

This Article Ideas has been taken from the following websites; which are following:

Simple Ajax CRUD Application in Laravel

https://techsolutionstuff.com/post/how-to-create-ajax-crud-operation-in-laravel-10

Laravel 9 Ajax CRUD Tutorial Example

Laravel 10 Ajax CRUD Example

https://websolutionstuff.com/post/laravel-10-ajax-crud-operations-example

FAQ : laravel 10 crud using ajax

Q1: What is Laravel 10 ?
Ans: Laravel is a popular PHP web framework that offers an elegant syntax and a variety of helpful tools and features for building web applications.

Q2: What is CRUD?
Ans: CRUD stands for Create, Read, Update, and Delete. It’s a set of operations commonly used in web applications for managing data.

Q3: What is AJAX?
Ans: AJAX stands for Asynchronous JavaScript and XML. It’s a technique used to send and receive data from a web server without refreshing the entire web page.

Q4: How can I create CRUD operations in Laravel 10 using AJAX?
Ans: Here are the general steps to create CRUD operations using AJAX in Laravel 8:

  • Create a new Laravel project or use an existing one.
  • Set up a database connection in your .env file and run migrations to create the necessary tables.
  • Create a model for the data you want to manage.
  • Create a controller with methods for each of the CRUD operations you want to perform.
  • Create routes to point to each of the controller methods.
  • Create the views for your CRUD operations using HTML, CSS, and JavaScript. Use AJAX to send requests to your controller methods.
  • Test your application and make any necessary adjustments.

There are many tutorials and resources available online that can guide you through the process of creating CRUD operations using AJAX in Laravel 10.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *