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

maddmike's avatar

Multi database - Tenant - Query builder

Hey, I'm using DatatableController to get records with Multi-database tenant with Builder, i have this 'Database [tenant] not configured' so i ask how i can change database query builder to connection tenant? I can't access tenant connection or in model can't set connection name because 'tenant' has not been created yet Sorry for the English

maddmike's avatar
maddmike's avatar maddmike8yrs agoLaravel
0
1
bincy123's avatar

Query result from database

I have two tables : galleries and shared galleries. Structure of galleries: (for storing images of individual students. One student contains multiple images) id, student_id, classroom_id, image Structure of shared gallery (for storing images which are common to all students in a classroom. One classroom contains many images): id,classroom_id,image I need to get a query so that

bincy123's avatar
bincy123's avatar Vilfago8yrs agoCode Review
17
1
Last reply by Vilfago 8yrs ago
oroalej's avatar

Purpose of Builder query

Hi, Just want to ask what is the purpose of Builder in $model::when(condition, function(Builder $query){ $query->someCondition; })->get(); Because sometimes I get an error using it and by removing it fixed the issue.

oroalej's avatar
oroalej's avatar Nash8yrs agoEloquent
1
1
Last reply by Nash 8yrs ago
filipe1221's avatar

Check if query update

I Have this $update=DB::table('pages')->where('id', $data['id'])->update(array('value' => $values)); Now this is updating correct and i want check if that was correctley update. i try this if ($update>0) but sometimes gives 0 however query was successfuly. Thanks

filipe1221's avatar
filipe1221's avatar Cronix8yrs agoLaravel
7
1
Last reply by Cronix 8yrs ago
adamjhn's avatar

Do you know why are not appaering the query results?

I have a UserController that has the index() method that should get all the registrations in congresses by a user and for each registration get the congress details (title and date). So that is possible to show in the view "users.index" the congress title, date and registration date of all user registrations in congresses. The congresses table has a column "end_d

adamjhn's avatar
adamjhn's avatar adamjhn8yrs agoLaravel
2
1
Last reply by adamjhn 8yrs ago
HopesAreMiracle's avatar

How to write the query for updating from same table every night?

What i want is how can i update amount from each ID everynight. For example Today date is 8 - 5 - 18 and if goes to 9 - 5 - 18 , i want like to update wallet date to be 9 - 5 - 18 date and amount should be previous date amount. Need query first and i can do it on task scheduling. ID = 1 Amount '1000' Wallet Date = ' 8 - 5 - 18 ' ---- ID = 2 Amount '2000' Walle

HopesAreMiracle's avatar
HopesAreMiracle's avatar HopesAreMi...8yrs agoLaravel
0
1
sadalsuud's avatar

how I do a this query

