Laravel Open a route in a modal window


Following code shows a button that when I click routes me to a page where I see the post.

<a target="_blank" rel="nofollow noreferrer" target="_blank" rel="nofollow noreferrer" href="{{ route('post.show',$post->id) }}" 
   class="btn btn-info btn-xs" 
   role="button" 
   data-toggle="tooltip" title="Show">
   <span class="glyphicon glyphicon-eye-open"></span> Show
</a>

What should I do show the content of the route in a modal dialog window? I was able to figure ut how to use the bootstrap data-toggles to show a modal dialog, but not able to figure out how I can get the routes html content to show in the modal.

Answer

There are several ways to get it done. But please don't solve it via iframe.

If there should be only text in the modal, put an empty modal into your main layout and fill it with variables.

If there is a form or something that really should come from an other view, get it with ajax and put it in the modal.


EDIT

AJAX solution:

Put the CSRF token into your DOM, so you can access it from everywhere. You could need it for POST requests. Laravel does not accept POST requests without this token by default.

Also put an empty modal into your body. Later you will fill it with HTML which you'll get with AJAX.

main.blade.php

<!DOCTYPE html>
<html lang="en">
  <head>
    ...
    <meta name="_token" content="{{ csrf_token() }}" />
  </head>
  <body>
    ...
    <div class="modal fade" id="dynamic-modal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
      <div class="modal-dialog">
        <div class="modal-content">
          <div class="modal-body"></div>
        </div>
      </div>
    </div>
    <script src="custom.js"></script>
  </body>
</html>

Modify your HTML:

<button data-path="{{ route('post.show',$post->id) }}" 
   class="btn btn-info btn-xs load-ajax-modal" 
   role="button" 
   data-toggle="modal" data-target="#dynamic-modal">
   <span class="glyphicon glyphicon-eye-open"></span> Show
</button>

Set up the header for your AJAX requests

custom.js

$.ajaxSetup({
    headers: {
        'X-CSRF-Token': $('meta[name="_token"]').attr('content')
    }
});

Look for the click event on your button, get HTML from the requested url (data-path attribute) and put it into your modal-body.

$('.load-ajax-modal').click(function(){

    $.ajax({
        type : 'GET',
        url : $(this).data('path'),

        success: function(result) {
            $('#dynamic-modal div.modal-body').html(result);
        }
    });
});

All of this is not tested and is just a concept ;)


2. EDIT

If you want to replace more than the modal body, you also have different ways to solve it:

  1. Return JSON Object with/for different content
  2. Return that DOM-Node, that you need and place it into your raw modal.
source: stackoverflow.com
js interview questions