Using ::find but with a custom where clause - php

I use ::find to find the business but business_position I need to use WHERE business_id = and WHERE id to find the correct position, and example is avalible below...
<?php
$s = Stats::find(Auth::user()->id);
$myJob = \App\Businesses::find($s->business_id);
$matchedValues = ['business_id' => $s->business_id, 'id' => $s->business_position];
$myPosition = \App\BusinessPositions::where($matchedValues)->get();
?>
And using $myPosition I use
{{ $myPosition->pay_amount }}
And on that line it throws and error...
Undefined property:
Illuminate\Database\Eloquent\Collection::$pay_amount (View:
C:\Users\Darren\MyLavProject\resources\views\pages\business\business.blade.php)

Laravel's get() returns a collection of results that match your query (even if there are none or just one, it'll be an array of Laravel model instances).
You can use first() instead of get() to grab the first result, or you can foreach through each of the results get() provides. It depends if your application permits more than one permission per business_id/id combination.

$myPosition This is an array of objects.
So if you need the result:
{{ $myPosition[0]->pay_amount }}
Or
#foreach($myPosition as $position)
{{ $position->pay_amout }}
#endforeach
Of if you don't want to use any of these:
Change your query to :
$myPosition = \App\BusinessPositions::where($matchedValues)->first();
Now you can use: {{ $myPosition->pay_amount }}

Related

Eloquent relationship fails to work unless dd()ed in view

Reference: Laravel Eloquent relationship not an object when doing anything but dd()
I am trying to output a Laravel relationship in Blade. However, this, {{ $video->channel->id }} returns a non-object error. But, when dded, like so, {{ dd($video->channel->id) }}, a value is there. I've been pulling my hair so hard because of this... What is going on? Why is there an output only when the variable is dded?
I'm testing on PHP 7.2 with Laravel 5.6. Relationships are established as per Eloquent documentation. I've tried fetching the data like this:
$videos = Video::where('foo', 'bar')->with('channel')->take(100)->get();
and
$videos = Video::where('foo', 'bar')->take(100)->get();
The same thing; same output/error.
$tokens = preg_split("/[\s,]+/", $q);
$videos = Video::with('channel')
->where(function ($query) use ($tokens) {
foreach ($tokens as $token) {
$query->orWhere('title', 'LIKE', "%$token%");
}
})
->take(100)
->get();
// foreach ($videos as $video)
{{ $video->channel->id }} // non-object error
{{ dd($video->channel->id) }} // WORKS! IDK Why...
Trying to get property 'id' of non-object is the actual error log.
EDIT:
Below is an image of the $videos collection fetched from Database.
If in dd(), something gets outputted fine, I can only assume I'm fetching the data right, yea?
As you're doing this in a loop, the error
Trying to get property 'id' of non-object
means that 1 iteration of $video->channel returns a non-object (likely null), and you can't access the property ->id of it (as null doesn't have any properties, etc.)
The reason dd() works is that it's dumping and dieing on the first iteration, which has a channel. To handle this, simply add an #if() clause:
#foreach($videos AS $video)
#if($video->channel)
{{ $video->channel->id }}
#else
...
#endif
...
#endforeach
Or, in the query to get $videos, enforce relationship:
$videos = Video::where('foo', 'bar')->has('channel')->with('channel')->take(100)->get();
This way, $video->channel will not be null.

Echo Data From Collection to Blade View

I am simply (for my own testing purposes) trying to take data from a collection and pass it to a view. I am using Laravel.
I am getting my data from the GitHub API, converting it and putting it in a collection. From here it's passed to a view, but I can't output each individual field.
Here's some code:
$httpClient = new Client();
$response = $httpClient->get('https://api.github.com/users/<randomuser>');
$json = json_decode($response->getBody(), true);
$collection = collect($json);
return view('github')->with('github', $collection);
and my Blade file is
#foreach ($github as $git)
{{ $git }}
#endforeach
Now I thought it would be something as simple as {{ $git->email }} to output it, but I don't think the array keys are been sent (?)
Can anybody point me in the right direction of where I am going wrong?
Thanks in advance.
-Chris
Because it's a key => val array, you should loop it as such...
#foreach ($github as $key => $val)
Key: {{ $key }} ~~ Value: {{ $val}} <br />
#endforeach
However if you are looking to just grab the email, use the Collection's get method.
$email = $github->get('email')
Simple use get() method in your blade
$github->get('login')
Try this,
in your controller use View and in function
$data['github_data'] = $collection;
return view('github', $data);
and in blade
{{ dd($github_data) }}
When you are working with Laravel try to check if you have the correct structure before trying to manipulate it.
In this case, check that:
You are getting what you expect in $response after call $httpClient->get (if you are using Guzzle).
You have a $json with the structure that you expect to receive.
You have a Collection instance after calling collect().
You can use dd() or var_dump() to see what data structure you have. What´s probably happening is that you don´t have the structure that you think.

