How do I use components to display my dynamic navigation bar using laravel?

不羁的心 提交于 2021-01-29 05:17:33

问题


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.

  1. I watched https://www.youtube.com/watch?v=THN5Q8JBeDM.
  2. Added "$navContent = Nav::all(); view()->share('navContent', $navContent);" to AppServiceProvider.php in the boot() public function.
  3. Add use App\Nav; into the AppServiceProvider.php.
  4. Remove @slot('$navContent') and @endslot in navbar.blade.php.
  5. 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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!