Browse AI Field GuideForum Podcast
All ThreadsLeaderboard
  1. Discussions

    1. Popular This Week
    2. Popular All Time
    3. Solved
    4. Unsolved
    5. No Replies Yet

Johny22's avatar

Query

Hi how could I retrieve data with such a query? The point is, I would need to save the category and country in as a result of filtering. He tried foreach but it didn't work. Need to call another function on the builder? $categoryId = $request->get('category_id'); $countryCod = $request->get('country_code'); $country = Country::query()->with('categori

Johny22's avatar
Johny22's avatar Johny-225yrs agoEloquent
8
1
Last reply by Johny-22 5yrs ago
Virys's avatar

Query

I am doing a query on tables that presents some columns with the same name as is the case "created_at", precise guidance on how to do to specify which field of the table I will display.

Virys's avatar
Virys's avatar bobbybouwm...6yrs agoLaravel
1
1
Last reply by bobbybouwmann 6yrs ago
Aronaman's avatar

query

$status_id = BookStatus::where('name', 'Booked')->firstOrFail()->id; $check_in =$check['check_in']; $check_out=$check['check_out']; $booking_id=$room->bookings()->with('individualRooms')->get(); $booking_list=$booking_id->pluck('individual_rooms'); $roomNeverBooking =$room->individualRooms()->whereNotIn('id',$booking_list)->g

Aronaman's avatar
Aronaman's avatar ahmeddabak6yrs agoLaravel
3
1
Last reply by ahmeddabak 6yrs ago
davy_yg's avatar

query

