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

archiebango's avatar

How do I add If-Else and Query to database?

Hi, I am planning to build a simple website that has 3 types of account, Admin, Seller, and Buyer. I created a different row like, 'Firstname', 'Lastname' ,'Email', and 'Role' Under 'Role' it has 3 types, admin, seller, and buyer How can I code this in HomeController? My logic is to query the database: If the user have 'Seller' in Role Row, then he will be redirected to Selle

archiebango's avatar
archiebango's avatar Parasoul8yrs agoLaravel
3
1
Last reply by Parasoul 8yrs ago
rachelmaeve's avatar

Run query on user login

Hello everyone at laracasts! i'm quite new to laravel and i have a fairly simple question (I assume it is simple, could be wrong): I have a column hasLoggedIn with a default value of TRUE and i would like to run a query as soon as the user is authenticated, so i can update my database without having to run this query on every page or every returned view. Problem: I can't find w

rachelmaeve's avatar
rachelmaeve's avatar rachelmaev...8yrs agoLaravel
4
1
Last reply by rachelmaeve 8yrs ago
vnc00's avatar

belongsToMany fires query with id 0

Hi, got the following migrations: Schema::create('product_categories', function (Blueprint $table) { $table->increments('id'); $table->string('slug')->unique()->index(); $table->string('name')->unique(); $table->string('teaser', 350); $table->integer('product_category_id')->unsigned()->nul

vnc00's avatar
vnc00's avatar vnc008yrs agoLaravel
7
1
Last reply by vnc00 8yrs ago
tesarwijaya's avatar

Eloquent whereDate query give different than expected result

I have query where i need to select using whereDate function, here is my query. $histories = History::where('location_id', 71)->whereDate('started_at', date('Y-m-d', strtotime('2017-07-27')))->get(); and DB query log: Array ( [0] => Array ( [query] => select * from `history` where `location_id` = ? and date(`started_at`) = ? [bin

tesarwijaya's avatar
tesarwijaya's avatar khizer10308yrs agoEloquent
1
1
Last reply by khizer1030 8yrs ago
iamripespoon's avatar

Trouble with Separating a Query into 2 Separate States

I'm building a query for a Leads report. So the person will select parameters in a form and eloquent builds it's query based on the forms values and the results page will obviously show the results. The trouble i am having is... I have say a query, mine is split into different functions but for this example i'll put it into a simpler form. This part will load all Leads within t

iamripespoon's avatar
iamripespoon's avatar iamripespo...8yrs agoEloquent
0
1
bnazarov's avatar

BelongsToMany filtering query

I have 2 models. User, Styles[id|name]. Relationships are as following: // in user class public function styles() { return $this->belongsToMany('App\Styles', 'user_style', 'user_id', 'style_id'); } // in styles class public function users() { return $this->belongsToMany('App\User'); } When filtering, visitors can select differen

bnazarov's avatar
bnazarov's avatar bnazarov8yrs agoEloquent
0
1
Jam0r's avatar

Complex query, comparing sum of different tables

I have a base model with has a relation to two other models. I'm calculating a balance and appending to the base model based on amounts recorded in the relationship models. Both relationship models have fields named 'amount' which I total, and then subtract from each other, giving me a balance on the fly. This works well as if and when a record in a relationship table is delete

Jam0r's avatar
Jam0r's avatar Jam0r8yrs agoEloquent
0
1
bhuether's avatar

How would you do this tricky JOIN query?

I have a guitar lessons site (laravel 5.2) where lessons contain exercises. In exercise table you have lessonid as well as a difficulty. For lessons table, there is no difficulty column, as difficulty is determined dynamically by retrieving maximum difficulty of the exercises in the lesson. So, what I need to do is sort lessons on difficulty. Here are the functions involved: pu

bhuether's avatar
bhuether's avatar bhuether8yrs agoLaravel
0
1
freshface's avatar

URL/Request parameters to query

I want to provide query params in my url to filter in my database. fe: /api/books?_q=The Lord of the Rings&_sort=-_score I found this package https://github.com/marcelgwerder/laravel-api-handler But I was wondering if there are any other packages out there with will do the same and are better maintained. The one I am referring to doesn't allow filtering on joined tables.

freshface's avatar
freshface's avatar matthew.er...8yrs agoLaravel
6
1
Last reply by matthew.erskine 8yrs ago
Arpit's avatar

No query results for model [App\Tags]

I am trying to fetch list of tags, but i keep getting this error : NotFoundHttpException in Handler.php line 131: No query results for model [App\Tag] Here is my routes file <?php Route::get('/', function () { return view('home'); }); Route::get('/dashboard', function () { return view('dashboard'); }); Route::get('/browse', 'TeamsController@index'); Route::get('/

Arpit's avatar
Arpit's avatar Arpit8yrs agoLaravel
2
1
Last reply by Arpit 8yrs ago
udoyen's avatar

Database Query Error

$loginusers = DB::table('sessions')->select('user_id')->distinct()->where('user_id', '!=', null)->get(); // Create array to add logged in users $logged = []; This is my attempt to add the result of this database query to my $logged array. foreach ($loginusers as $loginuser) { # code...

udoyen's avatar
udoyen's avatar udoyen8yrs agoLaravel
7
1
Last reply by udoyen 8yrs ago
fredmoras's avatar

query builder

I 've got a problem with the laravel query builder. I don't understand what 's wrong. I have 3 tables (salades, ingredients ,salade_ingredient(pivot for n:n relation) I would like to list the name of ingredients(column ingredients.nom) for salade id 22. sql query(work well): select distinct ingredients.nom from ingredients, salade_ingredient,salades where salade_ingredient.sala

fredmoras's avatar
fredmoras's avatar lostdreame...8yrs agoEloquent
8
1
Last reply by lostdreamer_nl 8yrs ago
Tangaye's avatar

How to format or rearrange inner join query results in laravel view or controller

I have five table students, grades, subjects, terms, and scores. I'm performing an inner join on thes table to return results. This how my schema looks: Students table: students -------- id * name class_id (fk) Subjects table: subjects -------- id * name Class table: classes -------- id * name Term table: terms -------- id * name Scores Table: scores --------------- id * st

Tangaye's avatar
Tangaye's avatar Tangaye8yrs agoGeneral
2
1
Last reply by Tangaye 8yrs ago
J_shelfwood's avatar

Get pivot data from another model as query scope.

Hi everyone, I'm struggling with a bit of an odd query. my models are as follows: class Register extends Model { public function users() { return $this->belongsToMany(User::class) ->withPivot([ 'credit', ]); } } class User extends Model { public function registers() { return $this->belongsToM

J_shelfwood's avatar
J_shelfwood's avatar Hawkleaf8yrs agoEloquent
4
1
Last reply by Hawkleaf 8yrs ago
BladeSlayer1000's avatar

Duplicated records with query

Hi all, I have the following code: public function indexnew() { Log::info("Called indexnew"); //Log::debug(Request::get('search')); if(isset($_GET['search'])) { $searchQuery = $_GET['search']; } else { $searchQuery = null; } $orders = Order::where('orders.id', 'LIKE', '%'. $searchQuery .'%')-&g

BladeSlayer1000's avatar
BladeSlayer1000's avatar Snapey8yrs agoEloquent
11
1
Last reply by Snapey 8yrs ago
Haider's avatar

Returning a result set of raw query from controller to view

I am unable to output the result of a raw database query in a view which is as follows // Controller coding public function calculate_fees() { $q1 = DB::select("Select SUM(fee) as paid_customers from customers where status='Paid'"); return view('employee_home', ['paid_customers'=>$q1]); } // View coding <? {{$paid_customers}} An error that

Haider's avatar
Haider's avatar Haider8yrs agoLaravel
26
1
Last reply by Haider 8yrs ago
rammy85's avatar

Please help me convert this SQL into an eloquent query

I am trying out a way to conduct a spatial query in eloquent so I can return user models to pass to a view. the aim is search by distance in order of distance. I have this raw query as outlined below public static function searchByDistance($distance, $unit) { //spatial queries $circle_radius = 6371; // $circle_radius = 3959;

rammy85's avatar
rammy85's avatar rammy858yrs agoEloquent
4
1
Last reply by rammy85 8yrs ago
jpeterson579's avatar

How to Eager loading other model from DB::Select() Query?

Hi there, I have a query that grabs the 60 closest locations near a given longitiude latitude point. What I want to do is eager load my another model on top of this. Any ideas on if this is possible or another work around? $circleRadius = 3959; $maxdistance = 60; // SQL statement that finds closest 60 locations within radius of 60 miles to $lat $lng. $locat

jpeterson579's avatar
jpeterson579's avatar jlrdw8yrs agoEloquent
5
1
Last reply by jlrdw 8yrs ago
13en's avatar

Help with query Please!!

Hello and thanks for reading my post. I have a foreach which displays a list of categories on a page, then i have a cart on the same page however i need to interweave these so when a product is added to the cart it takes the place of the category name. I hope I'm making sense as sometimes i over/under explain things and don't actually say what i want to do. Here's my Cart contr

13en's avatar
13en's avatar jlrdw8yrs agoEloquent
1
1
Last reply by jlrdw 8yrs ago
gendylopez's avatar

MySQL Query Prepared Statement to Laravel

I spent hours making this query right using phpMyAdmin and when I was already going to transfer it on my laravel project, it says there is an error, and I really don't understand what the error is. SELECT GROUP_CONCAT(DISTINCT CONCAT( 'SUM( CASE WHEN rate_sub_type = ''',rate_sub_type,''' THEN rate END ) AS rate_sub_type' ) ) INTO @sql FROM rate_sub_ty

gendylopez's avatar
gendylopez's avatar AnonyMouse7yrs agoLaravel
3
1
Last reply by AnonyMouse 7yrs ago
MrRobot21's avatar

Laravel Relationship query

I have 2 models OrderDetails and Product //OrderDetail MOdel class OrderDetail extends Model { protected $fillable = ['order_id', 'product_id', 'quantity']; protected $hidden = ['created_at','updated_at','deleted_at']; public function product() { return $this->has

MrRobot21's avatar
MrRobot21's avatar MrRobot218yrs agoLaravel
0
1
shanukk's avatar

How to convert mysql query to laravel

I have a mysql query $sql="SELECT *from table where `Content`->>'$.cycle_id'=1"; How can i convert this query to laravel?Any help would be appreciated.

shanukk's avatar
shanukk's avatar spekkionu8yrs agoLaravel
1
1
Last reply by spekkionu 8yrs ago
charlieBrown's avatar

whereHas with orderBy in the first query

I have read some answers over here but I'm not able to adapt it to my problem. I would like to order a collection where I use whereHas. I have two tables profissao_user and users. It is returning the users but I would like to orderBy the table profissao_user by desc order on raio_deslocacao. $users = User::whereHas('profissoes', function ($query){ $query->where('prof

charlieBrown's avatar
charlieBrown's avatar Snapey8yrs agoLaravel
2
1
Last reply by Snapey 8yrs ago
fernandocg_12's avatar

Just can't make an "Advanced Query" work

Hello everbody! I'm new here in Laracasts... I've been searching for an answer to my question for two or three days, and I can't be able to found it. So I have decided to make a question here in the forum (sorry for my bad, bad english...) The problem is: I have a SQL Query that works perfectly if executed directly in the DataBase via PHPmyAdmin or any other SQL manager. But I

fernandocg_12's avatar
fernandocg_12's avatar fernandocg...8yrs agoEloquent
6
1
Last reply by fernandocg_12 8yrs ago
noreason's avatar

Removing a query parameter from url?

Is there a laravel based way to remove a query string from the url? I have your typical filtering setup going on and I have no problem building and concatenating multiple queries into my url using route(), but I don't know how to do the opposite... For instance if I've built up a a url such as http://example.com?color=red&size=large by applying both the color and size filte

noreason's avatar
noreason's avatar noreason8yrs agoLaravel
0
1
hillcow's avatar

No query results for model [App\Thread].

Hey there, I am following the forum series from Jeffrey and decided to change things up a little and make my own project out of it. I have changed plenty things, such as routes and I am using tags instead of channels. Now when I try to go to /profiles/anyName, I get this: "No query results for model [App\Thread]." Now I'm not sure why this would request any threads in

hillcow's avatar
hillcow's avatar Snapey7yrs agoLaravel
3
1
Last reply by Snapey 7yrs ago
mbpp's avatar

Query multiple options attributes

Hi guys, i created a search form, but i need some help in how to query the data and results: Basically i have a list of products, and in each product there is one product_type and also each product can have many materials attributes. I already made the query to get the type of products, and that is easy since the product type id is in the same table (products) but than i have t

mbpp's avatar
mbpp's avatar mbpp8yrs agoLaravel
2
1
Last reply by mbpp 8yrs ago
hillcow's avatar

Database Query returns object - how do I get it's values to display?

Hi there, I guess there is a simple solution to my problem, I'm just a beginner :D On one of my controllers I have a fairly complex DB::table...... request that returns an object and not an array (and I think I cannot perform the request with Eloquent). Now I don't know how I get these values to actually display inside my blade page? Do I have to somehow convert it to an array

hillcow's avatar
hillcow's avatar Cronix8yrs agoLaravel
1
1
Last reply by Cronix 8yrs ago
bobmyles's avatar

Join Statement using Query builder

Hi there, I have a Query builder statement below and I would want to introduce another condition to the query. However, I can not get this right. This query works fine; $content = DB::table('subscribed_services as a') ->join('scheduled_messages as b', 'a.id', '=', 'b.subscribed_services_id') ->join('subscription_services_msisdn as c', 'a.id

bobmyles's avatar
bobmyles's avatar bobmyles8yrs agoLaravel
1
1
Last reply by bobmyles 8yrs ago
hillcow's avatar

MySQL to Laravel Database Query

Hey there, I need some help in transforming the following MySQL query to a Laravel Database query. I get this error: "Base table or view not found: 1146 Table 'forum.(tag_thread) tt' doesn't exist" Raw MySQL: select ta.name from tags ta join tag_thread tt on tt.tag_id = ta.id join (select * from threads order by id desc limit 100) th on tt.thread_id = th.id group by t

hillcow's avatar
hillcow's avatar Youz8yrs agoLaravel
5
1
Last reply by Youz 8yrs ago
amrsoft's avatar

turn mysql query to Laravel

Hello , i have this query , can anyone help me to make same using laravel way thanks SELECT `categories`.`id`,`categories`.`cat_name`,COUNT(`tenders`.`cat_id`) FROM `categories` left JOIN `tenders` ON `tenders`.`cat_id` = `categories`.`id` WHERE `categories`.`active`=1 GROUP BY `categories`.`id`

amrsoft's avatar
amrsoft's avatar jlrdw8yrs agoLaravel
3
1
Last reply by jlrdw 8yrs ago
Leff7's avatar

Laravel eloquent - making query with optional value key parameters with relationship

I need to make a query with optional parameters array, that could look something like this: array:3 [ "parent" => "prosjektsamarbeidets" "category" => "article" "slug" => "prosjektsamarbeidets-verdi" ] It will always have a slug parameter but other parameters are optional in the array. With this argumen

Leff7's avatar
Leff7's avatar Leff78yrs agoEloquent
0
1
Xanger's avatar

Select2 does not put all ID in the query

Hi, I have inserted the select and work properly, but if I try to put a multiselect with select2 I have problems. Controllers: $articoli = Articoli::find($articleId); $articoli->id_gioco = $request->get('id_gioco'); $articoli->id_console = $request->get('id_console'); $articoli->save(); Blade: <select class="col-md-12" name="id_gioco[]" i

Xanger's avatar
Xanger's avatar Xanger8yrs agoLaravel
2
1
Last reply by Xanger 8yrs ago
maslauskast's avatar

Get join query from relationship

Hi, is there any way to get the join query from relationship object? I need to join many related models and I don't want to write all the joins, maybe there's a way to pluck it from related model by any chance?

maslauskast's avatar
maslauskast's avatar maslauskas...8yrs agoEloquent
0
1
FehriJawher's avatar

Query builder

Hi, please can any one tell me how can i convert this query to eloquent query builder SELECT id_produit , COUNT(id_produit) FROM commandes GROUP BY id_produit ; Thank u all

FehriJawher's avatar
FehriJawher's avatar FehriJawhe...8yrs agoLaravel
1
1
Last reply by FehriJawher 8yrs ago
berkkaya's avatar

How to do this query in Laravel Query Builder

Hi guys, I have tried to implement this query on query builder but I failed. select *, (SELECT avg(score) FROM scores where application_id = A.id) as score from application_forms as A inner join users as B on A.user_id = B.id This is what I tried but I cant add scores table :) DB::table('application_forms as A') ->join('users as B', 'A.user_id', '=', 'B.id') ->select( '*

berkkaya's avatar
berkkaya's avatar jlrdw8yrs agoLaravel
8
1
Last reply by jlrdw 8yrs ago
pravash's avatar

laravel conditional nested query

I have a table name product having column name taraget_university. I need query somethings like Product::where("sold_to_user",null) if target_university == null then continue if target_university !=null then query->where("target_university",$university -> id) ======================================= ->whereIn("user_id",$userArray) ->get(

pravash's avatar
pravash's avatar Hawkleaf8yrs agoLaravel
3
1
Last reply by Hawkleaf 8yrs ago
sheldonscott's avatar

Multiple leftJoins using Laravel's Query Builder producing incorrect counts

I am using Laravel 5.4's Query Builder to perform a series of leftJoins on three tables. Here are my tables: items | id | type | title | visibility | status | created_at | |----|------|---------------------|------------|--------|---------------------| | 1 | 1 | This is a Title | 1 | 1 | 2017-06-20 06:39:20 | | 2 | 1 | Here's Anot

sheldonscott's avatar
sheldonscott's avatar sdurstling8yrs agoLaravel
2
2
Last reply by sdurstling 8yrs ago
madsem's avatar

Query Speed/Performance which one is faster:

Hey, which one would deliver results fastest when querying lots of relationships: ->with([ 'tags' => function ($query) { $query->select('id', 'tag_label'); // use index } ])->distinct(); or simply: ->with('tags') The difference I am seeing when running these with EXPLAIN in mysql is that the first one is using "Using whe

madsem's avatar
madsem's avatar madsem8yrs agoEloquent
0
1
jericopulvera's avatar

Laravel Query Builder Join method date where date is not working properly.

I have this list of property_prices that belongs to a property property_prices table |id |property_id|price|date | |10 |6 |100 |2017-06-22 | |11 |6 |200 |2017-06-23| |12 |6 |300 |2017-06-24| |13 |6 |400 |2017-06-25| My code looks like this $query ->select('properties.id') ->join('property_prices', funct

jericopulvera's avatar
jericopulvera's avatar jlrdw8yrs agoLaravel
3
1
Last reply by jlrdw 8yrs ago
GroundZero's avatar

Query with dynamic amount of joins

Ha guys, I have a unknown (1 up to 4) amount of joins that I would like to add to my query. Unfortunately, no matter what I do, the query ignores my join. No error, nothing. Can someone please help me out and tell me how to get this working? // create a new query object $products = new Products; // create selects and joins foreach($fields as $field){ switch($field){

GroundZero's avatar
GroundZero's avatar GroundZero8yrs agoLaravel
2
1
Last reply by GroundZero 8yrs ago
RayC's avatar

Is there a better way to make this query?

Hello All, I have a query that works as it is, but I'm thinking there could possibly be a better and more efficient way to run it. It suits it's purpose the way it is. Please review and let me know if you think there is a way that is better. Models: // Dealer public function users() { return $this->hasMany('Dbn\User'); } // User public function dealer()

RayC's avatar
RayC's avatar michaelrtm8yrs agoCode Review
5
1
Last reply by michaelrtm 8yrs ago
ianmcqueen's avatar

Using Query Parameter Bindings with whereRaw in Scope

I'm using a query scope and I'm getting 0 results when I should be getting 1 result for my query. On the Eloquent model... public function scopeHashtagSearch($query, $value) { return $query->whereRaw('json_contains(hashtags, \'["?"]\')', [$value]); } In tinker... >>> $query = App\Models\Forums\Post::hashtagSearch('matchit')->toSql(); => "se

ianmcqueen's avatar
ianmcqueen's avatar ianmcqueen8yrs agoEloquent
0
1
mstarkey's avatar

Raw SQL vs Eloquent query

Hi, I am trying to get my head round using a collection instead of a DB:: query the following code returns results a a json object but is not quite what i need: $entries = DB::table('timesheet_entries') ->join('timesheets', 'timesheet_entries.timesheet_id', '=', 'timesheets.id') ->where('client_id', $client_id) ->where('project_id',

mstarkey's avatar
mstarkey's avatar mstarkey8yrs agoEloquent
3
1
Last reply by mstarkey 8yrs ago
gmartha07's avatar

Query SQL

Hello. Can anyone help me to build this query in Laravel 5? (SELECT , (SELECT COUNT() FROM posts_likes AS tbl_likes WHERE tbl_likes.id_post = tbl_posts.id) AS likes, (SELECT COUNT(*) FROM posts_likes AS tbl_likes WHERE tbl_likes.id_post = tbl_posts.id AND tbl_likes.usuario='$userid') AS liked FROM posts_blog AS tbl_posts") I don't know how to do this in laravel. Thanks

gmartha07's avatar
gmartha07's avatar shakti8yrs agoLaravel
1
1
Last reply by shakti 8yrs ago
split19's avatar

nested relationship query

I have 3 tables: projects, entries and submissions relationships: Project hasMany(Entry:class) Entry belongsTo(Project:class) and hasMany(Submissions:class) belongsTo(User:class) Submission belongsTo(Entry:class) submissions table has a round field (value is 1, 2 or 3) How can I get a list of all submissions for a given Project, grouped by round and also grouped by user? Ie, I

split19's avatar
split19's avatar split198yrs agoLaravel
2
1
Last reply by split19 8yrs ago
SankalpRanade's avatar

Write Query using Eloquent

How do i Write following query using laravel's eloquent? SELECT v.*,s.service_name from service_list s , vendors v where v.service_id = s.id and v.account_status=2;

SankalpRanade's avatar
SankalpRanade's avatar malvika8yrs agoLaravel
6
1
Last reply by malvika 8yrs ago
RuinSain's avatar

No query results for model [App\Article].

Hi! Im having a strange problem. for some reason, i am getting the following error when i try to go to this route: article/create. the complete error is this: (2/2) NotFoundHttpException No query results for model [App\Article]. This is my route: Route::get('/article/create','ArticlesController@create'); And this is my controller: public function create() { re

RuinSain's avatar
RuinSain's avatar tomi8yrs agoLaravel
2
1
Last reply by tomi 8yrs ago
baqirfarooq's avatar

Query Laravel

I need a select query that display one record from each company. Each company have multiple products in product table. I need exact match criteria. I have following tables. 1) Users 2) Companies 3) Products 4) Industries 5) Product_industry 6) packages 7) media Example: I am search "led". Company xyz have more than 1 products having led in their title i need to displa

baqirfarooq's avatar
baqirfarooq's avatar baqirfaroo...8yrs agoEloquent
0
1
jpeterson579's avatar

How to make a url like domain.com/?&search=something trigger an eloquent query?

I would like to be able to create a url that has something looks like the following domain.com/page?&search=something which will then show the query results when the page is visited. Is this possible? How? Good practice or bad?

jpeterson579's avatar
jpeterson579's avatar rubol8yrs agoEloquent
2
1
Last reply by rubol 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.