Laravel isset with array value - php

I am having an issue - well because the value I am trying to pull from the DB does not exist yet.
Is there away that I check if its isset?
Is there any better way that I can get my value from the db to save on double code?
Controller:
$siteSocialFacebook = socialSettings::where('socialName','=','facebook')->get();
$siteFacebook = $siteSocialFacebook[0]['socialLink'];
Blade:
value="{{ old('facebook', #$siteFacebook)}}"

If you will only ever expect one result, use first() instead of get() and skip the array. You can pass it into the Blade template like this:
return view('blade', [
'siteFacebook' => $siteSocialFacebook['socialLink'] ?: null,
]);
This will prevent any issues with undefined parameters.
Edit: I just realized you're treating models as arrays. You can do this too:
return view('blade', [
'siteFacebook' => $siteSocialFacebook->socialLink,
]);
That handles it for you.

Related

How do i resolve Call to a member function only() on array error

I want to use laravels FormRequest to validate before updating some fields. This works fine if i just use:
User::find($application->userid)->fill($request->only('first_name'...
but the request also contains sub array ($request->programmeData).
array:2 [▼
"programme_id" => 5
"programme_title" => "some programme title"
]
if i try access that the same way i get 'Call to a member function only() on array':
Course::find($application->userid)->fill($request->programmeData->only('programme_id...
I've tried a handful of things, but not sure best way to go with this?
Update
I'm now using a foreach loop to save two items in the array. the example below saves the second value for both user_ids. any reason this isn't saving the first value for the first user_id?
foreach ($request->programmeData['userProgrammes'] as $key=>$userProgrammes) {
Course::where('application_id', $application->id)->get()[$key]->fill(Arr::only($request->programmeData['userProgrammes'][$key], ['programme_id']))->save();
}
but nothing updates. Any ideas on this one?
You can use Array::only() helper for this:
foreach ($request->programmeData['userProgrammes'] as $key=>$userProgrammes) {
Course::where('application_id', $application->id)->first()->fill([
$key => Arr::only($request->programmeData['userProgrammes'][$key], ['programme_id'])
])->save();
// or
$course = Course::where('application_id', $application->id)->first()
$course->$key = Arr::only($request->programmeData['userProgrammes'][$key], ['programme_id']);
$course->save();
}
//Arr::only($request->programmeData, ['programme_id', ...]);

Laravel rename collection keys

I have the following line to get an array of collections.
$tags = Tag::all()->map->only(['id', 'name']);
Which produces the following data.
[{"id":1,"name":"tag 2"},{"id":2,"name":"tag 3"},{"id":3,"name":"tag-44"},{"id":4,"name":"biyoloji"}]
My objective is to rename the key names inside the collections as follows.
[{"value":1,"text":"tag 2"},{"value":2,"text":"tag 3"},{"value":3,"text":"tag-44"},{"value":4,"text":"biyoloji"}]
Basically, I want to rename "key" to "value" and "name" to "text." I tried the pluck() function, get() function, mapping but couldn't get it to work. Most probably, iterating over it with foreach and toArray() would do the trick, but I'm looking for the proper way to do it. My environment is Laravel 8 with PHP 7.4
The best way I can propose:
$tags = Tag::query()->get(['id', 'name'])
->map(function($tag){
return [
'value' => $tag->id,
'text' => $tag->name,
];
})
->toArray();
Pay attention to get(['id', 'name]) invoking. Passing required fields to get method helps improving query performance. Specially if there are lots of unused columns in the table.
You can do this via your query more efficiently
$tags = Tag::get(['id as value', 'name as text']);

Laravel - Cannot Access Collection Indexes

For sure it's an understanding issue on my part. I'm just trying to create a collection in which the elements can be output.
Example:
So I want to be able to execute:
$collection=collect([
'index1' => 'data1',
'index2' => 'data2',
'index3' => 'data3',
]);
$row=$collection->first();
dd($row->index1);
Or similar.. But I get the error
trying to get property of a non object.
It's an understanding issue about Laravel collections, I've read the Laravel documentation which goes from basic usage, to API reference. I cannot find the information on how to produce this basic static collection.
Can someone help?
$row=$collection->first(); points to the value data1, not an object/array.
To get the expected behavior try the code below, it wraps each in individual arrays.
$collection=collect([
['index1' => 'data1'],
['index2' => 'data2'],
['index3' => 'data3'],
]);
$row=$collection->first();
dd($row->index1);
As Laravel collections implement ArrayAccess you can simply access collection items as you do with an array
$value = $collection['index1'];
or you can use the get method on collections
$value = $collection->get('index1');
Thanks for your answers, I see the $collection['index1']; format works.
It's not exactly what I wanted, let me explain why. I know there's probably a better way of doing it although, for the sake of this particular coding requirement I'd like to know the answer to this.
I'm building a CRUD blade form.
On my blade I'll have 'field1' with initial output of $dbcollection->field1
Now of course if the database returns a null (create required) this output will fail. So what I'm trying to do here is pass blade a NULL-filled collection it understands so at least it doesn't complain about non instance of an object and avoiding #if statements on the blade form to account for differences in coding format.
I believe this is what you are looking for:
Controller:
$collection=collect([
'index1' => 'data1',
'index2' => 'data2',
'index3' => 'data3',
]);
$row = $collection->first();
view:
<input type="text" value="{{ ($row->index1 ? $row->index1 : '') }}" >
.
.
.
.

Laravel Eloquent Pluck without losing the key

I have the following collection in Laravel:
["TheNumbers":[{"episodeID":16818,"episodeNumber":100,"created_at":null,"updated_at":null},{"episodeID":16818,"episodeNumber":210,"created_at":"2017-02-20 21:30:38","updated_at":"2017-02-20 21:30:38"}]
If I run the following code:
$TheEpisode->TheNumbers->pluck('episodeNumber');
I will get the following result:
[100,210]
I would like to keep the keys for each number, how can I achieve this?
EDIT: EXPECTED RESULT:
This is my expected result:
[{"episodeNumber":100},{"episodeNumber":210}]
PHILIS PETERS (improved)
TheEpisode->TheNumbers->reduce(function ($result, $episode) {
$episodeData = (collect())->put('episodeNumber', $episode['episodeNumber']);
$result[] = $episodeData;
return $result;
}));
Pluck() can take two params. The second of which is what the value can be keyed by.
You should be able to do:
$TheEpisode->TheNumbers->pluck('episodeNumber', 'episodeID');
Hope this helps!
Try something like this, it should work using map...
return $TheEpisode->TheNumbers->map(function ($episode) {
return ['episodeNumber' => $episode['episodeNumber']];
});
This can be simply achieved by passing a second argument to pluck. From the documentation:
You may also specify how you wish the resulting collection to be
keyed:
$plucked = $collection->pluck('name', 'product_id');
$plucked->all();
// ['prod-100' => 'Desk', 'prod-200' => 'Chair']
$collection->forget(['created_at', 'updated_at]);
This will simply left two first key-value pairs. Worth to keep in mind:
forget does not return a new modified collection; it modifies the collection it is called on.
Laravel docs
This should work properly:
$collection->only(['episodeID', 'episodeNumber']);
Try using
$TheEpisode->TheNumbers->lists('episodeNumber');
the key will remain.
Try using mapWithKeys like this:
$TheEpisode->TheNumbers->mapWithKeys(function ($theNumber) {
return ['episodeNumber' => $theNumber['episodeNumber']
});
I assume you want the result like this:
"TheNumbers":['episodeNumber':100,'episodeNumber':210]
For sake of updated Laravel, I tried all and I found
return Model::get(['name','id'])
will give reduced results with key => value.

CakePHP array() is empty, but query seems to be getting the correct results

I am trying to extract ONLY the PlanDetails where PlanDetail.company_id = Company.id AND PlanDetail.id' => $id.. ( you can see the conditions in my controller below)..
Controller:
function pd_list_by_company($id = null) {
$this->recursive = 2; // I am going to use containable to trim this.
return $this->PlanDetail->find('all',
array('conditions' =>
array('AND' =>
array('PlanDetail.company_id' => 'Company.id',
array('PlanDetail.id' => $id)))));
}
Test View:
$planDetailsByCompany = $this->requestAction('/planDetails/pd_list_by_company');
debug($planDetailsByCompany );
Output result of my debug??
Array()
If I remove the conditions and just have the find all, I get all PlanDetails as expected, so I know the data is being passed.. SQL debug dump even shows the query:
WHERE ((`PlanDetail`.`company_id` = 'Company.id') AND (`PlanDetail`.`id` IS NULL))
And yes, I did notice the $id is NULL, and I know the value needs to be there.. So maybe my question is why is the $id value not being passed to the controller even though I can see the PlanDetail.id value on a find('all') w/ out the conditions??
Thanks for any tips.
Since $id seems to be null, I would assume that you call the function without the parameter. And you don't get an error message, because as far as PHP is concerned the parameter is optional. In this case it's clearly required, so you should make it a required parameter in your function declaration:
function pd_list_by_company($id) {
Also you could simplify the return statement, you do not need the AND:
return $this->PlanDetail->find('all',
array('conditions' =>
array('PlanDetail.company_id' => 'Company.id','PlanDetail.id' => $id)
)
);
To answer the question why is the $id not being passed is because you're not passing it
To pass say $id of 2 you need to do the following in your requestAction
$this->requestAction('/planDetails/pd_list_by_company/2');
Seems to me that your code should just be
return $this->PlanDetail->find('array('PlanDetail.id' => $id));
Assuming you have the $this->PlanDetail->recursive flag set to > 0, your Model should already know about and return the associated data for any 'Company' table.....
I'm used to an old (1.3) version of CakePHP but the find() function is pretty basic and is designed to only return one row.
and yes, you definitely need to call the function with the id appended to the url, eg.
$planDetailsByCompany = $this->requestAction('/planDetails/pd_list_by_company/999');

Categories