Laravel Undefined propety

时间:2016-02-29 18:00:36

标签: laravel search

我一直试图让我的搜索系统完全工作几天,但由于某种原因,错误不断被抛出我正在使用的其中一个变量,我看不出原因,错误是“未定义属性:Illuminate \ Database \ Eloquent \ Collection :: $ firstName“,我的代码如下:

userblock.blade.php

<div class="media">
<a class="pull-left" href="{{ route('profile/index', ['firstName' => $users->firstName]) }}">
    <img class="media-object" alt="{{ $users->getNameOrUsername() }}" src="{{ $users->getAvatarUrl() }}">
</a>
<div class="media-body">
    <h4 class="media-heading"><a href="{{ route('profile/index', ['firstName' => $users->firstName]) }}">{{ $users->getNameOrUsername() }}</a></h4>
</div>
@if ($users->currentLocation)
    <p>{{ $users->currentLocation }}</p>
@endif

SearchController.php

<?php 

namespace App\Http\Controllers;

use DB;
use App\User;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Http\Request;

class SearchController extends BaseController
{
public function getResults(Request $request)
{   
    $query = $request->input('query');

    if (!$query) {
        return back();
    }

    $users = User::where(DB::raw("CONCAT(firstName, ' ', lastName)"), '
        LIKE', "%{$query}%")
        ->orWhere('username', 'LIKE', "%{$query}%")
        ->get();

    return view('search/results')->with('users', $users);
}
}

user.php的

<?php

namespace App;

use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
/**
 * The attributes that are mass assignable.
 *
 * @var array
 */

protected $table = 'users';

protected $fillable = [
    'id', 'username','firstName', 'lastName', 'bio', 'DoB', 'homeLocation', 'currentLocation', 'journeys', 'friends', 'email', 'password',
];

/**
 * The attributes excluded from the model's JSON form.
 *
 * @var array
 */

protected $hidden = [
    'password', 'remember_token',
];


public function getName()
{
    if ($this->firstName && $this->lastName) {
        return "{$this->firstName} {$this->lastName}";
    }

    if ($this->firstName) {
        return $this->firstName;
    }

    return null;
}

public function getNameOrUsername()
{
    return $this->getName() ?: $this->username;
}

public function getFirstNameOrUsername()
{
    return $this->firstName ?: $this->username;
}

1 个答案:

答案 0 :(得分:2)

您现在正在获得一组用户,并且您只需要一个用户,即WHERE子句中匹配的用户。试试这个:

$users = User::where(DB::raw("CONCAT(firstName, ' ', lastName)"), '
    LIKE', "%{$query}%")
    ->orWhere('username', 'LIKE', "%{$query}%")
    ->first();

这不会再返回一个集合,只有一个用户。让我知道它是否有效!