27,357 questions
Best practices
0
votes
6
replies
119
views
MySQL Eloquent ORM - where clause: value could be null
I'm a bit unsure about how to proceed with Eloquent ORM (Laravel 12) queries when a value COULD be NULL.
Normally, you would check for a NULL value with:
->whereNull("column")
But if you ...
4
votes
2
answers
151
views
How do you move the function definition for the ->when() function in Laravel Eloquent Models?
I'm building a way to organize Items based on different requests:
$items = Item::query()
->where("type", $itemType)
->when($mode, function (Builder $query, $mode) {
...
0
votes
1
answer
56
views
Query timing out despite making several changes
I have the following query:
$countries = Country::with('place.details')->get();
My website is timing out running this query, even when I set the timeout to 10+ minutes.
I discovered that if I ...
2
votes
1
answer
67
views
PHPStan complains about @var Builder<ProductTemplate> in Laravel Eloquent scope
I'm trying to define a Laravel Eloquent model with a custom scope that filters categories by a related product's vendor_id. Here's my setup:
class Category extends Model
{
public function ...
2
votes
2
answers
118
views
Avoiding redundant data in an Eloquent model Instance
I encountered an issue while working on a Laravel project of mine, intended for property rentals. In the database, both the property owner’s and the tenant’s contact information are stored in the same ...
3
votes
1
answer
80
views
Problem Searching Using Blind Index in Laravel
I am developing an application that contains sensitive data, and I want this data to be encrypted while still being searchable through the application code.
I found a solution using the CipherSweet ...
1
vote
0
answers
114
views
does database chunk() have a memory leak?
In laravel, I have a query that searches thousands of rows in a database, and I trying to compile that into a CSV file. In attempt to reduce memory usage, I get 500 rows at a time and output the CSV.
...
3
votes
2
answers
95
views
Automatically set timestamps on polymorphic relation table
I have a ProductLandedCost model with a morphToMany relationship to various other models: Warehouse, for example:
class Warehouse extends Model
{
// ...
public function productLandedCosts(): ...
0
votes
1
answer
105
views
Laravel migration creates wrong columns and data mismatch in employers table
I’m building a job board project in Laravel, and I’m trying to establish a one-to-one relationship between User and Employer. However, my database table is not being generated correctly — the columns ...
0
votes
0
answers
83
views
Defining a BelongsToMany relation with an additional where clause
I have a belongs to many relation between two tables via a pivot table. But the business dictates that the relation needs an additional WHERE clause connecting the first with the last table.
table_a ...
0
votes
1
answer
157
views
How to change model to export from filament resource to exporter class
I have an application that uses filament 3.2 and in this application I have a resource called "Students", within this resource I am calling a "Tables\Actions\ExportBulkAction" that ...
0
votes
1
answer
50
views
How do relation for column Backpack from relation of model?
I tried do table with relations with three models Orders, Users and Chats.
Model includes with (->with('orders'), ->with('users'), etc).
How I can indicate in Backpack column name of relation ...
0
votes
0
answers
62
views
How does Eloquent's new Laravel 11 HasScopedValues feature address it and how is it different from casts?
In Laravel 11, Eloquent introduced HasScopedValues to define scoped values for model attributes somewhat like $casts. I’m unclear how it differs from $casts can it transform values like casts or is it ...
0
votes
1
answer
67
views
Laravel Eloquent option for return null in hasOne/belongTo relation
Is there an elegant way to return null from one-to-one relation based on other model's field? Eg. I have ModelA with field1, $field2. Maybe raw joins suitable for that and could be used in relations? ...
1
vote
0
answers
95
views
Livewire pagination with collections and calculated fields
I have an issue where I need to paginate an eloquent collection that has calculated fields, fields not in the database. Livewire's WithPagination trait only wants to be applied to an Eloquent query ...
0
votes
1
answer
122
views
Laravel query existence of relationships
I need to check just existence of Laravel model relationships. Is there a loader similar to withCount? Eg
// with count
$authors = Author::withCount('books')->get();
foreach ($authors as $author) {
...
0
votes
1
answer
40
views
What causes the error "Invalid parameter number" when using union() function in Laravel model?
I can't understand what happened, it all worked before.
I have a model:
class MyModel extends Model
{
protected $table = 'table1';
use HasFactory;
public function rel()
{
return ...
0
votes
2
answers
89
views
Select top users based on their Recipes popularity
I am trying to get the top of users and order them by popularity of their recipes
The popularity of a recipe is determined by the number of:
likes
dislikes
(likes and dislikes are stored in ...
2
votes
1
answer
90
views
Using Eloquent ORM Outside of Laravel - Getting Error: Unsupported driver [oracle]
PHP Version 7.4.33
I am trying to use Eloquent outside of Laravel and it is throwing the error "Unsupported driver [oracle]" Apparently there is still some connection that needs to be made ...
0
votes
1
answer
86
views
global scopes for get , all and paginate function in laravel
I write a trait in laravel named prioritiable and I add a global scope to the query to sort the query result based on priority value
The problem is the scope add the order by SQL clause to all SELECT, ...
0
votes
2
answers
78
views
Is it possible to combine collections in Eloquent relationships in Laravel?
I have a query that can get data on 3 relationships as a result: Relationship1, Relationship2 and Relationship3. But the problem is that in some cases, there may be fewer of these relationships. Tell ...
3
votes
2
answers
66
views
Is it possible to create an instance of a model with a relationship?
I create a model instance to add a record to the DB, and after using the save() function I pass the added object to the DB for further processing, but I can't get data from the added record via the ...
0
votes
0
answers
61
views
Eager loading date dimension sending query with hundreds of parameters
I have an Entry model which has the below relation to a date dimension model:
class Entry extends Model
{
public function date() : HasOne {
return $this->hasOne(Date::class, '...
0
votes
1
answer
68
views
What is the best way to find a record from an Eloquent collection by relationship?
I get data from related tables via the eloquent model and want to access the collection pulled in via the relationship, how to do this correctly and quickly, is it possible?
When debugging the code ...
1
vote
1
answer
53
views
retrieve data using where condition and sort in descending order
I am trying to retrieve category (id, category_name, status) table data using where condition and sort in descending order for id. I am writing query like::
public function category()
{
$...
0
votes
1
answer
100
views
Is it possible to get multiple different selections from a relation in laravel?
I need to select one record by several conditions from a link. I need several records to be randomly selected from linked table #2 by different conditions.
Here is the code I wrote, but it only works ...
2
votes
1
answer
99
views
Eloquent Boot or Booted method in Model is never called in my model class
When i create a model with eloquent and i wan't to use boot or booted method static for trigger an action, is never triggered.
Laravel 12 Eloquent
<?php
namespace App\Models;
use App\Traits\...
2
votes
0
answers
96
views
How to manage BelongsToMany relationship in Laravel with API Platform?
I'm working with API Platform for Laravel and encountering difficulties managing BelongsToMany relationships. While BelongsTo and HasMany relationships work seamlessly by sending IRIs in the request ...
3
votes
1
answer
86
views
Eloquent model producing infinite loops with any queries
I have a Model with a protected $withCount property, and it always gets into an infinite loop. If remove that property, the model will return data. The project I am working in has another Model using $...
3
votes
1
answer
84
views
How to query models with a where condition on the pivot table using a many-to-many relationship?
I have two models, User and Role. These two models have many-to-many relationship between each other with pivot table role_user. In this pivot table are values user_id, role_id and meta_value. ...
1
vote
1
answer
98
views
Table prefix not used as expected in Laravel 9
I'm working on a laravel app that used to work, but I don't know why after a few modifications on different setups, I cannot make it work as expected locally.
Symptoms
Queries from models accessing ...
0
votes
0
answers
73
views
Livewire 3.0 Component returns 404 error when using Model::get() but works with Model::get()->toArray() - why?
I faced a strange 404 error when working with Livewire 3.0 (maybe because I use nested components - didn't tested on a single component yet) when passing a Model Object to the data of the view of a ...
1
vote
2
answers
74
views
Laravel Eloquent: how to implement INNER JOIN with condition
I need to get INNER JOIN with condition by Laravel Eloquent (no Database Query!).
with with condition works as LEFT JOIN:
Project::with(['tasks' => condition_for_tasks])
Here I got ALL project ...
1
vote
1
answer
59
views
How to set sorting in sql request on detailed fields?
I have laravel 12/ postgresql 17 app I have a function request with related tables and nullable parameters :
public function getByActionId(int $actionId, ?int $districtId = null): Collection
{
$...
1
vote
1
answer
60
views
Laravel Eloquent Get the Group with the highest Member Points
I have two tables, Members and WhatsAppGroup.
Each Member belongs to a WhatsAppGroup and a WhatsAppGroup hasMany Members.
Each Member accumulates Points for their activities. On the Members table, ...
1
vote
1
answer
87
views
Eloquent query for filter with multiple params from url (Some parameters may not be specified)
I am new for Eloquent Query Builder and I have some questions:
Goal: Create a query that will get me recipes that match the specified parameters from selectors:
Dish Category
Dish Subcategory
Cuisine
...
2
votes
0
answers
101
views
Schema::hasColumn() returns false for existing SQL table columns using Laravel and external database connection
I'm working on a Laravel 12 project that connects to a Microsoft Dynamics CRM SQL Server database through a custom connection. I've run into a puzzling issue: Laravel's Schema::hasColumn() returns ...
-1
votes
1
answer
51
views
Database question about simple Categories & Subcategories. Laravel 11
I want to have Categories with related Subcategories, It must looks like this:
Category: Broth
Subcategory: Chicken broth, Meat broth, Vegetable broth
And I'll create create_categories_table & ...
1
vote
1
answer
103
views
Laravel N+1 when accessing a pivot relationship and the related model (unit)
I got n+1 query while working with my models and pivot
Recipe.php:
public function user(): BelongsTo
{
return $this->belongsTo(User::class);
}
public function ingredients():...
0
votes
0
answers
51
views
Unable to call the faqs in proper sequence in laravel, succeded in fetching data but not in that way which i wanted
What I'm trying to build
I'm working on an FAQ system. At the top level, there's FaqType, which represents the type or category of FAQs.
Each FaqType can have one or more FaqSubtypes, and under each ...
-4
votes
2
answers
123
views
Convert this Eloquent model function to a MySQL query? [closed]
I need to convert this Eloquent Model Function to a MySQL Query:
public function currentPrice(): HasOne
{
return $this->hasOne(Price::class)->ofMany([
'published_at' =>...
0
votes
1
answer
78
views
How to update a Laravel Eloquent data, calculating a date diff
I have this problem.
I need to update all data from a Table, each time incoming batch finishes inserting.
What I have to do is:
Incoming data has CreationDate, so I need to do a DIFF with current date,...
1
vote
0
answers
109
views
How to Eager Load Aggregated Fixtures from Original and Duplicated Competitions in Laravel?
I'm working with a database design where competitions can be duplicated, and I need to efficiently query original competitions along with aggregated fixtures from both the original and duplicated ...
2
votes
1
answer
115
views
Is it possible to setup a permanent property on a Laravel Eloquent model using withCount()?
I have a Laravel Eloquent model called Team that has a hasMany relationship to users. Is it possible to easily setup a user_count property that is permanently on a Team model? or do I always need to ...
0
votes
1
answer
104
views
Aggregate for custom attribute
My tables are: projects -> tasks -> commands
Trying to calculate average on field duration
Project::with('tasks.commands')->withAvg('commands', 'duration')
It can't work because Eloquent ...
2
votes
1
answer
48
views
Laravel Eloquent: aggregate for table
My tables (and Laravel models relations):
projects -> tasks -> commands
Calculate count of tasks:
$body = Project->withCount('tasks')->get();
Fine.
Then I want to calculate count of ...
0
votes
1
answer
57
views
Image tag not rendering on Gmail but will render on Outlook
Using laravel, I have a method in my controller that is taking the base path of a .png file and base64 encoding it before sending it to my blade template. The image is able to be rendered on outlook ...
1
vote
1
answer
61
views
How to find model with condition on multiple relationship?
I have the following model with two one-to-many relationship:
class Dad extends Model
{
public function sons()
{
return $this->hasMany('App\Models\Son', 'dad_id');
}
public ...
0
votes
0
answers
50
views
How can be used TagsInput component to store related data using model hasmany relationship?
I have eloquent model to store specific car brand model years:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
class CarModel ...
-2
votes
2
answers
110
views
Eloquent query returning null when using a variable
I am having a issue where when i write out a eloquent query using a variable it is returning NULL but if i write out that variable value in text it returns data.
This is my code
$code = 'Test123';
...