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

Crazylife's avatar

How to match word from beginning until a space in a query to get result?

How to query a record where need to match word from beginning until a space? For example, i have entered full keyword "tesco" then in my database consist of "tesco store". I would like to return this result. If keyword "tes" entered, i will not show any record even there's partial string match with it. I cannot use LIKE % % for it. Any method can a

Crazylife's avatar
Crazylife's avatar Snapey7yrs agoGeneral
6
1
Last reply by Snapey 7yrs ago
booni3's avatar

Determine source of slow page load - fast query on its own but slow when run as part of more complex operation. Blackfire Profiling included.

I have a call to an endpoint that returns a paginated set of results (15 at a time). To get all the information needed, I am running between 60 - 100 queries. I realise this is a lot and I am optimizing this seperately, but I really want to get to the source of my issue! Using laravel devbug bar, I can see all queries are fast apart from a single sum where. As part of the page

booni3's avatar
booni3's avatar bobbybouwm...7yrs agoLaravel
9
2
Last reply by bobbybouwmann 7yrs ago
Charrua's avatar

Need help to think over a 3 model related query

This is a school Laravel app, using 3 models Member for school members, Attendance for registering school attendance and EmailLog to see emails sent to members. The main objective is to send "miss you" emails to inactive members on 4 ranges: one week inactive members, two week, one month and two month. Let's only review the first case, one week inactive members. To se

Charrua's avatar
Charrua's avatar Charrua7yrs agoLaravel
3
1
Last reply by Charrua 7yrs ago
booni3's avatar

Multiple indexes slowing down query

I am struggling to work out which columns are best to put my indexes on, when it seems adding additional indexes can have a detrimental effect on the query performance. For example, I have the following query on a table with around 5m rows; SELECT col1, col2 FROM table WHERE col1 = 'a' AND col2 = 'b' AND col3 = 'c'; Running this with no indexes takes 12 seconds! I add a compou

booni3's avatar
booni3's avatar lambooni7yrs agoLaravel
20
3
Last reply by lambooni 7yrs ago
t0berius's avatar

laravel strange SQL query builded

I'm using the following model for a message system inside my application: User model: public function getMessagesInvolvedAttribute() { return MessageType::where('initiated_by', $this->id)->orWhere('receiver', $this->id)->with(['sender:id,slug'])->orderBy('created_at', 'desc'); } MessageType model: public function sender() { return $this->hasOne('App\U

t0berius's avatar
t0berius's avatar willjohnat...7yrs agoEloquent
3
1
Last reply by willjohnathan 7yrs ago
lara28580's avatar

Query on a relation

I wanna query on a relation like this: $article = Coin::where('name', '=', $coin)->whereHas('articles', function ($query) { $query->where('slug', '=', $slug); })->get(); The problem is the param is not available in this scope? What can I do? Or is there a easier way? So to be clear I wanna get an article with a specific slug in relatio

lara28580's avatar
lara28580's avatar devfrey7yrs agoEloquent
1
1
Last reply by devfrey 7yrs ago
abnersouza's avatar

Query using max and group

Guys, I have the following scenario: I need to filter the latest version for each type. My Collection is called Template, for the template I have the following columns in the DB: variant (int) version (int) id_type(int) For the given table data: Row........: 1-----2-----3-----4-----5-----6 id_Type...: 1-----1-----1-----2-----2-----2 Variant....: 1-----1-----2-----1-----1----

abnersouza's avatar
abnersouza's avatar abnersouza7yrs agoLaravel
8
1
Last reply by abnersouza 7yrs ago
FREDERIC LD's avatar

query with pivot table

Hi I need a bit of help querying some data as I am fairly new to eloquent. I am using the Spatie Permissions module which comes with all sorts of fantastic methods to build/query permissions and roles and I have all of that working like a charm. I need to display in my "Manage Administrator", all the admins in the system and I want to have a role column in the datatab

FREDERIC LD's avatar
FREDERIC LD's avatar RFFRED7yrs agoEloquent
2
1
Last reply by RFFRED 7yrs ago
Msoft's avatar

