问题
I have an issue where I can't display my navigation bar when I am displaying my page content. Currently the output of my code is, Undefined variable: navContent (View: C:\Users\Computer Angel\Documents\blog\resources\views\layouts\components\navbar.blade.php). My desired output is to show my navigation bar, then my page content below it.
This is my code for the dynamic.blade.php which is where both the navigation bar and the page content should be displayed.
<!DOCTYPE html>
<html>
<head>
</head>
@component('layouts.components.navbar')
@endcomponent
<body>
{!!$pageContent->pageContent!!}
</body>
</html>
The navbar.blade.php which is also my component is shown below:
<nav>
@slot('$navContent')
@foreach($navContent as $nav)
<a href="{!!$nav->navLink!!}">{!!nav-navName!!}</a>
@endforeach
@endslot
</nav>
This is my PageController@show:
public function show($URI)
{
$pageContent = DB::table('pages')->where('URI',$URI)->first();
return view('page.dynamic', ['pageContent' => $pageContent]);
}
This is my Nav.php
protected $fillable = ['navName', 'navLink'];
This is my Page.php
protected $fillable = ['title', 'URI', 'pageContent'];
This is my pages migration:
Schema::create('pages', function (Blueprint $table) {
$table->id();
$table->string('title');
$table->string('URI');
$table->text('pageContent');
$table->timestamps();
});
This is my navs migration:
Schema::create('navs', function (Blueprint $table) {
$table->id();
$table->string('navName');
$table->string('navLink');
$table->timestamps();
});
This is my web.php:
Route::get('/page/{URI}', 'PageController@show');
For my full code, use the GitHub Repository link below:
https://github.com/xiaoheixi/blog
Thanks for taking the time to read and try to help me! :D
回答1:
I just fixed my problem by doing my current steps listed below.
- I watched https://www.youtube.com/watch?v=THN5Q8JBeDM.
- Added "$navContent = Nav::all(); view()->share('navContent', $navContent);" to AppServiceProvider.php in the boot() public function.
- Add use App\Nav; into the AppServiceProvider.php.
- Remove @slot('$navContent') and @endslot in navbar.blade.php.
- Open terminal and run php artisan serve, it should work.
Finally best wishes, hope you all pass your Professional Experience and graduate.
来源:https://stackoverflow.com/questions/63883304/how-do-i-use-components-to-display-my-dynamic-navigation-bar-using-laravel