paduraruionutandrei
6 months ago

Laravel and ajax

Posted 6 months ago by paduraruionutandrei

Hello guys, I have a doubt.I am newbie in Laravel and ajax calls.I just made a simple basic crud, but I don't know if what I did, its pretty ok and not a messy thing.Can you review my code, and tell me your opinion and how can I improve this.I have only 4 days of hard working :).

Blades

@extends('layouts.app')

@section('content')
    <div class="container">

        @include('partials.nav')

        <div class="row justify-content-center">
            <div class="col-md-8">
                <div class="card">
                    <div class="card-header">Folders</div>

                    <div class="card-body">
                        <!-- Button trigger modal -->
                        <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal">
                            Create folder
                        </button>

                        <!-- Modal -->
                        <div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
                            <div class="modal-dialog" role="document">
                                <div class="modal-content">
                                    <div class="modal-header">
                                        <h5 class="modal-title" id="exampleModalLabel">Create</h5>
                                        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                            <span aria-hidden="true">&times;</span>
                                        </button>
                                    </div>
                                    <div class="modal-body">
                                        <form id="create-folder-form">
                                            @csrf

                                            <div class="form-group">
                                                <label for="name">Name</label>
                                                <input type="text" class="form-control" name="name" id="name">
                                            </div>

                                            <div class="form-group">
                                                <button type="button" class="btn btn-primary" id="create-folder">Create</button>
                                            </div>

                                        </form>
                                    </div>
                                    <div class="modal-footer">
                                        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div class="row justify-content-center mt-3">
            <div class="col-md-8">
                <div class="card">
                    <div class="card-header">Folders</div>
                    <div class="card-body">
                        @if($folders)
                            <ul class="folders">
                                @foreach($folders as $folder)
                                    <li data-id="{{ $folder->id }}">
                                        {{ $folder->name }}

                                        <button type='button' class='btn btn-danger delete-folder' data-toggle='modal' data-id='{{ $folder->id }}'>Delete</button>
                                        <button type="button" class="btn btn-primary edit-folder" data-toggle="modal" data-target="#editModal" data-id="{{ $folder->id }}">
                                            Edit
                                        </button>
                                    </li>
                                @endforeach
                            </ul>
                        @endif
                    </div>
                </div>
            </div>
        </div>

        <!-- Modal -->
        <div class="modal fade" id="editModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
            <div class="modal-dialog" role="document">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title" id="exampleModalLabel">Edit</h5>
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                            <span aria-hidden="true">&times;</span>
                        </button>
                    </div>
                    <div class="modal-body">
                        <form id="update-folder-form">
                            @csrf

                            <div class="form-group">
                                <label for="name">Name</label>
                                <input type="text" class="form-control" name="name" id="name">
                            </div>

                            <div class="form-group">
                                <input type="hidden" id="hidden-folder" value="0">
                            </div>

                            <div class="form-group">
                                <button type="button" class="btn btn-primary" id="update-folder">Update</button>
                            </div>

                        </form>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                    </div>
                </div>
            </div>
        </div>

    </div>
@endsection

Ajax Calls

<!-- jQuery 3.x CDN -->
<script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>

<!-- Create ajax call -->
<script>
    $(document).ready(function() {
        $.ajaxSetup({
            headers: {
                'X-CSRF-TOKEN': $('input[name="_token"]').val()
            }
        });

        $('#create-folder').click(function(e) {
            e.preventDefault();

           $.ajax({
               data: $('#create-folder-form').serialize(),
               url: "{{ route('folders.store') }}",
               type: "POST",
               dataType: "json",

               success: function (data) {

                   if(data.errors) {
                       alert('Sorry');
                   } else {
                       $('#create-folder-form').trigger("reset");
                       $('#exampleModal').modal('hide');

                       $('.folders').append('<li data-id=' + data.id + '>' + data.name + " <button type='button' class='btn btn-danger delete-folder' data-toggle='modal' data-id='" + data.id + "'> Delete " +  "</button>" + " <button type='button' class='btn btn-primary edit-folder' data-toggle='modal' data-target='#editModal' data-id='" + data.id + "'> Edit " +  "</button>" + '</li>');
                   }

               },

               error: function (data) {
                    console.log('Error ' + data);
               }
           })
        });
    });