Hello, I am trying to analize this related table. ProductCatalogsRepository.php public function listAllCatalog() { $query = $this->model->where('flag_product', FlagEnum::CATALOG)->latest(); if (request('search')) { $keyword = request('search'); $query = $query->whereTranslationLike('name', '%' . request('search') . '%');

davy_yg's avatar
davy_yg's avatar tisuchi6yrs agoEloquent
2
1
Last reply by tisuchi 6yrs ago
davy_yg's avatar

query

What does this query means? $query = Products::query();

davy_yg's avatar
davy_yg's avatar tykus6yrs agoEloquent
3
1
Last reply by tykus 6yrs ago
pafait's avatar

query

HI every one please can some help me write this SQL query into laravel eloquent SELECT SUM(price) FROM ( SELECT COUNT(STOCK_ID)*Price FROM STOCK ST INNER JOIN PRODUCT PDT ON PDT.PROD_ID=ST.PROD_ID WHERE PROD_NAME='PENCIL' GROUP BY STOCK_ID LIMIT 6 ) TB This is what i try out but am messing the whole ting DB::(table_stock) ->where(['tbl_stock.product_id',

pafait's avatar
pafait's avatar spekkionu8yrs agoEloquent
4
1
Last reply by spekkionu 8yrs ago
ricardosoares's avatar

Query

My question is, i have users table, roles table, role_users table, and i want to make the list of all users, and the roles for each user, but doing it obviously is just returning me the id, and now how can i go pickup the name on the roles table? I guess i can do it with join but it's the best way? or there is a better way to do it? Query on controller $users = User::Join('rol

ricardosoares's avatar
ricardosoares's avatar willvincen...9yrs agoLaravel
10
1
Last reply by willvincent 9yrs ago
Aronaman's avatar

query

sorry

Aronaman's avatar
Aronaman's avatar ahmeddabak6yrs agoLaravel
1
1
Last reply by ahmeddabak 6yrs ago
Aronaman's avatar

query

sorry

Aronaman's avatar
Aronaman's avatar ahmeddabak6yrs agoLaravel
1
1
Last reply by ahmeddabak 6yrs ago
vibe's avatar

Query

I have one problem I want whenever user login one table should show the list of client of his department. how can I pass the user department value to my controller without submitting the request

vibe's avatar
vibe's avatar vibe8yrs agoLaravel
7
1
Last reply by vibe 8yrs ago
vibe's avatar

query

I need help i want to display the patient who has the body temp more the 45 from the database i am getting the clue because it is in the relationship table

vibe's avatar
vibe's avatar vibe8yrs agoLaravel
3
1
Last reply by vibe 8yrs ago
afoysal's avatar

Query

I downloaded the vue.js and found Vue.config.productionTip = false in main.js file. Could anyone say what is the meaning of that code ?

afoysal's avatar
afoysal's avatar topvillas8yrs agoVue
1
1
Last reply by topvillas 8yrs ago
pafait's avatar

query

Hello everyone there is this problem i am facing. i have the total cost of a product i am trying to calculate. The product has the same Product_ID but different Stock_ID. I explain. Let say the product is PENCIL, i have two stocks where i bought the first 5pencils at a rate of 100 and the remaining 5pencils at a rate of 120. Now i want to sell out 6pencils at the rate at whic

pafait's avatar
pafait's avatar pafait8yrs agoLaravel
2
1
Last reply by pafait 8yrs ago
yassinali's avatar

Query

How can i retrive data using between in laravel 5

yassinali's avatar
yassinali's avatar bestmomo10yrs agoEloquent
4
1
Last reply by bestmomo 10yrs ago
Aronaman's avatar

DB Query relationship

query

Aronaman's avatar
Aronaman's avatar tykus6yrs agoLaravel
1
1
Last reply by tykus 6yrs ago
jswoolf01's avatar

Query on parent-table condition or child-table condition

Situation: I have three tables: Product (inventory products), Flags (indicator flags that show 'something needs attention'), and Rules (rules for creating Flags). The relationship chain goes product->flags->rules. Each product can have many flags, while each flag belongs to one rule (but one rule can have many flags). We're transitioning to a new way of defining and han

jswoolf01's avatar
jswoolf01's avatar jswoolf013mos agoEloquent
3
6
Last reply by jswoolf01 3mos ago
adamnet's avatar

No repeating Eloquent query statements in the mathods of a controller

I have an Eloquent model query with quite a few statements which is repeated the same in almost all the methods of a controller. Is there a way to save it somewhere and call it with a name into the methods of the controller with a single line?

adamnet's avatar
adamnet's avatar vincent150...5mos agoLaravel
13
11
Last reply by vincent15000 5mos ago
ella-stinnes's avatar

Duplicate Query when Passing Eloquent Query to Blade Component

I have the following select blade component: @props([ 'id' => '', 'options' => array(), ]) <select name="{{ $id }}" id="{{ $id }}"> @foreach($options as $value => $name) <option value="{{ $value }}">{{ $name }}</option> @endforeach </select> I'm then using this component as foll

ella-stinnes's avatar
ella-stinnes's avatar Snapey7mos agoLaravel
13
1
Last reply by Snapey 7mos ago
minaremonshaker's avatar

Code Review: Spatie Query Builder Implementation with Multiple Search Filters - Best Practices?

I'm working with the Spatie Laravel Query Builder package (v6) and would like some feedback on my current implementation. I'm creating a search functionality with two filters and want to know if there are any technical issues or improvements I should consider. Here's my current code: $request = \Illuminate\Http\Request::create("/users", "GET", [ "filt

minaremonshaker's avatar
minaremonshaker's avatar minaremons...8mos agoCode Review
7
80
Last reply by minaremonshaker 8mos ago
jaspercreel's avatar

Customizing query using 'with' eliminates results

Hi all, Ran into a funny thing. I have a pretty robust query I am using to pull data for a report. Lots of joins and withs. I ran into an issue where a relationship of a relationship would disappear from the results when I tried to customize the query. For example, this works: ->with([ 'deliverables.timeEntries' ]) But this doesn't: ->with([ 'deliverables.timeEntries

jaspercreel's avatar
jaspercreel's avatar jlrdw9mos agoEloquent
2
1
Last reply by jlrdw 9mos ago
justindantzer's avatar

Altering an action query

I'm running into a roadblock in trialing some resource list tooling. Looking into user-selectable fields, I came across this column-toggler package. While it does update the visible columns, it does not affect the result when using the ExportAsCsv action. I've dug into the repo a bit to see how the resource query gets updated, which is apparently done by overriding the resource

justindantzer's avatar
justindantzer's avatar LaryAI9mos agoNova
1
1
Last reply by LaryAI 9mos ago
elvisisking's avatar

PHPStan custom query builder usage in whereHas

I'm struggling a bit with phpstan. I'm using laravel 11.45 with phpstan 2.1.22 and larastan 3.6.0. I'm wondering if there is a way to support phpstan to properly understand the situation before I give up and ignore the error. I have the following query in a controller: $disputesWon = $user->productPurchases() ->whereHas('dispute', fn ($q) => $q->

elvisisking's avatar
elvisisking's avatar elvisiskin...10mos agoEloquent
3
30
Last reply by elvisisking 10mos ago
sajadsholi's avatar

global scopes for select query

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, DELETE , UPDATE , INSERT but I want to just to have the scope on select so I did this trait Prioritiable { protected static function bootPrioritiable(): void { sta

sajadsholi's avatar
sajadsholi's avatar Glukinho10mos agoLaravel
10
3
Last reply by Glukinho 10mos ago
EMax's avatar

Query parameter with same name but different values without brackets=

I currently have the task of consuming some data from an API. Current implementation requires filtering by query paramters, however to filter for a subset of persons you have to add the same query parameters multiple times with different values API DOC: https://developer.personio.de/reference/get_v2-attendance-periods. URI for a request would have to look like this: https://ap

EMax's avatar
EMax's avatar krisi_gjik...10mos agoLaravel
2
31
Last reply by krisi_gjika 10mos ago
iqbalrafli13's avatar

Emoji or Unicode characters break when saving via Eloquent to SQL Server NVARCHAR – works with Query Builder

Hi everyone, I’m running into a strange problem with Unicode (emoji) characters not saving correctly when using Eloquent in Laravel. I’m trying to save emoji characters like ✅ into a SQL Server NVARCHAR column. If I use Laravel’s query builder, everything works: DB::table('cabang')->insert(['kodecabang' => '✅']); The emoji gets saved and displays correctly. But if I u

iqbalrafli13's avatar
iqbalrafli13's avatar nara0148mos agoEloquent
4
1
Last reply by nara014 8mos ago
Rretzko's avatar

Error when using concat() in query: "syntax error, unexpected token "as", expecting ")"

Hi all - I'm trying to use the following query in a Livewire v3 method but am getting the error: "syntax error, unexpected token "as", expecting ")". Here's the query: Member::query() ->join('students', 'students.id', '=', 'ensemble_members.student_id') ->join('users', 'users.id', '=', 'students.user_id') ->

Rretzko's avatar
Rretzko's avatar Rretzko11mos agoLivewire
2
1
Last reply by Rretzko 11mos ago
RiadhKHEDHIRI's avatar

Collection loosing relations and run into N+1 query problem in Livewire

Trivial example here, nothing crazy. I am loading posts with users info in mount. Everything works fine until I call createPost. What am I missing? public function mount(): void { $this->posts = Post::query()->orderBy('created_at', 'desc')->with('user')->take(10)->get(); } public function createPost(): void { $this->authorize('create', Post::class);

RiadhKHEDHIRI's avatar
RiadhKHEDHIRI's avatar RiadhKHEDH...1yr agoLivewire
5
1
Last reply by RiadhKHEDHIRI 1yr ago
vincent15000's avatar

Strange SQL query from Eloquent

Hello, I have this query. $companies = Company:: with('admin') ->withCount('users', 'products', 'sales') ->orderBy('name') ->get(); And the corresponding SQL query is. select `companies`.*, (select count(*) from `users` where `companies`.`id` = `users`.`company_id` and `users`.`deleted_at` is null) as `users_count`, (select count(*) from `products` whe

vincent15000's avatar
vincent15000's avatar EricZwart1yr agoEloquent
4
1
Last reply by EricZwart 1yr ago
r9host's avatar

How do I do this db query with eloquent?

Hi friends, I have a case where I need to have a special "WHERE" clause that include a some criteria to be ORed then the result be ANDed with other criteria. I'm not able to achieve this by chaining where() and orWhere() methods. The query should look like this: SELECT bank_transactions.*, journal_entries.bank_transaction_id, journal_entries.description FROM bank_tran

r9host's avatar
r9host's avatar akramghale...1yr agoEloquent
9
1
Last reply by akramghaleb 1yr ago
AsnCode's avatar

exists() methods cause some n + 1 query

Hello i have an app that cause me many + 1 duplicate query, with the help of N + 1 query detector from spatie i have isolate the problem : public function hasLiked(Post $post): bool { return $post ->likes() ->where('user_id', $this->id) ->exists(); } inside my laravel debugbar : select exists(select * from "l

AsnCode's avatar
AsnCode's avatar Snapey1yr agoLaravel
4
1
Last reply by Snapey 1yr ago
dmytroshved's avatar

How to query pivot table and related data in laravel query builder

Hey everyone, I need to get this data for recipe: related users with name and photo (foreign key in recipes table: user_id) related ingredients with name of ingredient name and unit name (pivot table ingredient_recipe) users: id, name, photo (necessary columns: name & photo) ingredient_recipe (pivot table): id, recipe_id, ingredient_id, quantity, unit_id ingredients: id

dmytroshved's avatar
dmytroshved's avatar Snapey1yr agoLaravel
6
2
Last reply by Snapey 1yr ago
dmytroshved's avatar

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 Menu important nuance: in selectors you can't select a subcategory without first selecting a category (dependent dropdown logic using livewire). After selecting parameters in sel

dmytroshved's avatar
dmytroshved's avatar jlrdw1yr agoLaravel
3
1
Last reply by jlrdw 1yr ago
prince69's avatar

How optimize query performance?

I have 1M+ records. The code below works, but it takes too long to load because I'm using get() and then filter based on request data. I tried using SQL groupBy() directly, but got a MySQL ''Syntax error or access violation: 1055 Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregated column'''. For this I do not want to change strict mode false in con

prince69's avatar
prince69's avatar vincent150...1yr agoLaravel
11
1
Last reply by vincent15000 1yr ago
dadino80's avatar

Eloquent query vs Collections

Hi at all, I am Davide and this is my first post on this FORUM. I am a computer and programming enthusiast and I am working on a project to manage the day off of employees of the Company where I work. I have a parent calendar component and nested days child components. The parent component retrieve all the day off request from database with an Eloquent query and then it passes

dadino80's avatar
dadino80's avatar jlrdw1yr agoTips
1
6
Last reply by jlrdw 1yr ago
aarontharker's avatar

Eloquent query behaving differently in Livewire page

I'm using the following query to select posts to display $posts = $this->category->postsPublished() ->whereNot(function ($query) { $query->withAnyTagsOfAnyType(['Guest Post', 'Press Release']); }) ->when($this->year, function ($query) { $query->whereYear('published_at', $this->year); }) ->when($this->month, funct

aarontharker's avatar
aarontharker's avatar Snapey1yr agoLivewire
2
1
Last reply by Snapey 1yr ago
MauricioMateus's avatar

Laravel Insert urls with query string causes performance issue

Hello: Please see the example below: $data = collect(range(0, 300))->map(fn () => [ // 'googleDriveDocument' => Str::random('180'), // 'googleDriveDocument' => 'https://docs.google.com/document/d/16jabcPOytUWDTXv1QjAau5123453K5r2NbxtU/edit?usp=drive_link', 'googleDriveDocument' => 'https://docs.google.com/document/d/16jubu123

MauricioMateus's avatar
MauricioMateus's avatar fullstacka...9mos agoEloquent
7
1
Last reply by fullstackalien 9mos ago
JimNayzium's avatar

Query Builder vs. Stored Procedure for something fairly complex?

I am finding whenever the procedure of updating my database is pretty complex, and requires multiple tables, that doing it all in Laravel or in PHP takes 10-100 times longer to execute than just coming up with the very complicated storedProcedure to keep on the mysql side and run whenever I need it. Is this a "no-duh" type thing to experienced developers? That doing t

JimNayzium's avatar
JimNayzium's avatar Tray21yr agoLaravel
11
5
Last reply by Tray2 1yr ago
yonka's avatar

Restore or Permanantly Delete using Query Builder not eloquent

I want to be able to restore or permanently delete soft deleted record by using Query Builder not Eloquent

yonka's avatar
yonka's avatar Snapey1yr agoLaravel
2
2
Last reply by Snapey 1yr ago
PeregrineStudios's avatar

->with() query not working; can't figure out why

I'm struggling a bit, here: I can't figure out why this Eloquent query isn't automatically including my images relationship. Here's the relationship: class ImagesetCrop extends Model { ... public function images(): BelongsToMany { return $this->belongsToMany(File::class)->withPivot('height', 'width', 'left', 'top'); } } And here's me dumping

PeregrineStudios's avatar
PeregrineStudios's avatar PeregrineS...1yr agoEloquent
11
1
Last reply by PeregrineStudios 1yr ago
varovas's avatar

Can Eloquent query with() return only array without loading models?

Hi, I wonder if laravel can query related ids without loading models for these ids? I need all ids, because I am checking if user has any of that ids relations. Each exam can have several thousand related questions, so if there are for example 10 exams and each exam has 3000 questions, then laravel will load 30k models, which I think is not very good. Maybe I am wrong? Example

varovas's avatar
varovas's avatar varovas1yr agoEloquent
5
1
Last reply by varovas 1yr ago
ctrlaltdelme's avatar

Collections vs Query Builder? When to use each?

I'm progressing on my project and realized I've been using query builder for things that I may have been able to use just Eloquent Collections using my existing relationships. From what I understand calling a Model relationship like posts() uses Query Builder, but calling posts uses Eloquent and returns a Collection. It seems they both do similar things, so I'm wondering what t

ctrlaltdelme's avatar
ctrlaltdelme's avatar ctrlaltdel...1yr agoLaravel
11
419
Last reply by ctrlaltdelme 1yr ago
franciscocaldeira's avatar

Retrieving Input From The Query String, and prevent SQL Injection

Hello to all Laravel devs. I have a $request->query('key'); how to prevent this from SQL injection like 1=1 or ;drop database -- etc..? I have string rule for my query params but that ins't enough. Any suggestions? Thanks.

franciscocaldeira's avatar
franciscocaldeira's avatar Snapey1yr agoRequests
1
1
Last reply by Snapey 1yr ago
griffhayes77's avatar

Eloquent vs Query Builder – When to Use Which?

I'm working on a Laravel project and often find myself wondering whether to use Eloquent or the Query Builder for database operations. I love Eloquent’s simplicity and relationships, but sometimes the Query Builder seems more efficient for complex queries. How do you decide when to use Eloquent vs Query Builder? Are there specific scenarios where one clearly outperforms the oth

griffhayes77's avatar
griffhayes77's avatar Tray21yr agoGeneral
2
1
Last reply by Tray2 1yr ago
ctrlaltdelme's avatar

When to pass full Model vs just ID and make query?

I'm loving Laravel and MVC. I love the opinions, structure and design paradigm that it enforces. It helps me keep my thoughts straight and "see" the big picture a little easier than if I was just building a SPA or similar website/webapp using your favorite JS framework like Svelte, Vue, React (and their meta framework equivalents). One thing that I'm not super clear o

ctrlaltdelme's avatar
ctrlaltdelme's avatar ctrlaltdel...1yr agoLaravel
9
6
Last reply by ctrlaltdelme 1yr ago
mohammadrasoulasghari's avatar

Equivalent of Eloquent’s firstOrCreate in Query Builder

Hello and good day, Just as we have a firstOrCreate function in Eloquent, is there anything similar in Query Builder? Note: I'm specifically asking about firstOrCreate, not updateOrCreate."

mohammadrasoulasghari's avatar
mohammadrasoulasghari's avatar Sinnbeck1yr agoLaravel
2
1
Last reply by Sinnbeck 1yr ago
hvolschenk's avatar

Relationship with custom query

Hi. I am having some trouble implementing a custom query for a relationship. Simplified, there are two models: Item and Location. Each Item BelongsTo a Location, however a Location can be stored in multiple languages and I'd like to fetch the Location in the request user's language. There is also a chance that the Location does not exist in the desired language yet, where it wi

hvolschenk's avatar
hvolschenk's avatar jj151yr agoEloquent
9
1
Last reply by jj15 1yr ago
Batman55's avatar

return a comments_spam_count property in this query

I am following along with Andre Madarang in Build a Voting App. I would like to add a property that returns like comments_count toward the bottom called comments_spam_count. There is a table comments with a field spam_reports that holds the number of times the comment has been reported as spam. I would like to return the number of spam reports per idea. I for the life of me ha

Batman55's avatar
Batman55's avatar LaryAI1yr agoEloquent
1
1
Last reply by LaryAI 1yr ago
angelorigo's avatar

How can i get the SQL query formatted by Eloquent

Hi, I have a query created using eloquent, how can i see the real formatted query ?

angelorigo's avatar
angelorigo's avatar Sergiu171yr agoEloquent
2
1
Last reply by Sergiu17 1yr ago
birdietorerik's avatar

Execute old query

Hi! Have this Query $gpstracker = new Gpstracker; $gpstracker->latitude = $gpslatitude; $gpstracker->longitude = $gpslongitude; $gpstracker->timeused = $timeused; $gpstracker->created_at = $localDateTime; $gpstracker->golfclub_id = $golfID; $gpstracker->flight = $flight; $gpstracker->start = $starttim

birdietorerik's avatar
birdietorerik's avatar Snapey1yr agoLaravel
8
1
Last reply by Snapey 1yr ago
birdietorerik's avatar

How to check using IF in query

Hi! Have this query: $query = DB::table('gpstrackers') ->select('gpstrackers.*', 'users.name') ->leftJoin('users', 'gpstrackers.player_id_ref', '=', 'users.id') ->whereIn('gpstrackers.id', function ($query) use ($from1, $to1, $golfID, $courceid) { $query->selectRaw('MAX(gpstrackers.id) as id')

birdietorerik's avatar
birdietorerik's avatar Snapey1yr agoLaravel
2
1
Last reply by Snapey 1yr ago

Want us to email you occasionally with Laracasts news?

Nine out of ten doctors recommend Laracasts over competing brands. Come inside, see for yourself, and massively level up your development skills in the process.

Learn
BrowseSeriesCreatorSeriesLaravel PathLarabitsPlayground
Discuss
ForumPodcastSupport
Extras
Gift CertificatesApparelFAQiOS AppTerms
Social
X(Twitter)TikTokYoutube

© Laracasts 2026. All rights reserved. Yes, all of them. That means you, Todd.

Proudly hosted with Laravel Forge and DigitalOcean.

Want us to email you occasionally with Laracasts news?

Nine out of ten doctors recommend Laracasts over competing brands. Come inside, see for yourself, and massively level up your development skills in the process.

Learn
BrowseSeriesCreatorSeriesLaravel PathLarabitsPlayground
Discuss
ForumPodcastSupport
Extras
Gift CertificatesApparelFAQiOS AppTerms
Social
X(Twitter)TikTokYoutube

© Laracasts 2026. All rights reserved. Yes, all of them. That means you, Todd.

Proudly hosted with Laravel Forge and DigitalOcean.