katie hudson
katie hudson

Reputation: 2893

Laravel 5 - List database entries using where clause

I am trying to list all entries which fall under a where condition. If I do the following, I get all the entries returned

$users = User::lists('userName', 'id');

However, I am looking to return only the users who have a department id of 3. So I am doing

$users = User::lists('userName', 'id')->where('departmentId', 3);

However, this returns an empty result set. In my database, I do have users with this department id.

How can I get the lists statement working?

Just a note, the following returns the result I need

$users = User::select('userName', 'id')->where('departmentId', 3)->get();

However, in my edit form, because I have this

!! Form::select('csManager', $users, Input::old('users'), ['class' => 'csManager']) !!}

The old input is not selected and the data is showing up as an array. I know the way to fix this is to do my select like this

<select class="csManager" name="csManager">
    @foreach($users as $user)
    <option value="{{ $user->id }}">{{ $user->userName }}</option>
    @endforeach
</select>

But then I am not sure how to display the old user within the above select.

Any help appreciated.

Thanks

Upvotes: 0

Views: 318

Answers (2)

smartrahat
smartrahat

Reputation: 5609

In your controller:

$users = User::where('departmentId', 3)->lists('userName', 'id');

In blade form:

{!! Form::select('csManager', $users, null, ['class' => 'csManager']) !!}

To get the old data in edit form instead of

{!! Form::open([your attributes]) !!}

Use model binding. something like this:

{!! Form::model($user,[your attributes]) !!}

In this case your edit method should have $user=findOrFail($id);

Upvotes: 0

manix
manix

Reputation: 14747

To mark a old selection try this:

<option value="{{ $user->id }}" 
         {{ (Input::old('users') == $user->id)? 'selected' : '' }}>
    {{ $user->userName }}
</option>

As @TimVanUum say, you can save a little bit of code if you prefer. Both are equals.

<option value="{{ $user->id }}" 
         {{ (Input::old('users') !== $user->id)?: 'selected'}}>
    {{ $user->userName }}
</option>

Upvotes: 1

Related Questions