I dont know what am I doing wrong, I have a foreach loop and a where consult inside it and when I try to get the data through that object, it says that it's and non-object and I cant get the data.
public function actualizar_costo_promedio()
{
$empresas = Empresa::all();
$anteriores_exist = 0;
foreach ($empresas as $empresa) {
$producto = $empresa->productos()->where('producto_nombre_id', 1)->first();
$anteriores_exist += $producto->existencias;
}
}
If i do this, it gives me that error but if I change the where for only $producto = $empresa->productos()->first(); it works
I've made other tests with $empresa = Empresa::find(1); and after do the consult $producto = $empresa->productos()->where('producto_nombre_id', 1)->first(); and also it works, so I don't understand what it's wrong
So let me tell you what is wrong, this piece of code:
$empresas = Empresa::all();
returns a collection or an array of arrays.
Now when you are foreaching you are iterating over the Empresa, but then you are accessing a relationship
$empresa->productos()
which from the error I can tell that it's a one-to-many relationship since the error is happening because the relationship is returning you another collection and you are trying to access a property which throws the error.
But when you pick up the first item in collection you actually access the first array in that array containing all the arrays! Therefore this is working:
$producto = $empresa->productos()->where('producto_nombre_id', 1)->first();
So if you want to make it work you need another iteration inside the foreach, or as I can understand correctly you want to get the existing products foreach Empresa you could do:
$anteriores_exist = $empresas->map(function($row) {
$products = $row->productos()->where('id', 1)->get();
return $products->filter(function($row) {
return $row->existencias;
});
});
Related
function subscriptionpack(Request $request)
{
$sub = subscription::all();
$details = $sub['details'];
dump('$details');
}
I can get all values from this code, but I can't get the specific field that named details. When I call dump($sub) it was shown all details, but the dump('$details') make an error that is undefined index:details
anyone can help me to correct this code?
You can use select method to select specific column data :
$sub = subscription::select('details')->get();
Or, you can do with on get() method as like :
$sub = subscription::get(['details']);
If you need single column from the result set use pluck
$subs = subscription::all();
$details = $subs->pluck('details')->toArray();
You can either loop over to your collection e.g
foreach($sub as $s){
dump($s->details)
}
or you can try something like.
$sub->first()->details
but this will give you only first details element from your collection.
First a model should be in singular, no spacing between words, and capitalised.
You should use Subscription::all(); not subscription::all();. You should read Laravel conventions
use App\Subscription;
..
function subscriptionpack(Request $request)
{
$sub = Subscription::all()->pluck('details');
dd($sub);
}
After adding Paginate function I'm getting this error
$sub_categories = SubCategory::where('id', $id)->first();
$products = Products::where('subcategory_id', $sub_categories->id)->get()->paginate(10);
$sub_categories = SubCategory::where('id', $id)->first(), this will only give you null or one record, not a collection, so you can not use ->paginate(10); chain it. You will only get one record at the most, why you need to paginate?
Update
so first for the sub_categories you do not need to paginate, as you just want one record. so the code should be like this.
$sub_categories = SubCategory::where('id', $id)->first();
second, if you want to paginate $products you should do this,
if ($sub_categories)
{
$products = Products::where('subcategory_id', $sub_categories->id)->paginate(10);
}
I am trying to loop through an array of ids to get data from another table, I mean I want to get latest queues of every schedule id we are looping in it.
So first i have $schedules:
$schedules = [{"id":19},{"id":18},{"id":15}]
And the foreach loop is like this:
$queues= [];
foreach ($schedules as $schedule) {
$queues[] = Queue::withTrashed()
->latest()
->where('schedule_id', $schedule);
}
return $queues;
when i return queues it's showing :
Object of class Illuminate\Database\Eloquent\Builder could not be converted to string
The error that shows is related to you are not running the query, you need a ->get() at the end of Queue::...->where(...)->get() to do it.
if you dont do it, as Dhananjay Kyada say in his answer:
it will try to return a query object
But to return a response:
The Response content must be a string or object implementing __toString()
Next, we need to tackle one more thing.
If you are defining the variable $schedules and assigning it the value as it is shown in the question:
$schedules = [{"id":19},{"id":18},{"id":15}]
try to do it taking the JSON as string and converting it into a PHP variable with json_decode:
$schedules = json_decode('[{"id":19},{"id":18},{"id":15}]');
Then you can use the id values in you where clause:
->where('schedule_id', $schedule->id)->get()
Maybe because you are not getting the result from your query. Because it is just a query it will return a query object. You need to add ->get() in order to get the result. You can try the following code:
$queues = [];
foreach ($schedules as $schedule) {
$queues[] = Queue::withTrashed()
->latest()
->where('schedule_id', $schedule)->get()->toArray();
}
return $queues;
I am trying to replicate certain data in my DB and I followed the steps as in the following link. Laravel 4: replicate to table
However, I need to replicate some other data using only a foreign key.I tried to use the find() method to get my data but returned nothing.The where clause returns my data but in the form of array which isn't accepted by the replicate method.
Anhy idea what i am doing wrong and how can I replicate my other data?!
Code:
$item = Cv::find($cv_id);
// return $item;
$clone = $item->replicate();
unset($clone['created_at'],$clone['updated_at']);
$data = json_decode($clone, true);
Cv::create($data);
//Skills
// return $cv_id;
$skills = Skill::where('cv_id', $cv_id);
$cloneSkills = $skills->replicate();
unset($cloneSkills['created_at'],$cloneSkills['updated_at']);
$skillData = json_decode($cloneSkills,true);
Skill::create($skillData);
For replicating skills you should probably use:
$skills = Skill::where('cv_id', $cv_id)->get();
foreach ($skills as $skill) {
$cloneSkill = $skill->replicate();
unset($cloneSkill['created_at'], $cloneSkill['updated_at']);
$skillData = json_decode($cloneSkill, true);
Skill::create($skillData);
}
You need to use get() to get all data and because $skills is Collection you need to use loop to replicate each skill.
I have a Poll table, a Students table, and a pivot table between them that includes a token and their three votes.
public function students()
{
return $this->belongsToMany('Student', 'polls_students')->withPivot('token','first','second','third');
}
While working out saving the poll results, I came across some odd behavior that I don't quite understand. I'm hoping somebody can explain what it is I'm missing:
$poll = Poll::find(Input::get('poll_id'));
foreach($poll->students()->where('students.id', '=', Input::get('student_id'))->get() as $student){
var_dump($student->pivot->token);
}
$student = $poll->students()->where('students.id', '=', Input::get('student_id'))->get();
var_dump($student->pivot->token);
In the above code, the foreach loop will successfully display the token, where the second one throws the exception Undefined property: Illuminate\Database\Eloquent\Collection::$pivot
What am I missing? Are these two calls not logically creating the same object? How is 'pivot' working on the first and not the latter?
You first example:
$poll = Poll::find(Input::get('poll_id'));
foreach($poll->students()->where('students.id', '=', Input::get('student_id'))->get() as $student){
var_dump($student->pivot->token);
}
Here $poll->students() retrieves a collection and because of foreach loop you get a single object in your $student variable and you can use $student->pivot->token
You second example:
$student = $poll->students()->where('students.id', '=', Input::get('student_id'))->get();
var_dump($student->pivot->token);
Here you are doing same thing, using $poll->students() you are getting a collection but this time you are not using a loop and trying to do same thing using $student->pivot->token but it's not working because you didn't define any index from which you want to get the pivot->token, if you try something like this
$student->first()->pivot->token
Or maybe
$student->get(1)->pivot->token
Or maybe you can use first() instead of get() like this
$student = $poll->students()->where('students.id', '=', Input::get('student_id'))->first();
Then you can use
$student->pivot->token
Remember that, get() returns a collection even if there is only one record/model.
$poll = Poll::find(Input::get('poll_id'));
foreach($poll->students as $student){
var_dump($student->pivot->where('student_id',$student->id)->where('poll_id',$poll->id)->first()->token);
}