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

Laravel 5.5中$request->all()在控制器与Blade视图的使用报错问题

Fixing "Trying to get property of non-object" Error in Laravel 5.5

Hey there, let's break down why you're hitting this error and how to fix it quickly!

The Root Cause

When you call $request->all(), Laravel returns an associative array of all request parameters, not an object. That's why trying to access $search_cons->name (object property syntax) throws the "Trying to get property of non-object" error—you're treating an array like an object.

On the flip side, $request->input('name') works because that method directly pulls the value from the request array for the name key. Laravel also lets you use magic properties like $request->name which does the same thing under the hood.

Solutions

Here are a few ways to fix this based on your needs:

1. Use Array Syntax with $request->all()

If you want to keep using $request->all() to get all parameters, access values using array keys instead of object syntax. Add a null coalescing operator (??) to handle cases where the name parameter might not exist:

Controller Code:

public function index(Request $request) { 
    $search_cons = $request->all(); 
    $search_con = $search_cons['name'] ?? ''; // Array syntax + default value
    return view('your-view-name', compact('search_cons', 'search_con'));
}

Blade View:

<p>{{ $search_cons['name'] ?? '' }}</p>

2. Convert the Array to an Object

If you prefer using object syntax (->) everywhere, you can cast the request array to an object using (object):

Controller Code:

public function index(Request $request) { 
    $search_cons = (object) $request->all(); // Cast array to object
    $search_con = $search_cons->name ?? ''; // Now object syntax works
    return view('your-view-name', compact('search_cons', 'search_con'));
}

Blade View:

<p>{{ $search_cons->name ?? '' }}</p>

3. Use Laravel's Built-in Request Helpers

The cleanest Laravel approach is to use the request object's magic properties or input() method to fetch individual parameters directly:

Controller Code:

public function index(Request $request) { 
    $search_con = $request->name; // Magic property (same as $request->input('name'))
    // Or with a default value: $search_con = $request->input('name', 'No name provided');
    return view('your-view-name', compact('search_con'));
}

Blade View:

<p>{{ $search_con }}</p>

Quick Note

Avoid returning an array concatenated with a string like return $search_cons.$search_con—this will throw another error because you can't concatenate arrays and strings. Instead, pass variables to a view or return a proper response like response()->json($search_cons) if you need to debug.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 10:16:47