Search code examples
javascriptphpjquerylaravellaravel-blade

Open the bootstrap modal with a form only for authenticated users in laravel


If the user is logged in then on click of the button bootstrap modal is open but if not logged in then it redirects to the login page.

Input Field Which opens the modal on click:

<form class="card-header">
  <div id="write" class="input-group mb-3">
    <button type="button" class="btn btn-danger rounded-0" data-bs-toggle="modal" data-bs-target="#postModal">
       <small>Write<i class="fa fa-plus-circle"></i></small>
     </button>
   <input data-bs-toggle="modal" data-bs-target="#postModal" class="form-control form-control-sm rounded-0 py-2"
                placeholder="Click to post" />
   </div>
</form>

Modal to be opened on click:

<div class="modal fade" id="postModal">
    <div class="modal-dialog modal-dialog-centered modal-xl">
        <div class="modal-content rounded-0">
            <div class="modal-header">
                <h3 class="modal-title">Create</h3>
                <!-- form-fields here -->
            </div>
        </div>
    </div>
</div>

So basically if the user is not authenticated and clicks in the input then it should be redirected to the login page.

@auth
I'm confused about how can I implement it for modal pop-up
@endauth

I want the authenticated user to be able to open the form to post anything if they are not logged in then it is redirected with the message "you need to login to post anything" and redirected to the login page.


Solution

  • 1.Update your Blade file to conditionally show the button and input field based on the user's authentication status:

        @auth
        <form class="card-header">
            <div id="write" class="input-group mb-3">
                <button type="button" class="btn btn-danger rounded-0" data-bs-toggle="modal" data-bs-target="#postModal">
                    <small>Write<i class="fa fa-plus-circle"></i></small>
                </button>
                <input class="form-control form-control-sm rounded-0 py-2" placeholder="Click to post" />
            </div>
        </form>
    @else
        <p>You need to login to post anything.</p>
        <a href="{{ route('login') }}" class="btn btn-primary">Login</a>
    @endauth
    

    OR Update your JavaScript to open the modal when the button is clicked only for authenticated users:

    <script>
        // Listen for the click event on the "Write" button
        $('#write button').click(function () {
            @auth
                // If the user is authenticated, open the modal
                $('#postModal').modal('show');
            @else
                // If the user is not authenticated, redirect to the login page
                window.location.href = "{{ route('login') }}";
            @endauth
        });
    </script>