Laravel 5.6 auth指令不适用于某些视图

时间:2018-09-10 15:24:19

标签: php laravel laravel-blade

我正在关注5.2上的Laravel教程,而我正在使用Laravel 5.6.29。我有两种类型的用户,一种是Admin,另一种是用户。我面临的问题是,当我以管理员身份登录时,它会将我重定向到它的仪表板。并在导航栏上显示用户名。但是在某些页面(例如主页,博客页面)上,它仍然在导航栏中显示“登录和注册”链接,在某些页面上,例如在帖子创建,编辑等中,它仍显示登录用户的名称。如何解决此问题,以便@auth在所有页面上都能正常工作?以下是我的文件:

Route> web.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!
|
*/

Auth::routes();
Route::get('blog/{slug}', ['as' => 'blog.single', 'uses' => 'BlogController@getSingle'])->where('slug', '[\w\d\-\_]+');
Route::get('blog', ['as' => 'blog.index', 'uses' => 'BlogController@getIndex']);
Route::get('contact', 'PagesController@getContact');
Route::get('about', 'PagesController@getAbout');
Route::get('/', 'PagesController@getIndex');
Route::resource('posts', 'PostController');
Route::get('/user/logout', 'Auth\LoginController@userLogout')->name('user.logout');


Route::get('/home', 'HomeController@index')->name('home');

Route::prefix('admin')->group(function(){
Route::get('/login', 'Auth\AdminLoginController@showLoginForm')->name('admin.login');
Route::post('/login', 'Auth\AdminLoginController@login')->name('admin.login.submit');
Route::get('/', 'AdminController@index')->name('admin.dashboard');
Route::get('/logout', 'Auth\AdminLoginController@logout')->name('admin.logout');
});

AdminController.php:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class AdminController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth:admin');
    }

    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        return view('admin');
    }
}

PostController.php:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Post;
use App\Admin;
use Session;
use Purifier;
use Image;
use Storage;

class PostController extends Controller
{

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth:admin');
    }
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        //the $posts variable stores all posts from DB
        $posts = Post::latest()->paginate(5);

        //return a view and pass abovr variable
        return view('posts.index')->withPosts($posts);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {

        return view('posts.create');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //validate the data
        $this->validate($request, array(    //validate() function is from extended class Controller
            'title' => 'required|max:255',
            'slug' => 'required|alpha_dash|min:5|max:255|unique:posts,slug',
            'author' => 'required',
            'body' => 'required',
            'featured_image' => 'sometimes|image'
        ));

        //Storing in the database
        $post = new Post;   //Creating new instance of post

        $post->title = $request->title; //Saves the title and body to $post
        $post->slug = $request->slug;
        $post->body = Purifier::clean($request->body);
        $post->author = $request->author;

        //save our image
        if ($request->hasFile('featured_image')) {
          $image = $request->file('featured_image');
          $filename = time() . '.' . $image->getClientOriginalExtension();
          $location = public_path('images/' . $filename);
          Image::make($image)->resize(800,400)->save($location);
          $post->image = $filename;
        }

        $post->save();          //Inserts the title and body to the DB

        $request->session()->flash('success', 'The blog post was successfully save!');

        //redirect to show page

        return redirect()->route('posts.show', $post->id);
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        $post = Post::find($id);           //finds the item by primary id and all the data retrieved from DB is stored in the $post variable
        return view('posts.show')->withPost($post); //the withPost helps to use the data of $post in our view by using $post
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $post = Post::find($id);
        return view('posts.edit')->withPost($post);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $post = Post::find($id);

            $this->validate($request, array(
                'title' => 'required|max:255',
                'slug' => "required|alpha_dash|min:5|max:255|unique:posts,slug,$id",
                'body' => 'required',
                'featured_image' => 'image'
            ));

        //save the data to the DB
    $post = Post::find($id);
        $post->title = $request->input('title'); //This means to grab the data from input with attribute 'title'
        $post->slug = $request->input('slug');
        $post->body = Purifier::clean($request->input('body'));

        if ($request->hasFile('featured_image')) {
          //add the new photo
          $image = $request->file('featured_image');
          $filename = time() . '.' . $image->getClientOriginalExtension();
          $location = public_path('images/' . $filename);
          Image::make($image)->resize(800,400)->save($location);
          $oldFilename = $post->image;
          //update the database
          $post->image = $filename;
          //delete the old photo
          Storage::delete($oldFilename);
        }
        $post->save();

        //set flash data with success message
        $request->session()->flash('success', 'The blog post was successfully saved.');

        //redirect with flash data to posts.show
        return redirect()->route('posts.show', $post->id);
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //delete the post
        $post = Post::find($id);

        $post->delete();

        Session::flash('success', 'The post has been successfully deleted.');
        return redirect()->route('posts.index');
    }
}

我的导航栏文件-视图>部分> _nav.blade.php:

<nav class="navbar navbar-expand-lg navbar-light bg-light" style="margin-bottom: 30px;">
<a class="navbar-brand" href="/..">Laravel</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
  <span class="navbar-toggler-icon"></span>
