2

I'm running Laravel 7, and I wonder if it is possible to return a rendered Blade component from a controller, just like you would with a view. I can return the view of the component like the following.

return View::make('components.some-view');

However, I do not have access to any of the data or methods inside the SomeView component class. If I try to use a variable defined in the component, I receive an undefined variable error.

4 Answers 4

5

Try this, it works for me in Laravel 8

for example I have App\View\Components\Form\Button component

<?php 
   class Button extends Component{
       public $variable1;
       public $variable2;

       public function __construct($variable1, $variable2){
            $this->variable1 = $variable1;
            $this->variable2 = $variable2;
       }

       public function render(){
             // return view('view_component_name'); 
       }
   }
?>

& I wants to render that component in controller without view layout then I can do like this

<?php
  use App\View\Components\Form\Button;

  class TestController extends Controller{

     public function index(Request $request)

        $obj = new Button($variable1, $variable2);
        $obj->render()->with($obj->data());
     }
  }
?>

** data function include methods, properties and attributes of Component.

I hope this one helps to you

Sign up to request clarification or add additional context in comments.

3 Comments

why my answer got negative votes? my answer is working example. I use this way in my project for render specific component view with calling main view or any extend view, then it is very useful.
don't forget to call "return" at the end of method
@HassanElshazlyEida ya, but its depends on requirement what you need to return like json response or view page response. so I doesn't mentioned it in my answer.
4

You can render a blade component from your controller using view function:

//first parameter = Path of your component
//second argument = All your variables that your component receive 

$html = view('components.yourComponentName', ['x-variable' => $value]);
return $html; 

Comments

2

Create object of component in controller like

$com = new SomeComponent($variable1, $variable2);

//call the render function
$comHtml = $com->render();

Hopefully this will help.

Comments

-1

Use YourDirectory\some-view;

$controllerObject = new some-view;

$controllerObject -> variable;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.