You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel 5.5报错:Trying to get property 'slug' of non-object 求助

Fixing "Trying to get property 'slug' of non-object" in Laravel 5.5 AdminMiddleware

Hey there, let’s work through this error you’re facing. This message almost always means you’re trying to access the slug property on a variable that isn’t an object—it’s probably null or an array instead. Let’s break down the most common fixes:

1. Check if your model instance actually exists

Chances are, you’re fetching a page (or other model) in your middleware, but the query isn’t returning a result. For example:

// This returns null if no matching page is found
$page = Page::where('id', $request->route('id'))->first();

// Then trying to access $page->slug throws the error

Fix: Add a check to ensure the model exists before accessing its properties:

$page = Page::where('id', $request->route('id'))->first();

if (!$page) {
    abort(404, 'Requested page not found');
}

// Now you can safely use $page->slug

2. Verify route parameter binding is working correctly

If you’re using Laravel’s implicit model binding (e.g., Route::get('/admin/page/{page}', 'AdminController@show')), make sure your route parameter name matches the model’s route key (usually id by default). If the binding fails (no matching model found), the injected variable will be null.

Quick check: Dump the variable in your middleware to confirm:

dd($request->route('page')); // Is this null or a Page object?

3. Guard against null in permission logic

If your middleware checks user permissions using the slug, ensure the related object exists before passing it to the permission check. For example:

// ❌ Risky: $page might be null
if (auth()->user()->can('view', $page->slug)) {
    // ...
}

// ✅ Safe: Check if $page exists first
if ($page && auth()->user()->can('view', $page->slug)) {
    // ...
}

4. Use Laravel’s optional() helper (Laravel 5.5+)

If you need to access the slug without causing an error when the object is null, use the optional() helper—it returns null instead of throwing an error:

$slug = optional($page)->slug; // Returns null if $page is null, else $page->slug

5. Debug to see what your variable actually is

The fastest way to pinpoint the issue is to dump the variable right before the line that throws the error. Add this:

dd($page); // Replace $page with the variable you're trying to access slug from

This will show you if it’s null, an array, or something else entirely—helping you trace back where the variable is being set incorrectly.

If none of these fixes resolve the issue, feel free to share a snippet of your AdminMiddleware code, and we can dig deeper into the specific logic causing the problem.

内容的提问来源于stack exchange,提问作者Arifur Rahman

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 07:02:48