I try many forms that to make this query: SELECT r.id, t.nombre, sum(cantidad), t.precio FROM alistamiento a, renglon r, renglon_trabajo rt, trabajo t WHERE a.fecha BETWEEN '2018-04-01' AND '2018-04-30' AND a.id = r.alistamiento_id AND r.id = rt.renglon_id AND rt.trabajo_id = t.id AND t.centro_id = 4 GROUP by t.id` But Laravel send me this error: SQLSTATE

sadalsuud's avatar
sadalsuud's avatar jlrdw8yrs agoEloquent
3
1
Last reply by jlrdw 8yrs ago
dust's avatar

Help with query

How can I write that query in Laravel? SELECT parent.id, COUNT(*) AS childs FROM categories AS parent INNER JOIN categories AS child ON child.parent_id=parent.id WHERE parent.`parent_id` = 1 GROUP BY parent.id Thanks!

dust's avatar
dust's avatar dust8yrs agoEloquent
2
1
Last reply by dust 8yrs ago
ralphmorris's avatar

Query with conditional logic in relationship has() method always returning true

I have the following relationship set up to show me new applications compared to when a summary of new applications was last sent out.. // Job Model public function applications() { return $this->belongsToMany('App\Professional', 'applications_pivot') ->withPivot('message') ->withTimestamps()

ralphmorris's avatar
ralphmorris's avatar ralphmorri...8yrs agoEloquent
2
1
Last reply by ralphmorris 8yrs ago
devTriple's avatar

Modal has many key unique meta data, I want to query it to be in one single array

I have a Lead model with id and name, I have a dynamicFields model with id, lead_id, key, value their is only one unique key per lead they are relationed as lead has many dynamic fields example: Lead 1, john doe dynamicFields 1,1,height, 150 2,1,width, 90 3,1,budget, 1000 I want the end query result to produce a collection/array [ 'id' => 1, 'name' => 'john doe', 'height

devTriple's avatar
devTriple's avatar devTriple8yrs agoEloquent
0
2
Badong's avatar

Query the first record of the relationship

Hello, Good day, just want to ask if this is possible? public function journals(){ return $this->belongsToMany(Traders::class); } // Is there a way how to do this? $traders = Trader::whereHas('journals',function($q){ $q->first()->where('query here'); }); I just want to query the first record of the relationship. Is that possible with eloquent? DB query is

Badong's avatar
Badong's avatar Vilfago8yrs agoEloquent
1
1
Last reply by Vilfago 8yrs ago
andremac96's avatar

Laravel combine multiple collections into one query

I'm wondering if this is possible. I have 3 models. Users TenantPreferances PropertyAdverts I'm trying to find out if I can do a query like so. Find all tenants, whose preferences, match the currently signed in users properties. The 3 databases are like so User Model Schema::create('users', function (Blueprint $table) { $table->increments('id'); $tab

andremac96's avatar
andremac96's avatar lostdreame...8yrs agoLaravel
5
1
Last reply by lostdreamer_nl 8yrs ago
shifoodew's avatar

SQL native to query builder

Hello, I need help on how to convert this SQL query with subquery inside inner join to Query builder. I'm new to this query builder. Hope you can help me convert this to query builder. SELECT DISTINCT CONCAT(u.last_name, ", ", u.first_name ) AS full_name, ci.created_at AS date_purchase FROM cart_items AS ci LEFT JOIN products AS p ON ci.product_id = p.id LEFT JOIN car

shifoodew's avatar
shifoodew's avatar Sinnbeck3yrs agoLaravel
14
1
Last reply by Sinnbeck 3yrs ago
ralphmorris's avatar

Query two different models and merging with pagination

I have two Models Conversation and DirectEnquiry that I would like to query together and show in the same list of results with pagination. This is where I am at: $conversations = $user->conversations() ->inbox($filters) ->with('job') ->paginate(20); $dire

ralphmorris's avatar
ralphmorris's avatar ralphmorri...8yrs agoEloquent
4
1
Last reply by ralphmorris 8yrs ago
thedome's avatar

Query with relation

Heyyo, I have the User public function buildings() { return $this->hasMany('MyApp\Building'); } And Buildings public function user() { return $this->belongsTo('MyApp\User'); } Now I want to paginate the Buildings but it don't work... public function index() { $buildings = Building::whereHas('user', function ($query) {

thedome's avatar
thedome's avatar tykus8yrs agoEloquent
1
1
Last reply by tykus 8yrs ago
Hassaan's avatar

How can i send one query result (via variable) into an other query

What I want is to include the result of sub variable into another query. $sub = DB::table('chef_food_ethics')-> select(DB::raw('count(id) as fCount')) ->where('chef_food_ethics.food_ethic_id', '=','food_ethic_managers.food_ethic_id') ->toSql(); Is it possible to include it like that? $r = DB::table('food_ethic_managers')where ('food_ethic_managers.manager_id','

Hassaan's avatar
Hassaan's avatar Hassaan8yrs agoLaravel
4
1
Last reply by Hassaan 8yrs ago
Skizo's avatar

Query to Eloquent model

I have this query: SELECT authors.name, COUNT(books.id) books_count FROM books LEFT JOIN authors on authors.id = books.author_id GROUP BY author.id How can I transform this into Eloquent models? I tried this: class Book extends Model { public function author() { return $this->belongsTo('Author'); } } Book::all()->with('author'); It worked but the group

Skizo's avatar
Skizo's avatar biishmar8yrs agoEloquent
6
1
Last reply by biishmar 8yrs ago
basvandertogt's avatar

Global query run once

Hello, I have a queried model based on current subdomain which should be accessible in all views/models/controllers. For now i have placed this query inside the helper class but this way the query is runned every time the helper is called. What is the best approach for this? Bas

basvandertogt's avatar
basvandertogt's avatar basvandert...8yrs agoLaravel
0
1
basvandertogt's avatar

Optimize eloquent query

I'm facing a performance issue when fetching my user models. My user model has a relation with many teams. The user has a separate profile for each team. These are my db tables: users id first_name last_name profiles id role position nickname back_number teams id name team_user (pivot) team_id user_id profile_id I'm looking for a better approach to query my users with d

basvandertogt's avatar
basvandertogt's avatar basvandert...8yrs agoLaravel
8
5
Last reply by basvandertogt 8yrs ago
zanakka's avatar

Query slow in datatable

Hi, I have 35,000 over records in my table and I'm using datatables library to render all these records. After implemented with datatables, the query result took about 27 seconds. It is too long, right? Can you help me to check the way I implemented is correct or wrong? Thanks in advance! $products = $merchant->Product()->select(['id', 'name', 'price']) -&

zanakka's avatar
zanakka's avatar lostdreame...8yrs agoGeneral
6
1
Last reply by lostdreamer_nl 8yrs ago
rotaercz's avatar

I have a database table that gets updated every 2-3 months or so. Is there a good way to not have to query the database when it hasn't changed?

I have a database table that gets updated every 2-3 months or so. Is there a good way to not have to query the database when it hasn't changed? I'm just working on making my site more efficient and faster. Is there a good way to handle cases like this?

rotaercz's avatar
rotaercz's avatar Cronix8yrs agoLaravel
6
1
Last reply by Cronix 8yrs ago
keevitaja's avatar

How to ignore specific query parameter with varnish cache?

/swatches/ajax/media/?product_id=17620&isAjax=true&_=1524469655019 I need to cache this request with varnish, but i need to ignore the last query parameter _=1524469655019. I am not sure how varnish internally works, but i suppose it makes the cache uid key from the url requested. So in my case it would need it only to create the uid key from this url /swatches/ajax/me

keevitaja's avatar
keevitaja's avatar bitumin2yrs agoServers
1
1
Last reply by bitumin 2yrs ago
Rahulniit's avatar

All records of Menu with sub menu using Query builder

how to get menu and submenu in view from mysql using query builder?

Rahulniit's avatar
Rahulniit's avatar unmd06yrs agoLaravel
8
2
Last reply by unmd0 6yrs ago
Rahulniit's avatar

Fetch Records Using Query Builder inside a loop in view

First i get id from outer loop then, through id Fetch Records Using Query Builder inside inner loop in view.. Does any body know about this..

Rahulniit's avatar
Rahulniit's avatar Rahulniit8yrs agoLaravel
12
1
Last reply by Rahulniit 8yrs ago
tinybot's avatar

How to manipulate query result into JSON-ready layout?

This is probably more of a PHP question than it is a Laravel-specific question - but here goes! I'm trying to prepare the result of an Eloquent Query for use in a charting tool (in my case, Highcharts): $rows = DB::table('pushups') ->join('users', 'pushups.user_id', '=', 'users.id') ->selectRaw('users.name as name, sum(pushups.amount) as am

tinybot's avatar
tinybot's avatar biishmar8yrs agoLaravel
3
1
Last reply by biishmar 8yrs ago
rafito's avatar

Slow MySQL query with Laravel Eloquent

I'm using Laravel Eloquent and debuging why this query is taking so long: select count(*) as aggregate from custom_products where hidden = '0' and (company_id = '1') and exists ( select * from categories inner join categorizables on categories.id = categorizables.category_id where custom_products.id = categorizables.categorizable_id and categorizables.categorizable_type = 'App\

rafito's avatar
rafito's avatar jlrdw8yrs agoEloquent
11
4
Last reply by jlrdw 8yrs ago
StackBoot's avatar

Laravel query tooo slow

I have the following filtering/grouping public function rows($organizationId, Request $request) { if (!$request->has('groupByItems')) { abort(404); } $groupByItems = json_decode($request->get('groupByItems')); $organization = auth()->user()->availableOrganizations()->findOrFail($organizationId); $que

StackBoot's avatar
StackBoot's avatar tykus8yrs agoLaravel
6
1
Last reply by tykus 8yrs ago
DenMette's avatar

Howto convert eloquent query to resource

Hi I'm working on a small application for a youth organisation. But I'm stuck in my mind ... select kids.id, kids.cash, kids.forename, kids.surname, (kids.cash - SUM(IFNULL(sub.total, 0))) as money from ( select histories.kid_id, (COUNT(histories.item_id) * items.price) AS total from `histories` inner join `items` on `histories`.`item_id` = `items`.`id` group by `histories`.`k

