Передача переменной в представление
Я написала представление шапки сайта:
<div class="bg-light">
<nav class="navbar navbar-expand-lg navbar-dark bg-mgray">
<div class="container">
<a class="navbar-brand" href="{{ route("home") }}">{{ config('app.name') }}</a>
<input type="checkbox" id="navbar-toggle-cbox">
<label class="navbar-toggler" for="navbar-toggle-cbox" data-toggle="collapse"
data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false"
aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</label>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav mr-auto">
@admin
<li class="nav-item @isroute('admin') active @endisroute">
<a class="nav-link" href="{{ route('admin.index') }}">Панель администратора</a>
</li>
@endadmin
@moderator
<li class="nav-item @isroute('admin') active @endisroute">
<a class="nav-link" href="{{ route('admin.index') }}">Панель модератора</a>
</li>
@endmoderator
@auth
<li class="nav-item @isroute('profile.tickets') active @endisroute">
<a class="nav-link" href="{{ route('profile.tickets') }}">Помощь</a>
</li>
@endauth
</ul>
@search
<div class="col-md-02">
<form action="{{route('search')}}" method="POST" class="form-inline h-100">
{{csrf_field()}}
<div class="input-group w-100">
<input type="text" class="form-control form-control" id="search" name="search"
placeholder="Что Вы ищете?" value="{{app('request')->input('query')}}">
<div class="input-group-append">
<button class="btn btn-info">Поиск</button>
</div>
</div>
</form>
</div>
@endsearch
<ul class="navbar-nav">
@auth
<li class="nav-item @isroute('profile.notifications') active @endisroute">
<a href="{{route('profile.notifications')}}" class="nav-link">
<span @if(auth()->user()->unreadNotifications()->count() > 0) class="text-warning" @endif><i class="fa fa-bell"></i> {{auth()->user()->unreadNotifications()->count()}}</span>
</a>
</li>
<li class="nav-item @isroute('profile.purchases') active @endisroute">
<a class="nav-link" href="{{ route('profile.purchases') }}">
<i class="fas fa-shopping-cart mr-2"></i>
</a>
</li>
<li class="nav-item @isroute('profile.index') active @endisroute">
<a class="nav-link" href="{{ route('profile.index') }}">{{auth()->user()->username}}</a>
</li>
<form class="form-inline" action="{{route('auth.signout.post')}}" method="post">
{{csrf_field()}}
<button class="btn btn-link text-muted my-0" type="submit" style="text-decoration: none;">Выйти</button>
</form>
@else
<li class="nav-item">
<a class="nav-link" href="{{route('auth.signin')}}">Войти</a>
</li>
<li class="nav-item">
<a class="nav-link" href="{{route('auth.signup')}}">Регистрация</a>
</li>
@endauth
</ul>
</div>
</div>
</div>
<div class="bg-nav-blue">
<nav class="navbar">
<div class="container">
<div class="hamburger-menu">
<input id="menu__toggle" type="checkbox" />
<label class="menu__btn" for="menu__toggle">
<span></span>
</label>
<ul class="menu__box">
@include ('includes.categories')
</ul>
</div>
<ul class="navbar-nav">
<li class="nav-item-blue">
<a class="nav-link" href="">#</a>
<a class="nav-link" href="">#</a>
</li>
</ul>
</div>
</nav>
</div>
</nav>
В этом представлении я пытаюсь инклудить представление категорий. Как только я это делаю - у сайта работает главная страница и я могу зайти в любую категорию. Все прекрасно. Но как только я пытаюсь посетить какие либо другие страницы - я получаю ошибку:
Undefined variable: categories (View: ###/resources/views/includes/categories.blade.php)
Я могу заинклудить список категорий хоть посреди домашней страницы и весь сайт прекрасно работает, но как только я пытаюсь сделать это в панели навигации - все перестает работать.
Я совсем запуталась в какое представление и каким образом я должна передать переменную $categories. И вообще потеряла логическую цепочку связи подключения представления и того, что переменная перестает передаваться.
Привожу код web.php и indexcontroller.php:
<?php
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::name('auth.')->group(function () {
include 'auth.php';
});
Route::prefix('admin') -> group(function (){
Route::middleware(['admin_panel_access'])->group(function () {
include 'admin.php';
});
});
// Profile routes
Route::middleware(['auth'])->group(function () {
Route::get('banned', 'ProfileController@banned')->name('profile.banned');
Route::middleware(['is_banned']) -> group(function(){
include 'profile.php';
});
});
Route::get('/', 'IndexController@home')->name('home');
Route::get('/category/{category}', 'IndexController@category') -> name('category.show');
Route::get('/login', 'IndexController@login')->name('login');
Route::get('/confirmation', 'IndexController@confirmation')->name('confirmation');
Route::get('setview/{list}', 'IndexController@setView') -> name('setview');
// Product routes
Route::get('product/{product}', 'ProductController@show') -> name('product.show');
Route::get('product/{product}/rules', 'ProductController@showRules') -> name('product.rules');
Route::get('product/{product}/feedback', 'ProductController@showFeedback') -> name('product.feedback');
Route::get('product/{product}/delivery', 'ProductController@showDelivery') -> name('product.delivery');
Route::get('product/{product}/vendor', 'ProductController@showVendor') -> name('product.vendor');
// category routes
Route::get('category/{category}', 'IndexController@category') -> name('category.show');
// vendor routes
Route::get('vendor/{user}', 'IndexController@vendor') -> name('vendor.show');
Route::get('vendor/{user}/feedback', 'IndexController@vendorsFeedbacks') -> name('vendor.show.feedback');
Route::post('search','SearchController@search')->name('search');
Route::get('search','SearchController@searchShow')->name('search.show');
<?php
namespace App\Http\Controllers;
use App\Category;
use App\Marketplace\Cart;
use App\Marketplace\FeaturedProducts;
use App\Marketplace\ModuleManager;
use App\Marketplace\Payment\Escrow;
use App\Marketplace\Payment\VergeCoin;
use App\Product;
use App\Vendor;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
/**
* Controller for all always public routes
*
* Class IndexController
* @package App\Http\Controllers
*/
class IndexController extends Controller
{
/**
* Handles the index page request
*
* @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
*/
public function home() {
if (!ModuleManager::isEnabled('FeaturedProducts'))
$featuredProducts = null;
else
$featuredProducts = FeaturedProducts::get();
return view('welcome', [
'productsView' => session() -> get('products_view'),
'products' => Product::frontPage(),
'categories' => Category::roots(),
'featuredProducts' => $featuredProducts
]);
}
/**
* Redirection to sing in
*
* @return \Illuminate\Http\RedirectResponse
*/
public function login() {
return redirect()->route('auth.signin');
}
public function confirmation(Request $request) {
return view('confirmation');
}
/**
* Show category page
*
* @param Category $category
* @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
*/
public function category(Category $category) {
return view('category', [
'productsView' => session() -> get('products_view'),
'category' => $category,
'products' => $category->childProducts(),
'categories' => Category::roots(),
]);
}
/**
* Show vendor page, 6 products, and 10 feedbacks
*
* @param Vendor $user
* @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
*/
public function vendor(Vendor $user) {
return view('vendor.index',[
'vendor' => $user->user
]);
}
/**
* Show page with vendors feedbacks
*
* @param Vendor $user
* @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
*/
public function vendorsFeedbacks(Vendor $user) {
return view('vendor.feedback', [
'vendor' => $user->user,
'feedback' => $user->feedback()->orderByDesc('created_at')->paginate(20),
]);
}
/**
* Sets in session which view are we using
*
* @param $list
* @return \Illuminate\Http\RedirectResponse
*/
public function setView($list)
{
session() -> put('products_view', $list);
return redirect() -> back();
}
}
Ответы (1 шт):
Проблема решена. Файл app/providers/AppService/Provider.php должен выглядеть так
<?php
namespace App\Providers;
use Illuminate\Support\Facades\View;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
View::share('categories', (new \App\Category)->roots());
}
/**
* Register any application services.
*
* @return void
*/
public function register()
{
if ($this->app->environment() !== 'production') {
$this->app->register(\Barryvdh\LaravelIdeHelper\IdeHelperServiceProvider::class);
}
}
}