I’m trying to make a Eloquent query between models but I’m not being able to delivery the value to my controller.
I don’t know what is happening. In the log the value is showing, but the code are not getting it.
My Controller
$processedMaterialOrders = ProcessedMaterialOrder::get();
$sessionVariables = Session::all();
// Log::channel('ecom')->info($processedMaterialOrders);
$filteredProcessedMaterials = [];
foreach ($processedMaterialOrders as $key => $processedMaterialOrder) {
// Log::channel('ecom')->info($processedMaterialOrder);
$sectorId = $processedMaterialOrder->process->sector->id;
Log::channel('ecom')->info($sectorId);
My relationship
ProcessedMaterial
public function process(): BelongsTo
{
return $this->belongsTo(Process::class, 'process_id');
}
}
Process
public function sector(): BelongsTo
{
return $this->belongsTo(Sector::class);
}
Log is returning:
[2023-11-11 16:49:39] local.INFO: 5
[2023-11-11 16:49:39] local.INFO: 2
[2023-11-11 16:49:39] local.INFO: 1
[2023-11-11 16:49:39] local.INFO: 1
[2023-11-11 16:49:39] local.INFO: 2
[2023-11-11 16:49:39] local.INFO: 5
[2023-11-11 16:49:39] local.INFO: 5
[2023-11-11 16:49:39] local.INFO: 2
[2023-11-11 16:49:39] local.INFO: 1
That ids exists in the sectors table.
Error page
https://flareapp.io/share/q5Ywd0xP
Thanks!
I’ve tried to understand e change all my code but it is not working.
How something can be printed in the log but not in the page?
2
Answers
I've solved. It was database problems. One of the loop itens had no process_id.
Here are three steps you may consider to troubleshoot the issue:
Ensure that the relationships are being loaded correctly. You can
use eager loading to improve performance and ensure that the related
models are loaded. Modify your query to:
This will load Process and Sector relationships at the time of querying ProcessedMaterialOrder, reducing the number of queries to the database.
Ensure that the relationships in your models are defined correctly. From
what you’ve provided, they seem correct. However, double-check the
foreign keys and relationships in your
Process
andSector
models.You are already logging the
sectorId
, which seems to work as expected. If you need to debug further, consider logging the entire$processedMaterialOrder
object to see all its loaded relationships and attributes:Finally you may consider to add error handling to catch any potential issues. For example, you might want to check if
$processedMaterialOrder->process
or$processedMaterialOrder->process->sector
isnull
before trying to access the id.