Site Admin
Site Admin Founder of MeaningArticles
1762 Views

Laravel 8 View Render example

Hello Dev.

In this small article, i will learn you how to view render in laravel eight.you could easy and simply view render in laravel 8.

Sometimes, we use get html view layout from ajax request. At that you need to first render view file and then you want to keep view in varibale and then we are able to return that varibale. In bellow instance i render view with pass data you could see how i did:

So let's start the lesson...

 

Step 1: Create Route

In this step,you can create route file in laravel.
web.php

use App\Http\Controllers\ViewRenderController;

Route::get('view', [ViewRenderController::class, 'view']);
Route::post('view-render', [ViewRenderController::class, 'viewRender'])->name('view.render');

 

Step 2: Create Controller

In this step,you can create to ViewRenderController in controller file.

ViewRenderController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class ViewRenderController extends Controller
{
    public function view()
    {
        return view('view');
    }

    public function viewRender(Request $request)
    {
        $viewRender = view('viewRend')->render();
    return response()->json(array('success' => true, 'html'=>$viewRender));
    }
}

 

Step 3: Create Render File

<!DOCTYPE html>
<html>

<head>
    <title>Laravel 8 View Render Example - meaningarticles.com</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
</head>

<style type="text/css">
    body{
        background:#fd56c2 !important;
    }
    .box{
        margin-top:200px;
        background:#fff;
        padding:100px 50px;
        text-align: center;
    }
</style>

<body>
    <div class="container">
        <div class="row">
            <div class="col-md-8 offset-md-2 box">
                <div class="viewRender">
        
                </div>
            </div>
        </div>
    </div>
</body>

<script src="https://code.jquery.com/jquery-1.9.1.min.js"></script>
<script type="text/javascript">
    $(document).ready(function(){
         $_token = "{{ csrf_token() }}";
         $.ajax({
             headers: { 'X-CSRF-Token' : $('meta[name=_token]').attr('content') },
            url: "{{ route('view.render') }}",
            type: 'POST',
            cache: false,
            data: {'_token': $_token },
            datatype: 'html',
            beforeSend: function() {
                //something before send
            },
            success: function(data) {
                console.log(data);
                $('.viewRender').html(data.html);
            }
        });
    });
</script>

</html>

I hope it assists you, thanks for visiting my article if you like my article then share it with your friends on the social media platform.

Happy Coding.....