How to get only one element from collection in the view - laravel

I passed $users variable to my view and I want to get only one element of this collection by comparing it using contains() method.
It's working but I want to retrieve this element so I can show the name
how to do that?
My code:
#foreach($rqs as $rq)
<td>{{$rq->user_id}} with name:
#if($users->contains('id',$rq->user_id))
Working >> I want to get the user name here but only one user
#endif
</td>
#endforeach

What about:
$users->where('id',$rq->user_id)->first()->name

Related

How to get an ID from the collection in laravel?

I am writing one database query it's returning the matching record that's stored in one variable called $store,i want to get the id of the particular record which is stored in the $store variable.
$store=DB::table('books')->where('bookName','dummy')->get();
books migration table structure
$table->increments('id');
$table->string('bookName'); //it's uniqe
$table->int('price');
what i am trying is when i try to get the id of a particular book based on $store [$store->id]variable it's throwing an error called
Propert id doesnot exist on collection instance
Try this
$store=DB::table('books')->where('bookName','dummy')->get();
foreach($store as $str){
echo $id = $str->id;
}
it's showing clearly collection so you have to call the following way
$store[0]->id
If you need only the id, the common way will be use select.
Model::select('id')->get();
And in the view you can iterate the ModelCollection and use $item->id or '$item['id']'
foreaxample, getting first book id with specific price:
$id = $store->where('price', 100)->first()->id;

Laravel - Passing array of data to view and accessing array elements conditionally

Suppose I design an email template notifying about the interview scheduled for 3 candidates to a recruiter, so in that case I send candidates array of 3 elements as a variable to my template. How do I access individual candidates name in that case?
you only need to pass parameters as you would for any other, with
$candArr = Candidates::where('something','value')->get();
return view('email')->with('candidates',$candArr);
Or
$candArr = Candidates::where('something','value')->get();
return view('email',compact('candArr'));
and then in view
#foreach($candArr as $key)
{{$key->name}}
#endforeach
Hope it helps!

Add row manually to eloquent result in Laravel 4.2

I am using Laravel 4.2 and i fetch all locations with this code:
$locations = Location::all();
This Locations are displayed in a select box afterwards. How can i add an additional row to the results in order to show an empty first option in the select box.
The options then should be:
choose a location
location 1
location 2
...
I just want to add an additional item to the result in $locations.
Thanks in advance
You can use:
{!! Form::select('location', ['' => 'Select your location'] + $locations, null , ['class' => 'form-control']) !!}
to update the view. In Laravel 5 there are attribute accessors to append an extra field with your eloquent collection.
Few other ways to do this are:
$locations[null] = 'choose a location';
Form::select('location', $locations);
Form::select('location',[null=>'Please Select'] + $locations);
Another way is to loop through the result and update it. Use json_decode() or 'toArray()` to convert your result into array format.
Otherwise you have to store choose a location as the first row value in your locations table(I know that is inappropriate for the requirement).
You should look at the put method for collections:
https://laravel.com/docs/5.6/collections#method-put
This method is not available in 4.2. You should make a custom Collection class and use it in your model by overwriting the newCollection method. https://laravel.com/docs/4.2/eloquent#collections

Laravel returns undefined offset 0 when trying to print from array

Controller
$new_products = Product::with('images')->orderBy('created_at', 'desc')->take(10)->get();
return view('site/home', compact('new_products'));
View
{{ $new_product->images[0]->image_name }}
This gives me error undefined offset 0. How do i print the values of images?
values returned on dd($new_products)
If you want to get the first item, you can use the first method.
{{ $new_product->images->first()->image_name }}
You also have the offsetGet method to get an item at a given offset.
{{ $new_product->images->offsetGet(0)->image_name }}
You can also loop through the collection though and do this:
#foreach ($new_product->images as $image)
{{ $image->image_name }}
#endforeach
Note: The first two method will only work if your products have images. If they don't, then Laravel will return an empty collection. The third method of looping through the collection will work in all cases.
If you want to make sure that products have images, you can use the has method.
$new_products = Product::with('images')->has('images')->orderBy('created_at', 'desc')->take(10)->get();
This will only return products that have at least one image.
Docs on collection methods: http://laravel.com/docs/master/collections#method-first
Docs on relationships: http://laravel.com/docs/5.1/eloquent-relationships
From the out it appears that $new_product is also an array of two items,
{{ $new_product[0]->images[0]->image_name }}
Edit: Thomas Kim has a better answer
Your relation (images) is a collection object, if you all() method on that then you'll get the underlying array so then you can access any item from array using the index:
{{ $new_product->images->all()[0]->image_name }}
Also toArray() method will work:
{{ $new_product->images->toArray()[0]['image_name'] }}
So, either pass the array to your view like $new_product->all() or loop it. You may check the documentation here for more information about Collection object in Laravel.

Laravel Form Model Binding with Relationships

Is it possible to bind a form with a model that has relationships? For example I have a Order model that has a one to many with a Details model. That would save a lot of time with
#foreach($order->details as $detail)
{{ Form::text('product_name', Input::old('product_name') ? Input::old('product_name') : detail->product_name)
#endforeach
For a one-to-one relation it's possible to use something like this:
Form::text('detail[product_name]')
In this case $order->detail->product_name will be populated in the given text box if an instance of Order model is bound to the from using Form::model($order) with the related model Detail but it may not possible for one-to-many because simply there will be a collection and you need a loop.
To complete the answer of #WereWolf..
Make an array of product_name detail_names
Input class allow you to access nested array by dot notation, eg: orders.1.product_name
Don't forget the second argument of Input::old() or Input::get()
is the default value, so you can specify the DB value and avoid conditional test..
.
Form::text('detail_names['.$detail->id.']', Input::old('detail_names.'.$detail->id, $detail->product_name))
In your controller, something like that:
foreach(Input:get('detail_names') as $id => $product_name)
{
//...
}
Hope this will help you to save a bit of time.

Resources