Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call controller action from Blade in Laravel 5.1?

Tags:

laravel-5.1

I am trying to call controller action within view in Laravel 5.1, but unable to do this.

Here is what I have tried so far:

<?php echo BridesController::getPhotographer($data->sender_id);?>

but it is giving Class 'BridesController' not found error.

like image 923
Amrinder Singh Avatar asked Aug 14 '15 10:08

Amrinder Singh


People also ask

How do you call a controller inside a view in Laravel 5?

$varbl = App::make("ControllerName")->FunctionName($params);

How do you call a controller in Laravel?

use App\Http\Controllers\UserController; Route::get('/user/{id}', [UserController::class, 'show']); When an incoming request matches the specified route URI, the show method on the App\Http\Controllers\UserController class will be invoked and the route parameters will be passed to the method.


2 Answers

To render a foreign action output inside the view that belongs to your current action, you need to call the foreign action from your current action, then store its output to a variable and pass it to your current view.

Calling actions from the same controller

If the action you want to render is inside the same controller you are using, you could call:

$result = $this->action();

return view('my.view',['my_rendered_action'=>$result]);

And then, inside your view, just:

{!! $my_rendered_action !!}

Take care of not rendering anything that comes from the user using this method, because {!! !!} tags won't scape dangerous inputs. If you do not need to have HTML inside your action response, always prefer using {{ }} instead.

Calling actions from another controller

If you need to share a method between more than one controller, the cleanest way is to create a trait or a Job that implements the logic, and then both controllers would use the trait or dispatch the same job.

Please refer to Shaddy's answer to this question for more information.

Hope it helps. ;)

like image 115
Rafael Beckel Avatar answered Oct 21 '22 09:10

Rafael Beckel


You can do this:

action('BridesController@getPhotographer',$data->sender_id);

Ofcourse if you are using blade you can do this

{{ action('BridesController@getPhotographer',$data->sender_id) }}

You can check it here http://laravel.com/docs/5.1/controllers#basic-controllers

like image 27
Marcus Jason Avatar answered Oct 21 '22 08:10

Marcus Jason