How to use blade component in controller laravel

 TestController.php

 public function ComponenetAjax(Request $request)
    {
        if ($request->ajax()) {

            $name ="Neeraj";

            $data = [
                'html' => View::make('components.alert',compact('name'))->render()
            ];

            return response()->json($data);
        }
  return view('testing.index');
}


alert.php


<h3>Welcome {{$name}}<h3>

index.blade.php
 <Button class="btn btn-success" id="mybtn">Click</Button>
 <div class="html">
        Hello
    </div>

  <script>
            $(document).ready(function() {
                $("#mybtn").click(function() {

                    function ajaxHeader() {
                        $.ajaxSetup({
                            headers: {
                                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                            }
                        });
                    }
                    console.log("Buton is working");
                    $.ajax({
                        type: 'get',
                        url: '{{ route('test.ajax') }}',
                        success: function(res) {
                            $(".html").html(res.html);
                            console.log('data:', res.html);
                        }
                    })

                })

            })
        </script>

Alert.php


<?php

namespace App\View\Components;

use Illuminate\View\Component;

class Alert extends Component
{

public $name;
    public function __construct($name=null)
    {
        $this->name =$name;

    }


    public function render()
    {
        return view('components.alert');
    }
}





Comments