John Davidson

php - Sharing Data with Multiple Views - Refactoring

0 comments
Message:


I am looking for a better way to code this. I have been pounding my head into my desk because I just cant seem to figure it out.


I have an application that has multiple companies in it, and each company has their own resources. For example routes would look like this:


test.app/organizations/2/contacts


I have code in the views that rely on the {organization} variable being there. So on every single function I am having to add organization and return it with the view.


I would like to simplify it with like a View::Share or something but the organization doesn't apply to every single view.


This is how it looks now. Is there a better way of doing this? Any guidance would greatly be appreciated!



/**
* Display a listing of the resource.
*
* @return Application|Factory|Response|View
*/
public function index(Organization $organization)
{
return view('app.pages.organization.contact.index', [
'organization' => $organization
]);
}

/**
* Return data for datatables.
*
*/
public function datatable(Organization $organization)
{
$query = $organization->contacts();
return DataTables::of($query)->toJson();
}


My Answer:
> One way to simplify this code is to use view composers in Laravel. View composers allow you to share data with multiple views without having to pass it explicitly in every controller method.

Here's how you can refactor your code using view composers:

1. Create a new service provider for your view composers. You can do this by running the following command:

bash
php artisan make:provider ViewComposerServiceProvider


2. In the `ViewComposerServiceProvider` class, define your view composers in the `boot` method. For example, you can define a view composer for the `app.pages.organization.contact.index` view like this:

php
use App\Organization;
use Illuminate\Support\Facades\View;

public function boot()
{
View::composer('app.pages.organization.contact.index', function ($view) {
$organization = Organization::find(2); // You can replace this with your logic to get the organization
$view->with('organization', $organization);
});
}


3. Register the `ViewComposerServiceProvider` in your `config/app.php` file.

4. Remove the `organization` parameter from your controller method and return the view without passing the organization data:

php
public function index()
{
return view('app.pages.organization.contact.index');
}


With this approach, the `organization` data will be automatically shared with the `app.pages.organization.contact.index` view without having to pass it explicitly in every controller method. You can define multiple view composers for different views as needed.

Rate this post

5 of 5 based on 7367 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us