Laravel 5.5报错:Trying to get property 'slug' of non-object 求助
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

