Reputation: 3082
I'm currently developing a CMS using PHP Laravel (5.4) based on an existing ASP.NET MVC version I've made in the past. Since most of the ASP.NET version is written in JS, I'm trying to reuse the most I can in the newer Laravel version I'm developing. I have already translated most of the C# code to PHP, thanks to Laravel's similarities with ASP.NET MVC architecture, this was somewhat straightforward.
Currently I'm facing a issue trying to call a controller action from within a view that will in-turn render a partial view. In the ASP.NET MVC version I've accomplished this using a Html.RenderAction
helper.
ASP.NET MVC Example:
<div>
@{Html.RenderAction("Controller", "Action");}
</div>
I want know if there is any alternative to the Html.RenderAction
helper that I can use to accomplish this task.
I've search the interwebs and Laravel's documentation, and from what I was able to find, View Composers seem to be closest alternative. Unfortunately, I didn't find any example that could resolve my issue.
@Farrukh suggested using View Composers and it does actually work as intended. The problem is that I will need to add a View Composer to the AppServiceProvider for every partial view I want to render.
I found another solution that allows me to call an action from a view and render a partial view:
<?php echo \App\Http\Controllers\PageController::listAll(); ?>
But this solution doesn't seem very clean.
Upvotes: 1
Views: 1169
Reputation: 11
You can use the Service Injection:
<div>
@{Html.RenderAction("Controller", "Action");}
</div>
In Laravel would be:
@inject('Controller', 'App\Http\Controllers\HomeOrOtherController')
{!! $Controller->action() !!}.
With this you will render in the view the content of the view of the action in the controller.
Upvotes: 1
Reputation: 11
ViewComposer behaves like a global component, all you have to do is put your business logic into a method in your Model.
e.g.
class Post extends Model {
public static function archives() {
return static::selectRaw('your query here')
->get()
->toArray();
}
}
Then goto providers/AppServiceProvider.php
add your viewcomposer code into boot method (a hook before any view loads).
e.g.
@include('layouts.sidebar')
in AppServiceProvier, boot method:
public function boot() {
view()->composer('layouts.sidebar', function($view) {
$view->with('archives', \App\Post::archives());
});
}
Upvotes: 1