Laravel Model Show函数返回null

时间:2018-04-30 11:43:02

标签: laravel binding model resources

我安装了Laravel 5.6并设置了多个身份验证。

一切正常,除非我进入资源展示功能时,说服者没有获得记录。只返回null。

我已在Google上搜索了2天,但无法弄明白。

代码如下。

web.php

Route::get('/', function () {
return view('welcome');
});

Auth::routes();

Route::get('/home', 'HomeController@index')->name('home');
Route::get('/user/logout','Auth\LoginController@userLogout')->name('user.logout');

//admin route for our multi-auth system

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

    //admin password reset routes
    Route::post('/password/email','Auth\AdminForgotPasswordController@sendResetLinkEmail')->name('password.email');
    Route::get('/password/reset','Auth\AdminForgotPasswordController@showLinkRequestForm')->name('password.request');
    Route::post('/password/reset','Auth\AdminResetPasswordController@reset');
    Route::get('/password/reset/{token}','Auth\AdminResetPasswordController@showResetForm')->name('password.reset');

});

Route::resource('/admin/stock_categories','Admin\Stock\CategoryController');

我正在使用的资源是上面的stock_categories。

我的路线:列表如下。

|        | POST      | admin/stock_categories                       | stock_categories.store   | App\Http\Controllers\Admin\Stock\CategoryController@store                   | web,auth:admin                               |
|        | GET|HEAD  | admin/stock_categories                       | stock_categories.index   | App\Http\Controllers\Admin\Stock\CategoryController@index                   | web,auth:admin                               |
|        | GET|HEAD  | admin/stock_categories/create                | stock_categories.create  | App\Http\Controllers\Admin\Stock\CategoryController@create                  | web,auth:admin                               |
|        | GET|HEAD  | admin/stock_categories/{stock_category}      | stock_categories.show    | App\Http\Controllers\Admin\Stock\CategoryController@show                    | web,auth:admin                               |
|        | PUT|PATCH | admin/stock_categories/{stock_category}      | stock_categories.update  | App\Http\Controllers\Admin\Stock\CategoryController@update                  | web,auth:admin                               |
|        | DELETE    | admin/stock_categories/{stock_category}      | stock_categories.destroy | App\Http\Controllers\Admin\Stock\CategoryController@destroy                 | web,auth:admin                               |
|        | GET|HEAD  | admin/stock_categories/{stock_category}/edit | stock_categories.edit    | App\Http\Controllers\Admin\Stock\CategoryController@edit                    | web,auth:admin         

当我显示列表时,它显示正确。

但是当我点击某个项目并打开网址

/admin/stock_categories/1

返回空结果。我没有显示该项目。

我的型号代码如下。

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Notifications\Notifiable;


class Category extends Model
{
    use Notifiable;

    protected $table = 'stock_categories';
    //protected $fillable = ['name, discount'];

    //
    function items() {
      return $this->hasMany('App\Item','category_id');
    }

}

我的控制器代码如下。

/**
 * 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()
{
    $category = Category::where('master_category_id',0)->orderBy('name')->paginate(20);
    $master_category_id = 0;
    return view('admin.stock.top_list',compact('category','master_category_id'));
}

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

/**
 * Store a newly created resource in storage.
 *
 * @param  \Illuminate\Http\Request  $request
 * @return \Illuminate\Http\Response
 */
public function store(Request $request)
{
    //
}

/**
 * Display the specified resource.
 *
 * @param  \App\Category  $category
 * @return \Illuminate\Http\Response
 */


public function show(Category $category)
{
    return view('admin.stock.category',compact('category'));
}

当我在show函数中使用var_dump($ category)时,我得到了这个。

object(App\Category)#755 (26) {
  ["table":protected]=>
  string(16) "stock_categories"
  ["connection":protected]=>
  NULL
  ["primaryKey":protected]=>
  string(2) "id"
  ["keyType":protected]=>
  string(3) "int"
  ["incrementing"]=>
  bool(true)
  ["with":protected]=>
  array(0) {
  }
  ["withCount":protected]=>
  array(0) {
  }
  ["perPage":protected]=>
  int(15)
  ["exists"]=>
  bool(false)
  ["wasRecentlyCreated"]=>
  bool(false)
  ["attributes":protected]=>
  array(0) {
  }
  ["original":protected]=>
  array(0) {
  }
  ["changes":protected]=>
  array(0) {
  }
  ["casts":protected]=>
  array(0) {
  }
  ["dates":protected]=>
  array(0) {
  }
  ["dateFormat":protected]=>
  NULL
  ["appends":protected]=>
  array(0) {
  }
  ["dispatchesEvents":protected]=>
  array(0) {
  }
  ["observables":protected]=>
  array(0) {
  }
  ["relations":protected]=>
  array(0) {
  }
  ["touches":protected]=>
  array(0) {
  }
  ["timestamps"]=>
  bool(true)
  ["hidden":protected]=>
  array(0) {
  }
  ["visible":protected]=>
  array(0) {
  }
  ["fillable":protected]=>
  array(0) {
  }
  ["guarded":protected]=>
  array(1) {
    [0]=>
    string(1) "*"
  }
}

我的中间件看起来像这样。

class Kernel extends HttpKernel
{
    /**
     * The application's global HTTP middleware stack.
     *
     * These middleware are run during every request to your application.
     *
     * @var array
     */
    protected $middleware = [
        \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
        \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
        \App\Http\Middleware\TrimStrings::class,
        \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,

    ];

    /**
     * The application's route middleware groups.
     *
     * @var array
     */
    protected $middlewareGroups = [
        'web' => [
            \App\Http\Middleware\EncryptCookies::class,
            \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
            \Illuminate\Session\Middleware\StartSession::class,
            // \Illuminate\Session\Middleware\AuthenticateSession::class,
            \Illuminate\View\Middleware\ShareErrorsFromSession::class,
            \App\Http\Middleware\VerifyCsrfToken::class,
            \Illuminate\Routing\Middleware\SubstituteBindings::class,

        ],

        'api' => [
            'throttle:60,1',
            'bindings',
        ],
    ];

    /**
     * The application's route middleware.
     *
     * These middleware may be assigned to groups or used individually.
     *
     * @var array
     */
    protected $routeMiddleware = [
        'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
        'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
        'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
        'can' => \Illuminate\Auth\Middleware\Authorize::class,
        'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
        'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
    ];
}

我希望我做过一些愚蠢的事情,而且我找不到我的生活。

总而言之,我点击了一个项目,加载了show资源路由,但是没有从数据库中检索该项目。

任何帮助都会被大大贬低。

由于

2 个答案:

答案 0 :(得分:0)

我认为您需要使用路线中发送的ID来获取类别。

例如

public function show($id)
{
    $category = Category::find($id);

    return view('admin.stock.category',compact('category'));
}

答案 1 :(得分:0)

我认为你应该寻找Model Binding。 这里的一些资源显示了如何将Model对象传递给Controller。

  1. Route model binding documentation
  2. Some examples
  3. SO
  4. 我希望能帮助你找到一些线索。