DenMette's avatar
DenMette's avatar jlrdw8yrs agoEloquent
1
1
Last reply by jlrdw 8yrs ago
ninja506's avatar

how to change eloquent with method query

i use laravel and my db is sql server . when use with method on eloquent , it make a query has where in and bind parameters . as my db is sql server limit on binding parameters and my parameters more than 2100 and script failed by this error . if parameters put directly in query no problem . if we change the query of with method and put parameters directly in query this problem

ninja506's avatar
ninja506's avatar tykus8yrs agoEloquent
7
1
Last reply by tykus 8yrs ago
mjc's avatar

Storage::temporaryUrl with query string

Is there a way to pass a query string along with the path and file? For example: Storage::disk('s3')->temporaryUrl('content/myfile.jpg?userName=john', now()->addMinutes(30)); At the moment this results in a NoSuchKey errror. Other permutations I've tried produce a SignatureDoesNotMatch error. I believe the query string needs to be passed using Amazon meta-headers so it w

mjc's avatar
mjc's avatar mjc8yrs agoLaravel
0
1
WallyJ's avatar

Query records within a foreach loop in a view

So, pardon me not having complete code yet because this is somewhat hypothetical. So, if I have a query in my Controller that looks up a list of Customers from the Customers table, with various fields like name, email, etc. and it shows in a view with something like: @foreach ($customers as $customer) <div>$customer->name</div> <div>$customer->email</