</button>

<div class="collapse navbar-collapse" id="navbarSupportedContent">
  <ul class="navbar-nav mr-auto">
    <li class="nav-item {{Request::is('/')?"active" :""}}">
      <a class="nav-link" href="/home">Home <span class="sr-only">(current)</span></a>
    </li>
    <li class="nav-item {{Request::is('blog')?"active" :""}}">
      <a class="nav-link" href="/blog">Blog</a>
    </li>
    <li class="nav-item {{Request::is('about')?"active" :""}}">
      <a class="nav-link" href="/about">About</a>
    </li>
    <li class="nav-item {{Request::is('contact')?"active" :""}}">
      <a class="nav-link" href="/contact">Contact</a>
    </li>
  </ul>
  <ul class="nav navbar-nav navbar-right">
    <li class="nav-item dropdown">

                    @auth
                        <li class="nav-item dropdown">
                            <a id="navbarDropdown" class="nav-link dropdown-toggle" href="#" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" v-pre>
                                {{ Auth::user()->name }} <span class="caret"></span>
                            </a>

                            <div class="dropdown-menu dropdown-menu-right" aria-labelledby="navbarDropdown">
                                <a class="dropdown-item" href="{{ route('logout') }}"
                                   onclick="event.preventDefault();
                                                 document.getElementById('logout-form').submit();">
                                    {{ __('Logout') }}
                                </a>
                                <a class="dropdown-item" href="{{ route('admin.dashboard') }}">
                                    {{ __('Dashboard') }}
                                </a>

                                <form id="logout-form" action="{{ route('logout') }}" method="POST" style="display: none;">
                                    @csrf
                                </form>
                            </div>
                        </li>
                        @else
                                          <li class="nav-item">
                                              <a class="nav-link" href="{{ route('login') }}">{{ __('Login') }}</a>
                                          </li>
                                          <li class="nav-item">
                                              <a class="nav-link" href="{{ route('register') }}">{{ __('Register') }}</a>
                                          </li>
                    @endauth
    </li>

  </ul>
</div><!--/.navbar-collapse-->

PagesController.php:

<?php

namespace App\Http\Controllers;

use App\Post;

class PagesController extends Controller{
    public function getIndex(){
        $posts = Post::latest()->limit(5)->get();
        return view('pages.welcome')->withPosts($posts);
    }

    public function getAbout(){

        return view('pages.about');
    }

    public function getContact(){
        return view('pages.contact');
    }
}

我的主要主页:views> pages> main.blade.php:

@extends('main')

@section('title', '| Homepage')

@section('content')
<div class="row">
    <div class="col-md-12">
        <div class="jumbotron">
          <h1 class="display-4">Hello, world!</h1>
          <p class="lead">This is a simple hero unit, a simple jumbotron-style component for calling extra attention to featured content or information.</p>
          <hr class="my-4">
          <p>It uses utility classes for typography and spacing to space content out within the larger container.</p>
          <a class="btn btn-primary btn-lg" href="#" role="button">Learn more</a>
      </div>
      <div class="row">
          <div class="col-md-8">

            @foreach($posts as $post)
            <div class="post">
                <h3>{{ $post->title }}</h3>
                <p>{{ str_limit(strip_tags($post->body), 300) }}</p>
                <a href="{{url('blog/'.$post->slug)}}" class="btn btn-primary">Read More</a>
            </div>
            <hr>
            @endforeach
        </div>
        <div class="col-md-3 col-md-offset-1">
            <h3>Sidebar</h3>
            <a href="{{ route('admin.login') }}">Admin Login</a>
        </div>
    </div>

</div><!--end of .row-->
@endsection

views> main.blade.php:

<!DOCTYPE html>
<html lang="en">
@include('partials._head')
</head>
<body>

  @include('partials._nav')

  <div class="container">

    @include('partials._messages')

        @yield('content')

    @include('partials._footer')

  </div><!--end of container-->

  @include('partials._javascripts')

</body>
</html>

当我以管理员身份登录时,“登录和注册”链接被替换为视图(视图> auth> {filesForLoggedInUsers})的auth文件夹中文件中的名称,但在所有其他视图(包括“欢迎”,“博客等。请帮助我所缺少的内容。

2 个答案:

答案 0 :(得分:0)

您设置了什么默认config / auth.php 您尝试过@auth('admin')吗?

您可以检查docs

答案 1 :(得分:0)

指定管理员身份验证保护程序以显式检查管理员用户的身份验证。

@auth('admin')
<!--Your navigation items for admin users-->

@else
    @guest
       <li class="nav-item">
       <a class="nav-link" href="{{ route('login') }}">{{ __('Login') }}</a>
        </li>
       <li class="nav-item">
       <a class="nav-link" href="{{ route('register') }}">{{ __('Register') }}</a>
       </li>
 @else
  <!--Your navigation items for general  users-->

  @endguest
  @endauth