differents between Eloquent ORM and Query Builder?

there are two things in Laravel dealing with database as Eloquent ORM and Query Builder. I need to understand what is the differences between them?

Msoft's avatar
Msoft's avatar MThomas7yrs agoLaravel
1
1
Last reply by MThomas 7yrs ago
Ganbatte's avatar

how to get count from select query ?

Hello, how to get count from select query ? Example. "select * from table where name like %aa%; == '$table=DB::table('table')->where('number','LIKE', '%аа%')' SELECT FOUND_ROWS(); == ??; i am sorry, i have bad English;

Ganbatte's avatar
Ganbatte's avatar wilk_randa...7yrs agoLaravel
2
1
Last reply by wilk_randall 7yrs ago
michalis's avatar

using the query builder for a many to many relationship?

I have a campaigns table and and an items table, and the pivot table is campaign_item is it possible to use the query builder to get all items that belong to a campaign? I ask because I need to chain some queries on it, but in the docs it only shows how to get the relationship through eloquent I search online and there are a few threads about the subject but I'm still not sure

michalis's avatar
michalis's avatar mayurdere7yrs agoLaravel
7
8
Last reply by mayurdere 7yrs ago
grigelionis's avatar

Laravel Query Builder - how to select pairs of items?

Hi guys, I will try to explain what i want to achieve by simple example. I have one table with following data: id, domain, clicks, url 1, example.com, 54, http://example.com/link1 2, oranges.com, 13, http://oranges.com/link1 3, example.com, 10, http://example.com/link2 4, apples.com, 3, http://apples.com/link1 5, apples.com, 7, http://apples.com/link2 6, crocs.com, 10, http://

grigelionis's avatar
grigelionis's avatar grigelioni...7yrs agoLaravel
2
3
Last reply by grigelionis 7yrs ago
pordonez's avatar

Laravel distinct query

I have the following data item 1 - 5 item 2 - 7 item 3 - 4 item 1 - 4 item 2 - 20 what query do i need to do to display this kind of result item 1 - 5 item 2 - 20 item 3 - 4 names should be distinct and get the highest value.

pordonez's avatar
pordonez's avatar Nakov7yrs agoLaravel
5
1
Last reply by Nakov 7yrs ago
slickness's avatar

Database Query

I have just quereme small quereme at a database query. How can I already select the posts in the database query below for specific values ​​in the controller? $user->mentioned_lead_user()->with('posts', 'users')->latest()->get();

slickness's avatar
slickness's avatar bekaskaki7yrs agoLaravel
1
1
Last reply by bekaskaki 7yrs ago
melx's avatar

get all data with SUM of Today and Sum of yesterday in same query

i want to get All data as usual and sum amount but i want sum of yesterday in same query?

melx's avatar
melx's avatar jlrdw7yrs agoLaravel
10
1
Last reply by jlrdw 7yrs ago
abarua's avatar

Database Query Syntax

Hi, I have two tables users(id, username, city, country) and friends(id, user_id, friend_id, status). The 'users' table stores the user information and 'friends' table store the currently logged in user's id, friend_id is the id of the user who sent a friend request to the current user and status will be 'received'. I want to show information of the users to sent requests to th

abarua's avatar
abarua's avatar jlrdw7yrs agoCode Review
8
1
Last reply by jlrdw 7yrs ago
abarua's avatar

Show link based on query result

Hi, I want to show a link if there are results from query. I get an error when the table is empty. Thanks in advance! The html: ... <div class="notification"> <header><h3>Notification</h3></header> @if(Auth::user()->friends()->where(['status', 'received'])->first()) <a href=""

abarua's avatar
abarua's avatar abarua7yrs agoCode Review
2
1
Last reply by abarua 7yrs ago
oliverbusk's avatar

Laravel - Method with relationship query - n+1?

