Questions tagged [eloquent]

The Eloquent ORM included with Laravel provides a beautiful, simple ActiveRecord implementation for working with your database. Each database table has a corresponding "Model" which is used to interact with that table. Models allow you to query for data in your tables, as well as insert new records into the table.

Filter by
Sorted by
Tagged with
847 votes
38 answers
1.3m views

How do I get the query builder to output its raw SQL query as a string?

Given the following code: DB::table('users')->get(); I want to get the raw SQL query string that the database query builder above will generate. In this example, it would be SELECT * FROM users. ...
meiryo's user avatar
  • 11.4k
589 votes
26 answers
1.1m views

How to Create Multiple Where Clause Query Using Laravel Eloquent?

I'm using the Laravel Eloquent query builder and I have a query where I want a WHERE clause on multiple conditions. It works, but it's not elegant. Example: $results = User::where('this', '=', 1) ...
veksen's user avatar
  • 6,913
416 votes
16 answers
681k views

Laravel Eloquent Query: Using WHERE with OR AND OR?

How do I say WHERE (a = 1 OR b =1 ) AND (c = 1 OR d = 1) For more complicated queries am I supposed to use raw SQL?
Farzher's user avatar
  • 14.3k
408 votes
32 answers
822k views

Get the Last Inserted Id Using Laravel Eloquent

I'm currently using the below code to insert data in a table: <?php public function saveDetailsCompany() { $post = Input::All(); $data = new Company; $data->nombre = $post['name'];...
SoldierCorp's user avatar
  • 7,640
408 votes
33 answers
915k views

Laravel Checking If a Record Exists

I am new to Laravel. How do I find if a record exists? $user = User::where('email', '=', Input::get('email')); What can I do here to see if $user has a record?
Ben's user avatar
  • 5,727
380 votes
2 answers
635k views

Laravel - Eloquent "Has", "With", "WhereHas" - What do they mean?

I've found the concept and meaning behind these methods to be a little confusing, is it possible for somebody to explain to me what the difference between has and with is, in the context of an example ...
user avatar
377 votes
17 answers
422k views

Laravel - Eloquent or Fluent random row

How can I select a random row using Eloquent or Fluent in Laravel framework? I know that by using SQL, you can do order by RAND(). However, I would like to get the random row without doing a count on ...
DigitalWM's user avatar
  • 4,446
351 votes
13 answers
466k views

Eloquent Collection: Counting and Detect Empty

This may be a trivial question but I am wondering if Laravel recommends a certain way to check whether an Eloquent collection returned from $result = Model::where(...)->get() is empty, as well as ...
bitinn's user avatar
  • 9,268
340 votes
22 answers
570k views

Get Specific Columns Using “With()” Function in Laravel Eloquent