WallyJ's avatar
WallyJ's avatar Snapey8yrs agoLaravel
10
1
Last reply by Snapey 8yrs ago
WallyJ's avatar

Converting MS Access Queries to Laravel Query Builder

I am converting some queries that contain primarily aggregate fields, all in one query, in a MS Access db. How would I convert so many aggregate fields into one lookup? Or would I need to break it up and then combine them? For instance, some of the query fields look like this: Field: Product Name Table: Products Total: Group By Field: Product Name Table: Products Total: Count C

WallyJ's avatar
WallyJ's avatar allaroundv...6yrs agoLaravel
11
1
Last reply by allaroundvba 6yrs ago
ashwini1987's avatar

Self join query in laravel 5.6

Hello I have a query : SELECT e.id,e.name_other, e.name, m.name AS manager,e.start_date,e.end_date,e.status FROM tm_vendor e, tm_vendor m WHERE e.gid=m.id AND e.status=1 I want to convert into Laravel. I have to write code. public function children() { return $this->hasOne(static::class, 'gid'); } $vendorQuery = DB::connection($this->connection)->table($this->table

ashwini1987's avatar
ashwini1987's avatar jlrdw8yrs agoEloquent
2
1
Last reply by jlrdw 8yrs ago
V9द's avatar

Create Filter query according to parameter using Eloquent

I want to filter products currently I am using below method its working fine. But whenever I want to apply pagination its not work. I tried with LengthAwarePaginator also but there is lot of stuff for me. So Please help and provide better approch if avialable, I am using laravel 5.6 $perpage = "1"; $offset = ($page - 1) * $perpage; $query='SELECT * FR

V9द's avatar
V9द's avatar V9द8yrs agoEloquent
2
1
Last reply by V9द 8yrs ago
evgaard's avatar

Group aggregate query by hour/day etc

I want to count for example number of created projects for every hour. Is this possible to do with a db query. It's easily done in a loop after a query like $res = DB::table('projects') ->select('id', 'created_at') ->get()->groupBy(function($date) { return Carbon::parse($date->created_at)->format('Y-m-d H'); }); foreach ($res as $index =>

evgaard's avatar
evgaard's avatar tykus8yrs agoLaravel
5
1
Last reply by tykus 8yrs ago
saidbakr's avatar

How to translate No query results for model message

When a model id is not found, I got custom 404 error with message says "No query results for model [App\ModelName]" I need to translate this message. I searched in resources/lang/en to find any file that may contain this message, but I could not find any one. It is just four files there, auth.php, pagination.php, passwords.php and validation.php.

saidbakr's avatar
saidbakr's avatar tykus8yrs agoLaravel
13
1
Last reply by tykus 8yrs ago
hidayat3676's avatar

how to get only query data from url

i have a url like localhost/posts/id here id is query which is an integer value how can i get this from this url

hidayat3676's avatar
hidayat3676's avatar rin4ik8yrs agoLaravel
1
1
Last reply by rin4ik 8yrs ago
cyw691205's avatar

How can i query by user input?

i want query products by user input keword or category. but this code is not work... public function index(Request $request) { // $keyword = $request['keyword']; $catgory_id = $request['catgory_id ']; if($catgory_id ){ $ps = Category::find($catgory_id )->products()->where('status', 1); }else{ $ps = Product->where('status', 1); } if($key

cyw691205's avatar
cyw691205's avatar ekhlas8yrs agoEloquent
4
1
Last reply by ekhlas 8yrs ago
verism's avatar

How do create a database query to use on both web and api?

Hi, I've been working on integrating Vue into a Laravel installation, and under a specific API route (that displays a list of actors) I arrived at the following to achieve what I need: // routes/api.php Route::get('/actors', function(Request $request) { // Select all user with actor role, with their attributes and gender $actors = User::whereHas('roles', function ($que

verism's avatar
verism's avatar martinbean8yrs agoLaravel
4
1
Last reply by martinbean 8yrs ago
r2get's avatar

filter eloquent query with many to many relationship table

Hi i have a datatable with filters so with each filter i want to adjust the query for the users table i have a table called roles that is a many 2 many with roles and users i use this code //filters $active = false; $non_active = false; $role = false; //check active status if ($request->get('active') == 'true') { $active = true; } if

r2get's avatar
r2get's avatar Cronix8yrs agoEloquent
4
1
Last reply by Cronix 8yrs ago
baloch's avatar

Query builder - inside insert query i want to implement a for loop over the array to insert multiple records in one go

what i want to achieve is that inside the DB query i insert all the records in one go so that the query doesn't run many times. the following code doesn't allow me to use the for loop inside the array. kindly help. { if($request['accessibleTodealers']!='' || $request['accessibleTodealers']!=null) { $memberships=explode(",&quo

baloch's avatar
baloch's avatar baloch8yrs agoCode Review
4
1
Last reply by baloch 8yrs ago
sakshamhappy's avatar

ORM for sql query

select * from transactions where transaction_type_id in ( 3,4,5,6,25) and (credit_id = 40 or debit_id =40); i am facing problem to write ( 3,4,5,6,25) and (credit_id = 40 or debit_id =40) " bracket query" can anyone help to write model for this query? i have written this orm Transaction::whereIn('transaction_type_id',array(3,4,5,6,25))->where('credit_id',$user-&g

sakshamhappy's avatar
sakshamhappy's avatar Snapey8yrs agoEloquent
1
1
Last reply by Snapey 8yrs ago
Corys8646's avatar

Remembering Query Scopes and Accessors

This is more of a general question and something that keeps popping up for me. When I initially develop an app, I will invariably create Query Scopes and Accessors on my models. That works great when i'm deep in a project. When coming back a few weeks later, I find myself rewriting those queries in the controller, forgetting I already have them on my model. Or inlining the same

Corys8646's avatar
Corys8646's avatar Corys86468yrs agoGeneral
0
1
sheldonscott's avatar

Query to find results within dynamic date ranges and group by dynamic elements

I think I am either overcomplicating this or "under-complicating" it. lol I have a table of data that holds assessment data for students. Teachers log this assessment data on a child-by-child basis within different user-defined "terms" (date ranges) over the course of a school year. I am looking to display the progress of a selected student, grouped by each

sheldonscott's avatar
sheldonscott's avatar sheldonsco...8yrs agoLaravel
1
1
Last reply by sheldonscott 8yrs ago
Crazylife's avatar

Query perform very slow when using where in condition

I am having this query. $items = DB::table('items') ->leftJoin('default_price', 'items.id_item', '=', 'default_price.id_item') ->leftJoin('vendors', 'items.id_vendor', '=', 'vendors.id_supplier') ->whereIn('items.id_vendor', $vendors) ->whereIn('items.id_item', $id_items_default) ->get()-&

Crazylife's avatar
Crazylife's avatar ricardovig...8yrs agoGeneral
10
1
Last reply by ricardovigatti 8yrs ago
madsem's avatar

Nested BelongsToMany query - How to filter unwanted results

I'm trying to query all the advertisers assigned to a domain, and return all the ads assigned to these advertisers which match a set of user variables, and that have banner ads. // Domain Model public function advertisers() { return $this->belongsToMany('App\Advertiser'); } // Ad Model public function banners() { return $this->hasMany('App\Ban

madsem's avatar
madsem's avatar madsem8yrs agoEloquent
7
1
Last reply by madsem 8yrs ago
Rymercyble's avatar

automatically changing query based on received data

I want to make user filter search. For all users I can use User::all(); And if i want to filter them by country I need User::where('country', Country::where('name', $country)->select('id')->first()->id) but this don't handle situation when user won't specify country so I need to change it to something like this if (Request::get('country') == ''){ $cou

Rymercyble's avatar
Rymercyble's avatar arukomp8yrs agoEloquent
6
1
Last reply by arukomp 8yrs ago
jrichmo93's avatar

Query by count of relationship comparison to parent field value

I'm building a project management tool and need to query for all projects that aren't full. The amount of users in a project is specified when the project is created. So essentially I need a query like below: Project::has('users', '<', 'project.user_count') Looking at the bindings from the query, project.user_count evaluates to 0. Is there anyway to accomplish this? Any hel

jrichmo93's avatar
jrichmo93's avatar Talinon8yrs agoLaravel
1
1
Last reply by Talinon 8yrs ago
Jacobs's avatar

Redirect back with query string parameters

Hey, is it possible to redirect back with query string parameters? Based on datepicker I choose a date, then with Carbon I get the week and year from the date. After that I want to redirect back to the previous page with new query string parameters. Keep in mind I didn't pass the week and year parameters into the controller. Currently using this: return redirect(strtok(back()-&

Jacobs's avatar
Jacobs's avatar Cronix8yrs agoGeneral
2
1
Last reply by Cronix 8yrs ago
mlarson's avatar

Query Builder and groupBy having issues

I'm trying to translate this query to query builder in Laravel 5.4: SELECT oc.id, oc.name, oat.user_id, p.first_name, p.last_name FROM oauth_clients oc LEFT JOIN oauth_access_tokens oat ON oc.id = oat.client_id JOIN users u on u.id = oat.user_id JOIN people p on p.id = u.person_id WHERE oc.revoked = false AND oc.password_client = true GROUP B

mlarson's avatar
mlarson's avatar jlrdw8yrs agoEloquent
2
1
Last reply by jlrdw 8yrs 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.