Hi there So I have a website where users can upload documents. When a document is uploaded, it will be saved to a specific folder in my storage, like: stream_token/document_unique_id/mydocument.pdf In my Document model, I have created a simple method, that can be used to get the path for the specific document: /** * A Document belongs to a Stream. * * @return

oliverbusk's avatar
oliverbusk's avatar oliverbusk7yrs agoLaravel
2
1
Last reply by oliverbusk 7yrs ago
martinszeltins's avatar

What is query() method for?

I have noticed in a project a syntax like this but I could not find it on the Laravel docs anywhere. What is this syntax and why is it necessary? class Email extends Model { public function getEmails() { return self::query() ->where('id', 89) ->where('email', '[email protected]') ->get(); } } Isn't it the same as

martinszeltins's avatar
martinszeltins's avatar ftiersch7yrs agoEloquent
1
1
Last reply by ftiersch 7yrs ago
abarua's avatar

Show results of query in bootstrap modal

I want to show a list of query result inside a modal. Thanks in advance! I have tried to modify my current modal to show the list but I am getting an undefined variable ($comments, in this case) error. My modal: <div class="modal" tabindex="-1" role="dialog" id="comment-post"> <div class="modal-dialog" role=&quo

abarua's avatar
abarua's avatar abarua7yrs agoCode Review
2
1
Last reply by abarua 7yrs ago
DavidPetrov's avatar

Select sum of realtion's attributes in query

I really can't figure it out although it's fairly simple... I've got two tables: orders and revenues and I want to add a global scope to my Order model to load the sum of its paid revenues as an attribute. I tried joining and selecting the sum but nothing seems to change. The closest I've come to building the query was the following: static::addGlobalScope('withPaidFromCustomer

DavidPetrov's avatar
DavidPetrov's avatar DavidPetro...7yrs agoEloquent
2
3
Last reply by DavidPetrov 7yrs ago
nanox's avatar

How to create this Query?

Please help me ? I have no idea :/ Below Query MariaDB [realpropertydb]> select name from properties where postalCode LIKE 50000 OR province LIKE 50000 OR city LIKE 50000; Image: https://prnt.sc/nif3qm My solution doesn't work, as I want my sloution: https://prnt.sc/niez9j

nanox's avatar
nanox's avatar nanox7yrs agoEloquent
8
1
Last reply by nanox 7yrs ago
bekaskaki's avatar

Query show data by date and status

db table : `user_id` `invoice_id` `guest_id` `room_id` `checkin_date` `checkout_date` `total_price` `deposit` `status` //default value 0 how to query to display data by checkout_date = current date and status value 1? i use code below but all data with 'status' values ​​0 and 1 appears : $guest_checkout = RoomTransaction::whereDate('checkout_date', Carbo

bekaskaki's avatar
bekaskaki's avatar Tray27yrs agoLaravel
1
1
Last reply by Tray2 7yrs ago
dbos1504's avatar

Search query for booking rooms

I made simple website for room rental. The gay has 4 rooms for rent, now i need some help to make search query for booking. You now, check in - check out date, and number of adults, i need some kind of query to search available rooms in specific date range choosed in input fields (check in - check out). Any ideas, i am guesing i need database table for dates and rooms and book

dbos1504's avatar
dbos1504's avatar dipakratan...7yrs agoLaravel
2
1
Last reply by dipakrataniagile 7yrs ago
madala's avatar

Multi term search query through the table

Here is my code but not getting results exactly $keyword = isset($_REQUEST['search']['value']) ? $_REQUEST['search']['value'] : ''; $keywords = explode(' ', $keyword); $query = $this->query()->where(function ($query) use ($keywords) { foreach ($keywords as $searchString) { $query->WhereRaw("LOWER(BFY) LIKE LOWER(?)"

madala's avatar
madala's avatar Sergiu177yrs agoLaravel
3
1
Last reply by Sergiu17 7yrs ago
pordonez's avatar

Laravel query

Hello guys, i have a record on my database something like this -------------------- Name|Count -------------------- Item 1 | 5 Item 2 | 10 Item 3 | 4 Item 1 |4 Item 3 | 5 -------------------- now what i want to do with my query is this Item 1 - 9 Item 2 - 10 Item 3 - 9 can anyone help me please?.

pordonez's avatar
pordonez's avatar toby7yrs agoLaravel
4
3
Last reply by toby 7yrs ago
booni3's avatar

Query Builder - Sum with groupBy on relationship

I am looking for a query builder solution for the following: Table: transaction_types | id | type_hash | description | category | |----|-----------|-----------------|----------| | 1 | abcd | sale price | sale | | 2 | dbac | sale tax | sale | | 3 | agft | sale shipping | sale | | 4 | pgsk | refund price | refund | | 5 |

booni3's avatar
booni3's avatar jlrdw7yrs agoEloquent
5
4
Last reply by jlrdw 7yrs ago
vegasys's avatar

How to validate URL query parameters?

Hello, https://youtu.be/-1Hh-Hj4ZyU?t=648 Here it says : if ($month = $filters['month']) { // some query scope } When I run the app, it raises following error: Undefined index 'month' I can solve the error if I change it to: if ( isset($filters['month']) ) { // some query scope } Why does it work on the video but not in my app? (Laravel 5.5) if I go to my home at /home, it won'

vegasys's avatar
vegasys's avatar berusjamba...4yrs agoLaravel
7
32
Last reply by berusjamban 4yrs ago
Dalma's avatar

I could use some assistance in formatting a query

I have a query that I'm struggling to get to bracket correctly, query appears at the end of this post I have three relations: User User->offices() User->roles() The User has a default office id stored in the office_id field and a ManytoMany relationship accessed via the User->offices() relation and ManytoMany relationship accessed via the User->roles() relation. to

Dalma's avatar
Dalma's avatar Dalma7yrs agoEloquent
2
2
Last reply by Dalma 7yrs ago
mouzak's avatar

No query results for model [App\salaries] id

hi, how to resolve this error please? No query results for model [App\salaries] id controller $data['sala'] = salaries::findOrFail($id) ->relationPaie()->save(new paie()); when i do $data['sala'] = salaries::findOrFail('8') ->relationPaie()->save(new paie()); the request is executed but when i change the number by a variable i got an error.

mouzak's avatar
mouzak's avatar mouzak7yrs agoLaravel
10
1
Last reply by mouzak 7yrs ago
tanveerkhanwd's avatar

How to run this raw query in laravel

//I am just trying to use this query in my controller: SELECT *,(select gaw.weight FROM game_activity_wets gaw WHERE gaw.creator_id=game_activity_wets.creator_id AND gaw.type=0 AND gaw.game_id=game_activity_wets.game_id) as startweight FROM `game_activity_wets` WHERE game_id=37 and type=2 GROUP BY creator_id

tanveerkhanwd's avatar
tanveerkhanwd's avatar tanveerkha...7yrs agoLaravel
2
1
Last reply by tanveerkhanwd 7yrs ago
martinszeltins's avatar

Query takes 10 seconds if I add orderBy and paginate

I have this query but it is taking 10 seconds to execute. If I remove orderByRaw nad paginate then it only takes 15 ms. But I need to order it and paginate it. Is there another way to do it? $inkasso = \App\Models\Inkasso::selectRaw(implode(',', $columns)) ->leftJoin('inkasso_items', 'inkasso.id', '=', 'inkasso_items.ink_id') ->leftJoin('end_statuses', 'inkass

martinszeltins's avatar
martinszeltins's avatar Tray27yrs agoEloquent
11
1
Last reply by Tray2 7yrs ago
esmaill23's avatar

eloquent query that sum of two column greater than a number

i want to build an eloquent query sum of two column greater than a number like this $query = Transaction::query(); $query = $query->where('plan_price - final_price','>=',5); how ?

esmaill23's avatar
esmaill23's avatar Jacobs7yrs agoEloquent
2
1
Last reply by Jacobs 7yrs ago
DavidPetrov's avatar

Using laravel policy to filter eloquent query

So I recently just got into the concept of gates and policies and totally loved it. However, a natural question that appeared alongside my work was if I could somehow simply use similar logic to filter my eloquent queries based on access constraints defined in policies, because that would really optimise my infrastructure and boost performance. I can, however, see that policies

DavidPetrov's avatar
DavidPetrov's avatar jlrdw1yr agoLaravel
7
3
Last reply by jlrdw 1yr ago
johnef_sh's avatar

Easy way to convert raw mysql query to Eloquent

How can I convert a row MySql query to Eloquent I have a query like this SELECT * FROM ( SELECT products.id, products.image, products.price, products.featured_item as featured, product_translations.name as name, product_translations.details as details FROM products LEFT JOIN product_translations on products.id=product_translations.product_id where products.quantity > 0 AND p

johnef_sh's avatar
johnef_sh's avatar jlrdw7yrs agoEloquent
3
1
Last reply by jlrdw 7yrs ago
ssquare's avatar

Return ID From updateOrInsert Laravel query builder

How to return the id of las updated or Inserted id. I am using query builder instead of eloquent. How can I return ID from the following example: DB::table('users') ->updateOrInsert( ['email' => '[email protected]', 'name' => 'John'], ['votes' => '2'] );

ssquare's avatar
ssquare's avatar ssquare7yrs agoLaravel
9
9
Last reply by ssquare 7yrs ago
martinszeltins's avatar

How could I make this query using Eloquent without using raw?

I have this raw query and I would like to create it using Elequent. Is it possible to do it without using a raw query? SELECT users.id, users.full_name FROM users WHERE EXISTS (SELECT 1 FROM user_phones WHERE user_phones.user_id = users.id AND user_phones.phone LIKE '%12345678%' ) ORDER BY

martinszeltins's avatar
martinszeltins's avatar MartinZelt...7yrs agoEloquent
2
1
Last reply by MartinZeltin 7yrs ago
Charrua's avatar

Laravel relation query taking too much time to load

Hello, I have two models, one for school Member and the other for school Attendance, each one with the corresponding database table. My goal is to get all school members who have at least one attendance between some particular date, as an example let's take '2019-04-05' and '2019-04-12' (one week) So in my Members model I have a relation: public function attendance() { retu

Charrua's avatar
Charrua's avatar lostdreame...7yrs agoEloquent
9
2
Last reply by lostdreamer_nl 7yrs ago
nionta's avatar

Get difference between two date type column in a Query

I want to find return a query like return $query->whereRaw('DATEDIFF(day,infos.date_of_enrollment, date("Y- m-d"))','>',$svc_length_in_days); exactly what should be the query in eloquent?

nionta's avatar
nionta's avatar GodwinIyam...3yrs agoLaravel
4
3
Last reply by GodwinIyamba 3yrs ago
drewdan's avatar

SQL Query with ANDs ORs

Hi All, I am using the Eloquent Filter to filter my database query, however, I have been asked to add a search field which will search values between multiple columns and tables. The problem I am getting is that I have had to use or operators to query between the different tables as we dont neccesarily know which field needs to be searched, so we have to search them all with th

drewdan's avatar
drewdan's avatar drewdan7yrs agoEloquent
2
1
Last reply by drewdan 7yrs ago
martinszeltins's avatar

How to make a sub query with Eloquent

I would like to create a query like this with eloquent but is it possible? SELECT customerNumber, checkNumber, amount FROM payments WHERE amount = (SELECT MAX(amount) FROM payments WHERE amount > 50);

martinszeltins's avatar
martinszeltins's avatar Nakov7yrs agoEloquent
2
1
Last reply by Nakov 7yrs ago
martinszeltins's avatar

Is there a way to do this query without selectRaw?

I have this query but I am using selectRaw and I'm wondering if it can be done without selectRaw but with ->sum() instead? But it doesn't group it if I use sum(). $contracts = Contracts::all(); $total_sums = Payments::selectRaw('contract_id, sum(paid) as paid_sum') ->whereIn('contract_id', $contracts->pluck('id')) ->gr

martinszeltins's avatar
martinszeltins's avatar jlrdw7yrs agoLaravel
1
1
Last reply by jlrdw 7yrs ago
zafirus's avatar

Query database of 3 tables using Laravel

I have 3 tables: Table: faction id_faccao name Table: faccao_relacao id_relating_factory id_faccao_1 id_faccao_2 Table: relacao_faccao id_relating_factory name The field id_relacao_faccao of the table faccao_relacao refers to id_relacao_faccao of the table relacao_faccao. The fields id_faccao_1 and id_faccao_2 of the faccao_relacao table refer to the faccao_id of the faccao tab

zafirus's avatar
zafirus's avatar zafirus7yrs agoEloquent
2
2
Last reply by zafirus 7yrs ago
timgavin's avatar

Converting query to Eloquent

A site user can refer another site user. The referred site user (user_id in the query) can do things on the site which will give the referring user (referred_by in the query) points, as a way of rewarding them for the referral. I want to get the total number of reward points (total) from each column and display it. The following query works, but I'm having a hard time convertin

timgavin's avatar
timgavin's avatar timgavin7yrs agoEloquent
1
1
Last reply by timgavin 7yrs ago
Virtualmix's avatar

Query builder whereIn AND whereNotIn

Hello All, I was hoping to get some help with the following query builder. I would like to return a random listing that exists in my 'quotes' table but does not exists in my 'orders' table. $listing = App\Listing::whereIn('id', function ($p) { $p->select('listing_id')->from('quotes'); }, 'AND') ->whereNotIn('id', function ($q) { $q->selec

Virtualmix's avatar
Virtualmix's avatar Virtualmix7yrs agoLaravel
5
3
Last reply by Virtualmix 7yrs ago
ludo1960's avatar

How to debug a query

Hi guys, got a rather annoying issue, there seems to be something wrong with one of my queries, to try and remedy this I installed https://github.com/barryvdh/laravel-debugbar hoping that it would help me find out which query is at fault. I've tried following a few examples I found on the internet, but can't find anything specific for queries. The error I get is "bad sort

ludo1960's avatar
ludo1960's avatar ludo19607yrs agoLaravel
2
1
Last reply by ludo1960 7yrs ago
fabien44300's avatar

Conditional multiple if in query

Hello, I try to do to a conditinal query with laravel but I don't know how do something like a switch or multiple if. I read the documentation with "when" but I don't really think it's the good way. This is an example of what I try to do (replace if else if by ????) $user = User::query()->with('address') ->if('address.type == A', function ($query)

fabien44300's avatar
fabien44300's avatar fabien4430...7yrs agoEloquent
10
1
Last reply by fabien44300 7yrs ago
rpsimao's avatar

Add Relationship result to where query

Hello Can anyone help, I'm out of ideas. I have this code: $item = ItemsBrandOitb::select('ItmsGrpCod')->where('Brand', '=', $brand)->first(); return ItemsOitm::where('Country', $country) ->where('OnHand', '>', 0) ->where('ItmsGrpCod','=', $item->ItmsGrpCod) ->with([ 'price' => function($q) use ($countr

rpsimao's avatar
rpsimao's avatar rpsimao7yrs agoEloquent
9
1
Last reply by rpsimao 7yrs ago
behnampmdg3's avatar

Are there any downsides to use raw queries like this instead of query builder?

Are there any downsides to use raw queries like this instead of query builder? $user_courses = \DB::select(' SELECT * FROM table_1 INNER JOIN table_2 ON table_1.course_id = table_2.id AND table_2.active = 1 INNER JOIN table_3

behnampmdg3's avatar
behnampmdg3's avatar Cronix7yrs agoLaravel
5
1
Last reply by Cronix 7yrs ago
zoltiecodes's avatar

How to get the PDOStatement object from the Query Builder?

Hi. How can I access the PDOStatement object when I'm using the Query Builder in Laravel? Thanks.

zoltiecodes's avatar
zoltiecodes's avatar jlrdw7yrs agoLaravel
5
2
Last reply by jlrdw 7yrs 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.