I have two tables, User and Post. One User can have many posts and one post belongs to only one user. In my User model I have a hasMany relation... public function post(){ return $this->...
Awais Qarni's user avatar
  • 17.8k
327 votes
5 answers
377k views

How to sort a Laravel query builder result by multiple columns?

I want to sort multiple columns in Laravel 4 by using the method orderBy() in Laravel Eloquent. The query will be generated using Eloquent like this: SELECT * FROM mytable ORDER BY coloumn1 DESC, ...
Sophy's user avatar
  • 9,105
326 votes
12 answers
461k views

Laravel Migration Change to Make a Column Nullable

I created a migration with unsigned user_id. How can I edit user_id in a new migration to also make it nullable()? Schema::create('throttle', function(Blueprint $table) { $table->increments('...
user391986's user avatar
  • 30.3k
324 votes
11 answers
569k views

How do you check "if not null" with Eloquent?

How do you check if a field is not null with Eloquent? I tried Model::where('sent_at', 'IS NOT', DB::raw('null'))->... but it gives IS NOT as a binding instead of a comparison. This is what DB::...
Marwelln's user avatar
  • 29k
293 votes
13 answers
351k views

Laravel Eloquent: Ordering results of all()

I'm stuck on a simple task. I just need to order results coming from this call $results = Project::all(); Where Project is a model. I've tried this $results = Project::all()->orderBy("name"); ...
MatterGoal's user avatar
  • 16.2k
288 votes
11 answers
442k views

Disable Laravel's Eloquent timestamps

I'm in the process of converting one of our web applications from CodeIgniter to Laravel. However at this moment we don't want to add the updated_at / created_at fields to all of our tables as we have ...
projectxmatt's user avatar
  • 3,201
285 votes
11 answers
359k views

Add a custom attribute to a Laravel / Eloquent model on load?

I'd like to be able to add a custom attribute/property to an Laravel/Eloquent model when it is loaded. For instance, at the moment, in my controller I have: public function index() { $sessions = ...
coatesap's user avatar
  • 11k
276 votes
24 answers
744k views

How to select specific columns in laravel eloquent

lets say I have 7 columns in table, and I want to select only two of them, something like this SELECT `name`,`surname` FROM `table` WHERE `id` = '1'; In laravel eloquent model it may looks like this ...
devnull Ψ's user avatar
  • 3,929
276 votes
3 answers
796k views

Laravel 4: how to "order by" using Eloquent ORM [duplicate]

Simple question - how do I order by 'id' descending in Laravel 4. The relevant part of my controller looks like this: $posts = $this->post->all() As I understand you use this line: ->...
Josh's user avatar
  • 6,089
266 votes
23 answers
655k views

Select Last Row in the Table

I would like to retrieve the last file inserted into my table. I know that the method first() exists and provides you with the first file in the table but I don't know how to get the last insert.
Carlos Suñol's user avatar
257 votes
41 answers
336k views

Migration: Cannot add foreign key constraint

I'm trying to create foreign keys in Laravel however when I migrate my table using artisan i am thrown the following error: [Illuminate\Database\QueryException] SQLSTATE[HY000]: General error: 1215 ...
user0129e021939232's user avatar
235 votes
12 answers
403k views

Bulk Insertion in Laravel using eloquent ORM

How can we perform bulk database insertions in Laravel using Eloquent ORM? I am working with an XML document, looping through its elements. I want to accomplish something like this in Laravel: $sXML = ...
phoenixwizard's user avatar
227 votes
3 answers
354k views

How to insert multiple rows from a single query using eloquent/fluent

I have the following query: $query = UserSubject::where('user_id', Auth::id())->select('subject_id')->get(); and as expected I get the following result: [{"user_id":8,"subject_id":9},{"...
Billy's user avatar
  • 2,923
226 votes
5 answers
120k views

What does "Mass Assignment" mean in Laravel?

When I went through Laravel Document about Eloquent ORM topic part, I got a new term "Mass Assignment". Document show How to do Mass Assignment and the $fillable or $guarded properties ...
Chen-Tsu Lin's user avatar
  • 23.1k
224 votes
13 answers
523k views

Laravel Eloquent "WHERE NOT IN"

I'm having trouble to write query in laravel eloquent ORM. my query is SELECT book_name,dt_of_pub,pub_lang,no_page,book_price FROM book_mast WHERE book_price NOT IN (100,200); Now I ...
Nur Uddin's user avatar
  • 2,888
222 votes
18 answers
403k views

Automatically deleting related rows in Laravel (Eloquent ORM)

When I delete a row using this syntax: $user->delete(); Is there a way to attach a callback of sorts, so that it would e.g. do this automatically: $this->photo()->delete(); Preferably ...
Martti Laine's user avatar
  • 12.9k
214 votes
14 answers
318k views

How to delete all the rows in a table using Eloquent?

My guess was to use the following syntax: MyModel::all()->delete(); But that did not work. I'm sure it's super simple, but I've searched for documentation on the subject and can't find it!
Pete's user avatar
  • 7,429
203 votes
10 answers
319k views

How to alias a table in Laravel Eloquent queries (or using Query Builder)?

Lets say we are using Laravel's query builder: $users = DB::table('really_long_table_name') ->select('really_long_table_name.id') ->get(); I'm looking for an equivalent to ...
prograhammer's user avatar
  • 20.4k
201 votes
12 answers
291k views

Laravel Check If Related Model Exists

I have an Eloquent model which has a related model: public function option() { return $this->hasOne('RepairOption', 'repair_item_id'); } public function setOptionArrayAttribute($values) { ...
Tom Macdonald's user avatar
193 votes
5 answers
320k views

Laravel orderBy on a relationship

I am looping over all comments posted by the Author of a particular post. foreach($post->user->comments as $comment) { echo "<li>" . $comment->title . " (" . $...
PrestonDocks's user avatar
  • 5,158
190 votes
19 answers
673k views

Laravel Eloquent groupBy() AND also return count of each group

I have a table that contains, amongst other columns, a column of browser versions. And I simply want to know from the record-set, how many of each type of browser there are. So, I need to end up with ...
kJamesy's user avatar
  • 6,113
190 votes
15 answers
498k views

Creating and Update Laravel Eloquent

What's the shorthand for inserting a new record or updating if it exists? <?php $shopOwner = ShopMeta::where('shopId', '=', $theID) ->where('metadataKey', '=', 2001)->first(); if ($...
1myb's user avatar
  • 3,586
188 votes
21 answers
176k views

Get the Query Executed in Laravel 3/4

How can I retrieve the raw executed SQL query in Laravel 3/4 using Laravel Query Builder or Eloquent ORM? For example, something like this: DB::table('users')->where_status(1)->get(); Or: (...
Patrick Maciel's user avatar
183 votes
7 answers
560k views

Eloquent - where not equal to

I'm currently using the latest Laravel version. I've tried the following queries: Code::where('to_be_used_by_user_id', '<>' , 2)->get() Code::whereNotIn('to_be_used_by_user_id', [2])->...
aBhijit's user avatar
  • 5,291
183 votes
12 answers
446k views

How to do this in Laravel, subquery where in

How can I make this query in Laravel: SELECT `p`.`id`, `p`.`name`, `p`.`img`, `p`.`safe_name`, `p`.`sku`, `p`.`productstatusid` FROM `products` p WHERE `p`.`id` IN ( ...
Marc Buurke's user avatar
  • 1,937
170 votes
8 answers
521k views

Laravel Eloquent Sum of relation's column

I've been working on a shopping cart application and now I've come to the following issue.. There is a User, a Product and a Cart object. The Cart table only contains the following columns: id, ...
Admiral's user avatar
  • 1,898
163 votes
8 answers
339k views

Laravel where on relationship object

I'm developing a web API with Laravel 5.0 but I'm not sure about a specific query I'm trying to build. My classes are as follows: class Event extends Model { protected $table = 'events'; ...
Lic's user avatar
  • 1,907
162 votes
6 answers
306k views

How to Make Laravel Eloquent "IN" Query?

I want to make query in Laravel Eloquent like here its raw MySQL query SELECT * from exampleTbl where id in(1,2,3,4) I have tried this in Laravel Eloquent but it's not working DB::where("id IN(...
Ravi Jethva's user avatar
  • 2,001
161 votes
14 answers
156k views

Laravel Pagination links not including other GET parameters

I am using Eloquent together with Laravel 4's Pagination class. Problem: When there are some GET parameters in the URL, eg: http://site.example/users?gender=female&body=hot, the pagination links ...
Nyxynyx's user avatar
  • 62.5k
154 votes
9 answers
510k views

Property [title] does not exist on this collection instance

I am following Laracasts' videos: Basic Model/Controller/View Workflow. I have a table holds contact information. CREATE TABLE `about` ( `id` int(10) UNSIGNED NOT NULL, `title` varchar(500) COLLATE ...
zkanoca's user avatar
  • 9,838
154 votes
2 answers
126k views

Retrieve Laravel Model results based on multiple ID's

I have implemented ZendSearch into my Laravel application. I am using it as my search engine where users will type a search word, and then ZendSearch will return me an array of results ordered by ...
justinl's user avatar
  • 10.5k
151 votes
15 answers
386k views

How to get distinct values for non-key column fields in Laravel?

This might be quite easy but have no idea how to. I have a table that can have repeated values for a particular non-key column field. How do I write a SQL query using Query Builder or Eloquent that ...
gthuo's user avatar
  • 2,456
147 votes
12 answers
267k views

How to select from subquery using Laravel Query Builder?

I'd like to get value by the following SQL using Eloquent ORM. - SQL SELECT COUNT(*) FROM (SELECT * FROM abc GROUP BY col1) AS a; Then I considered the following. - Code $sql = Abc::from('abc ...
quenty658's user avatar
  • 1,597
146 votes
5 answers
230k views

Eloquent get only one column as an array

How to get only one column as one dimentional array in laravel 5.2 using eloquent? I have tried: $array = Word_relation::select('word_two')->where('word_one', $word_id)->get()->toArray(); ...
Riiwo's user avatar
  • 1,909
145 votes
4 answers
200k views

Is there a way to "limit" the result with ELOQUENT ORM of Laravel?

Is there a way to "limit" the result with ELOQUENT ORM of Laravel? SELECT * FROM `games` LIMIT 30 , 30 And with Eloquent ?
Natan Shalva's user avatar
  • 1,572
140 votes
9 answers
272k views

How to Merge Two Eloquent Collections?

I have a questions table and a tags table. I want to fetch all questions from tags of a given question. So, for example, I may have the tags "Travel," "Trains" and "Culture" attached to a given ...
Martyn's user avatar
  • 6,187
139 votes
1 answer
121k views

Laravel. Use scope() in models with relation

I have two related models: Category and Post. The Post model has a published scope (method scopePublished()). When I try to get all categories with that scope: $categories = Category::with('posts')-...
Ilya Vo's user avatar
  • 2,269
136 votes
7 answers
347k views

Laravel Eloquent - Get one Row

This might be a simple question, but I cannot figure this out. I am trying to get a user by email using: $user = User::whereEmail($email)->get(); But this is returning an array (of dimension 1) ...
Kousha's user avatar
  • 34.8k
136 votes
14 answers
579k views

Laravel Eloquent - distinct() and count() not working properly together

So I'm trying to get the number of distinct pids on a query, but the returned value is wrong. This is what I try to do: $ad->getcodes()->groupby('pid')->distinct()->count() what returns ...
Inigo EC's user avatar
  • 2,258
135 votes
10 answers
534k views

Laravel Eloquent limit and offset

This is mine $art = Article::where('id',$article)->firstOrFail(); $products = $art->products; I just wanna take a limit 'product' This is wrong way $products = $art->products-&...
Sang Trần's user avatar
  • 2,217
134 votes
4 answers
44k views

Managing relationships in Laravel, adhering to the repository pattern

While creating an app in Laravel 4 after reading T. Otwell's book on good design patterns in Laravel I found myself creating repositories for every table on the application. I ended up with the ...
ehp's user avatar
  • 1,699
132 votes
9 answers
346k views

Convert a collection of models to an array of models

I have two models, Post and Comment; many comments belong to a single post. I'm trying to access all comments associated with a post as an array. I have the following, which gives a collection. $...
datavoredan's user avatar
  • 3,676

1
2 3 4 5
545