Laravel Get item syntax

I use Laravel with foreach in a blade.php
{{ $users = App\User::where('user_id', $post->user_id)->get() }}
and I got the result of this which show on the page
[{"user_id":"123","email":"123#com","password":"1234","first_name":"Tony"}]
But I want to get "Tony" only, how can I call?
{{ ($users = App\User::where('user_id', $post->user_id)->first())->first_name }}
Or better in sense of performance, if you select posts with user:
{{ $post->user->first_name }}
But it is better to prepare necessary data in controller.
get() returns an array, you should use first()
{{ ($users = App\User::where('user_id', $post->user_id)->first())->first_name }}
Since you said you are using foreach in blade. Try something like this
#foreach($user as $u)
{{$u->first_name}}
#endforeach
This will give you first_name for all users

Using in_array on collections

I need to check for a name in an array of names but I having trouble passing an array instead of a collection to the in_array() method.
My blade code looks something like this
#foreach($ecn->areas as $area)
{{ $area->area }}:<br>
<ul>
#foreach($area->people as $person)
#if(in_array($person, $ecn->signatures->name ))
<li><del>{{ $person }}</del></li>
#else
<li>{{ $person }}</li>
#endif
#endforeach
</ul>
#endforeach
I know my problem is in the way im trying to access the list of signatures.
#if(in_array($person, $ecn->signatures->name ))
I can access them in another part of the page doing this
#foreach($ecn->signatures as $signature)
{{ $signature->name }}<br>
#endforeach
and everything is fine.
How can I access and pass the list of signatures as an array in this scenario?
If you want to use in_array() version for Laravel Collections then you can use:
$collection->contains($needle)
It woks just like in_array.
If $needle is an integer, an id for example, don't forget to pluck first, like so:
$collection->pluck('id')->contains($needle)
You can use the lists or pluck method on the signatures collection to get a new collection of all the names. From there, you can either use the contains() method on the collection, or you can use the all() method to turn the collection into an array and use in_array directly.
I would suggest doing this outside of the foreach loop, so you're not generating this new collection and array every iteration.
Array:
// controller
$names = $ecn->signatures->lists('name')->all();
// blade
#if(in_array($person, $names))
Collection:
// controller
$names = $ecn->signatures->lists('name');
// blade
#if($names->contains($person))
You can also use contains() with a closure, which would let you get away with not creating an intermediate collection, but it's a little harder to read:
Contains with closure:
// blade
#if($ecn->signatures->contains(function ($key, $value) use ($person) {
return $value->name == $person;
}))
As per Laravel Docs
The get method returns an array of results where each result is an instance of the PHP StdClass object.
So you must convert your stdClass object to a array in your controller itself.
foreach ($ecn->signatures as $signature)
$nameArray[] = $signature->name;
and then you can use in_array in the blade template
#if(in_array($person, $nameArray))

Laravel: Undefined offset in view index.blade.php

In my routes I have this route defined as:
// app/routes.php
Route::resource('CharacterController');
The corresponding method in the controller is:
// app/controllers/CharacterController.php
public function index(){
$characters = Character::all();
$houses = House::all();
return View::make('characters.index')->with(array('characters'=>$characters, 'houses' => $houses));
}
Finally, in the view:
// app/views/characters/index.blade.php
#this fires an error:
{{ $houses[$characters->house_id]->name }}
# at the same time this gives correct result:
{{ $houses[1]->name }}
# and this IS equal to 1:
{{ $characters->house_id }}
You can't use the id as index of the array to access the object with given id.
Since you have an Eloquent Collection you can use its various functions. One of them being find() for retrieving one item by id
{{ $houses->find($characters->house_id)->name }}

Categories