user3019749
user3019749

Reputation: 81

Laravel Undefined propety

I've been trying to get my search system completely working for a few days now but for some reason an error keeps being thrown over one of the variables I'm using and I can't see why, the error is "Undefined property: Illuminate\Database\Eloquent\Collection::$firstName" and my code is as follows:

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;
}

Upvotes: 0

Views: 33

Answers (1)

holland
holland

Reputation: 2182

You're getting a collection of users right now, and you need to only a single one, the one that matches in your WHERE clause. Try this:

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

This will not return a collection anymore, only a single user. Let me know if it worked!

Upvotes: 2

Related Questions