</script>

<!-- Edit ajax call -->
<script>
    $(document).ready(function() {

        $.ajaxSetup({
            headers: {
                'X-CSRF-TOKEN': $('input[name="_token"]').val()
            }
        });

        $('body').on('click', '.edit-folder', function(e) {
            e.preventDefault();

            let id = ($(this).data('id'));

            $.get('folders/' + id + '/edit', function(data) {
               $('#editModal .modal-body #name').val(data.name);
               $('#editModal .modal-body #hidden-folder').val(data.id);
            });
        });

        $('#update-folder').click(function(e) {
            e.preventDefault();

            let id = $('#hidden-folder').val();

            $.ajax({
               type: 'patch',
               url: 'folders/' + id,
               data: $('#update-folder-form').serialize(),
               dataType: "json",

               success: function (data) {
                   if(data.errors) {
                       alert('Sorry');
                   } else {
                       $('#editModal').modal('hide');

                       $('.folders li[data-id=' + data.id + ']').replaceWith('<li data-id=' + data.id + '>' + data.name + " <button type='button' class='btn btn-danger delete-folder' data-toggle='modal' data-id='" + data.id + "'> Delete " +  "</button>" + " <button type='button' class='btn btn-primary edit-folder' data-toggle='modal' data-target='#editModal' data-id='" + data.id + "'> Edit " +  "</button>" + '</li>');
                   }
               }

            });
        });

    });
</script>

<!-- Delete ajax call -->
<script>
    $(document).ready(function() {

        $.ajaxSetup({
            headers: {
                'X-CSRF-TOKEN': $('input[name="_token"]').val()
            }
        });

        $('body').on('click', '.delete-folder', (function(e) {

            e.preventDefault();

            let id = ($(this).data('id'));

            $.ajax({
                type: 'delete',
                url: "folders/" + id,

                success: function(data) {
                    $('.folders li[data-id=' + data.id + ']').remove();
                }

            });

        }));

    });
</script>

Controller

<?php

namespace App\Http\Controllers;

use App\Folder;
use App\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Response;

class FolderController extends Controller
{
    public function index()
    {
        $user = User::findOrFail(Auth::id());

        $folders = $user->folders()->get();

        return view('folders.index', compact('folders'));
    }

    public function store(Request $request)
    {
        $attributes = $request->validate([
            'name' => 'required'
        ]);

        $attributes['user_id'] = Auth::id();

        $folder = Folder::create($attributes);

        return Response::json($folder);
    }

    public function edit($id)
    {
        $folder = Folder::findOrFail($id);

        return Response::json($folder);
    }

    public function update($id, Request $request)
    {
        $folder = Folder::findOrFail($id);

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

        return Response::json($folder);
    }

    public function destroy(Folder $folder)
    {
        $folder->delete();

        return Response::json($folder);
    }

}

Routes

<?php

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::get('/', function () {
    return view('welcome');
});

Auth::routes(['verify' => true]);

Route::get('/home', '[email protected]')->middleware('verified')->name('home');

Route::prefix('folders')->middleware('verified')->group(function() {

    Route::get('/', '[email protected]')->name('folders.index');

    Route::post('/', '[email protected]')->name('folders.store');

    Route::get('/{folder?}/edit', '[email protected]')->name('folders.edit');

    Route::patch('/{folder?}', '[email protected]')->name('folders.update');

    Route::delete('/{folder?}', '[email protected]')->name('folders.destroy');

});

PS: I'm obsessed in writing beautiful code. Thank you so much :) !

Please sign in or create an account to participate in this conversation.