FAQ Database Discussion Community


Laravel 5: Convert query builder to eloquent

php,eloquent,laravel-5,query-builder,php-carbon
Is there a way to transform this query builder to eloquent? $users = DB::table('connections') ->join('locations','connections.to_user','=','locations.user_id') ->join('users','connections.to_user','=','users.id') ->select( DB::raw("*, IF(( 3959 * acos( cos(radians(".$lat.")) * cos(radians(latitude)) * cos(radians(longitude) - radians(".$lng.")) + sin(radians(".$lat.")) * sin(radians(latitude))) ) < ".$distance.",true,false) near,( 3959 * acos( cos(radians(".$lat.")) * cos(radians(latitude)) * cos(radians(longitude) -...

Error while Eager loading a Eloquent model with multiple relationship in Laravel 5

php,laravel,eloquent,laravel-5,relationship
My User model have two relationships public function group(){ return $this->belongsTo('App\Group','group_id'); } public function profile() { return $this->hasOne('App\Profile','user_id'); } And Accessing them in Controller like $users = \App\User::with('group','profile')->get(); However, Retriving Profile Model's column give error (Inside a @foreach loop ) @foreach ($users as $user) URL::action('[email protected]',[$user->profile->id]) @foreach ($users as $user) Error...

laravel 5 - not sure what kind of relationship I need between two eloquent models

eloquent,laravel-5,relationship
I'm having an issue trying to determine the relationship for the given scenario: Table `appointments` id service_id client_id ... Table `clients` id ... Table `services` id ... What I want is to show all clients for a given service. I initially thought it might be a hasManyThrough IE a service...

Binding vars to raw queries

laravel,laravel-4,eloquent,laravel-5
I'm trying to bind vars to my raw query: $data = $myModel->select( DB::raw('(3959 * acos(cos(radians(:lat)) * cos(radians(lat)) * cos(radians(lng) - radians(:lng)) + sin(radians(:lat)) * sin(radians(lat)))) as distance'), array( 'lat' => $lat, 'lng' => $lng, ))->orderBy('distance', 'ASC')->having('distance', '<', $radius) ->get(); I've checked various SO posts which lead to this blog post:...

Laravel Eloquent: access method parameter within chunk Closure

php,laravel,static,scope,eloquent
I need to pass an anonymous function to a static method on an Eloquent model and have that static method call the closure within a chunk closure. The goal is code similar to the following: class MyModel extends Eloquent { // ... table stuff public static function doSomething (Closure $thing)...

SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails error in Laravel 4

mysql,laravel,laravel-4,foreign-keys,eloquent
I am recieving the following error: SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`database`.`messages`, CONSTRAINT `messages_sender_id_foreign` FOREIGN KEY (`sender_id`) REFERENCES `users` (`id`) ON UPDATE CASCADE) (SQL: insert into `messages` (`subject`, `message`, `draft`, `updated_at`, `created_at`) values (test, testgdsgds, 0, 2015-05-24 16:03:59,...

Laravel 5 No query results for model redirect page

laravel,view,eloquent
I have simple form that post values to a controller,everything works fine if a result is returned from the controller , but if there is no result I get error the following error: No query results for model Which works as it should. My question is : Is it possible...

save one to one relationship. foreign keys in both tables

laravel,eloquent,foreign-key-relationship,one-to-one
I have two tables as follow: CREATE TABLE pets( id int NOT NULL AUTO_INCREMENT, user_id int, any_data varchar(255), foreign key (user_id) references users(id), primary key(`id`) ); CREATE TABLE users( id int NOT NULL AUTO_INCREMENT, pet_id int, any_data varchar(255), foreign key (pet_id) references pets(id), primary key(`id`) ); And my models have...

Laravel (Eloquent) Table || Peer equivalent

php,laravel,doctrine,eloquent,propel
Propel uses Peer classes, and doctrine used Table classes as a way to manipulate respective objects and object properties, without having to pollute the actual object with static methods. After cursory glance of the laravel (eloquent) docs, I didn't see anything that eloquent provides for the same Peer or Table...

How can I select with count() on specific user in Laravel?

mysql,laravel,eloquent
Here is my Database structure: Also - there is a table users and reciever_id references that table id. I use that query to get count of each type of notifications as well as data for that type of notifications from notification_types table. Notification:: select('notification_types.*', DB::raw('count(*) as total')) ->join('notification_types', 'notifications.type_id', '=',...

Multiple Where In

mysql,laravel,laravel-4,eloquent,laravel-5
I'm using eloqent to filter a set of products: Product::whereIn('color', $color)->whereIn('size', $size)->whereIn('price', $price)->get(); Each of the above variables is an array of ids $color = [1,2,4,5] My question is, is this inefficient when the user fails to send through a set of variables, say they did not want any color...

Summing and grouping according to city and payment type with laravel eloquent

php,mysql,laravel,eloquent
I have three different tables: cities, payment_types and payments. I want to create summary report for the payments. cities table: And then payments type table: And payments table: What I want to get is (I want to create this summary) so, according to summary city doesn't repeat and grouped by...

Automaticlly attach to pivot table in Laravel 5

php,eloquent,pivot,relational-database,laravel-5
I currently have a Users to Groups Relationship (ManyToMany) with a pivot table group_user. I want the user to be able to create a group but once creating the group, how do I make it, that the creator becomes member of this group? Currently I have My Pivot Table (group_user):...

Laravel eloquent complex queries on relationships2

php,laravel,eloquent
Tables Business id name Portfolio id image description business_id Models class Business extends \Eloquent { public function portfolio() { return $this->hasMany('Portfolio'); } } class Portfolio extends \Eloquent { public function business() { return $this->belongsTo('Business'); } } Now i want to know is it possible if i have a portfolio id...

Laravel eloquent returns same row with different where clause

laravel,eloquent
i want to check username if taken, but eloquent is running weird for me... In my database, only one user is registered, username is yigitabi when i try to get user where username is yigitabi it returns the row but when i try to get user where username is yiğitabi...

Laravel 4 eloquent WHERE with AND and OR?

laravel-4,eloquent
How do I say WHERE (a=x AND b=y) OR (c=z AND d=j) For x , y , z .. are variables . How can i do that with eloquent ?...

Laravel 5 response()->json always returns an array?

php,json,eloquent,laravel-5
Is there any way to stop laravel always returning an array, regardless if there is only a single element? I've checked the docs and come up short. It's fine if thats just the way it is of course, just seems a little silly, as you wouldn't post an array to...

retrieving multiple records associated to multiple records laravel 4.2

php,laravel,laravel-4,eloquent,blade
recently i asked this question which got one answer but unfortunately didn't solve the problem, after that i got no more answers and i really need to fix this problem i have. Alright so i have to make a quiz website for my school in which a user should be...

How properly select data from DB according to filter in Eloquent?

php,mysql,laravel,eloquent
I have a filter. Filter contains three fields. Call_Date_From, Call_Date_Till, Telephone. So I need to select from LEADS (Lead Model) table all rows that fit filter. In raw Php + MySQL I would write something like this: $sql = ' WHERE '; $post['call_date_from'] ? $sql .= ' `call_date` >= '...

How to do a self join in laravel resulting in distinct values

sql,laravel,eloquent
ID|user_id |book_id |author 1 |8 |7 |bill 2 |8 |6 |sally 3 |3 |7 |rob 4 |3 |4 |sarah 5 |3 |6 |jane 6 |8 |7 |frank What I want to achieve are rows that user_id 8 book_ids match that of user_id 3 book_id. but only user_8s rows selected. And...

Laravel multiple whereIn array

laravel,eloquent
I was wondering if there is a way to use whereIn with an array of arrays, something like the where with array User::where(['user_id' => $currentUser, 'group_id' => $currentGroup]); so i'm looking for this: User::whereIn(['group' => $availableGroups, 'session' => $currentSessions]). which should be equivalent to using the whereIn clause twice. I...

Self Join in Eloquent - How To Call

laravel,laravel-4,eloquent,laravel-5
I recently asked a question regarding a self join SO I got a great answer but I'm not sure how to call it. I need to do this query: SELECT t2.title FROM products t1, products t2 WHERE t1.id = $id AND t2.color_id = t1.color_id AND t2.id != $id I now...

Issue when trying to populate a drop-down with database values

mysql,laravel,laravel-4,eloquent
I am using the following HTML to show a selected drop down with values from the database and rest of the others in the list. It shows the selected name correctly but the selected is also displayed in the list. How to remove the second time show selected name in...

Facing issue while reusing mongo connection

php,mongodb,eloquent
I have 'employees' collection I'm creating new mongo connection by using following code $mongoObject = DB::connection('mongodb')->collection('employees'); //fetch employee by employee id $employee = $mongoObject->where('employee_id', $input['employee_id'])->first(); //Fetch all employees $employees = $mongoObject->get(); Now my problem is that I got first response properly but when I tried to fetch all employees by...

Merging collections

laravel,eloquent,laravel-5
I have a raw query: $data = Product::hydrateRaw(//sql here); This returns a collection. I then perform a further query: $data2 = Product::take(3)->get(); I then wish to merge both collections: $data->merge($data2); Unfortunately the merge appears to have no effect, when I dd() the collection only contains $data and not $data2. Where...

Caching issue in angularJS application

angularjs,caching,orm,eloquent,slim
I've an admin panel which is a pure angularJS application, which uses REST api for data manipulation. REST api is built using SlimAPI framework and Laravel's Eloquent ORM. I'm facing caching issue in admin panel. Even though if a add new content to the system, it'll not show up in...

Querying one-to-one in laravel

php,laravel-4,orm,eloquent
I have two models city and business.I have to perform below queries Find Business by city name. Find Top 10 cities which have the maximum business. Here is the models Business class Business extends \Eloquent { protected $fillable = [ 'business_type', 'first_name', 'last_name', 'email', 'password', 'designation_id', 'name', 'description', 'portfolio_id', 'image',...

Creating an Eloquent Object with relation included

php,laravel,eloquent,laravel-5,foreign-key-relationship
I'm pretty much new to opps and laravel both So, to insert the values into my users and profiles table which hav OneToOne relationship, Here is how my store() method looks like public function store(Requests\StoreNewUser $request) { // crate an objct of user model $user = new \App\User; // now...

how to make a update page with hasMany relatioins in laravel

php,laravel,eloquent
I'm trying to create a form to update a model which has one to many relations. The structure is like item => {[arg1, arg2], [arg1, arg2], [arg1, arg2]} Each related model has two fields to be updated. I used the code below but I don't know how to code the...

findOrFail laravel 5 function for specific filed

database,laravel,view,eloquent
This is my code: $get_all = Geo_Postal_us::findOrFail($postal); With this query,laravel try to find ID filed in table. I don't have id filed, for primary key i have postal column. So, how to set function to find value in postal column, not to search from id column ? Thanks,...

How to perform a statement inside a query to check existence of a file that has the query id as name with less resources in laravel

php,function,laravel,laravel-4,eloquent
i'm looking for away to see if the query 'id' has a folder with the same id as name in the file system, i did it but it will slow down the drive in the future with lots of files $query = Model::all(); if(Input::get('field') == 'true'){ $filenames = scandir('img/folders'); $query->whereIn('id',...

How to use an array from a query result and to then be used again for another query

php,laravel,eloquent
The scenario is that I have a friend who will only lend me his borrowed books if he knows he can get the same books at another library. So he does the following query: $collectbook= LibraryOne::where('user_id', Auth::id())->get(); He then needs to loop through the array to collect the relevant IDs...

where method not working properly on laravel?

laravel,eloquent,laravel-5,where-clause,php-carbon
I'm trying to extract the last user workouts and I don't know why I can't do this. I think I'm doing well. Please, check it out.

Id Column Overwritten by Join

php,mysql,laravel,laravel-4,eloquent
Using Laravel 4.2 & MySQL. I have an applications table with an id and a fit_score_id column, and a fit_scores table with an id column. It's a basic "belongs to" relationship. The following code: $query = Application::join('fit_scores', 'applications.fit_score_id', '=', 'fit_scores.id'); $collection = $query->get(); ...produces a collection of Application models with...

Retreiving a single colum from a pivot table - Laravel 5

php,laravel,eloquent,laravel-5
I am using a pivot table genre_user to relate user to genre. table contains the following fields id user_id genre_id Following are the model definitions User.php public function genres() { return $this->belongsToMany('App\Genre'); } Genre.php public function artists() { return $this->belongsToMany('App\User'); } I am getting the results as a collection when...

Adding to a collection?

laravel,laravel-4,eloquent,laravel-5
This is a simplified version of what I need to do, so the below may seem pointless. I get a row with: $firstProduct = Product::first(); I also get all out with: $ data = Product::all(); I need the first product to be in position 5 so I: $data = $data->splice(5,...

Laravel. Eloquent query for two tables

php,mysql,sql,laravel,eloquent
I want to write laravel eloquent query which could select all the titles from titles table where title_id doesnt't exist in title_count table. Here is an example. titles table: title_id 1 2 3 4 title_count table: title_id 3 4 So my query should select titles with id's 1, 2...

Tinder Laravel matching between 2 models

php,laravel,laravel-4,eloquent,tinder
i have 2 tables namely users and employers . I would like to match them together like tinder style, which means that when both the user and the employer liked each other , they will each receive a notification . However i am not sure how would the relationship table...

Advanced nested AND clause in Laravel 5 Eloquent

laravel,eloquent,laravel-5
I am having a hard time converting this query to laravel eloquent and any help will be well appreciated. The query that I need to run is SELECT * FROM `articles` WHERE `articles`.`deleted_at` IS NULL AND `id` <> 2 AND (`tags` LIKE '%tag1%' OR `tags` LIKE '%tag2%') This is what...

How to use LIMIT query based on the ORDER BY clause in Eloquent

php,postgresql,laravel,eloquent,laravel-5
I have two tables (and corresponding Models) as following: posts ( id auto_increment, category_id refrences_id_on_categories, data json date timestamp ) and categories ( id auto_increment, name text ) I could get 5 posts using: Post::orderBy('category_id', 'asc')->take(5)->get(); But, Is there any way to get 5 posts of each Category using Eloquent...

How to Retrieve data form many to many relation in laravel4?

php,mysql,laravel-4,eloquent
Business Modal class Business extends \Eloquent implements UserInterface, RemindableInterface{ public function services() { return $this->hasMany('Services'); } } Service Modal class Service extends \Eloquent { public function business() { return $this->belongsTo('Business'); } public function tag() { return $this->belongsToMany('Tag','service_tags','service_id','tag_id'); } } Tag Modal class Tag extends \Eloquent { public function service() {...

Laravel: Error [PDOException]: Could not Find Driver in MySQL

php,mysql,database,laravel,eloquent
I'm trying save a register in my MySQL database using Eloquent of Laravel 5 I edited database information in .env file, localized in my system root path, and in config/database.php maintain 'default' => 'mysql' and other mysql connection information (it using env('DB_DATABASE', 'forge') for get informations) I can use Migration,...

Laravel update multiple rows using checkboxes

laravel,checkbox,eloquent
I need to understand how to use the laravel eloquent way to update multiple rows in a database, based on which checkboxes have been checked. I am using the following code right now, which is working to a certain extent: public function save() { $post_data = Input::get('checkbox'); if(is_array($post_data)) { foreach...

Laravel 5 - __callStatic function is working correctly?

php,laravel,eloquent,laravel-5
I have a model extended from Model its name is IcerikRltCategory and i want to use getTable function with staticly. But __callStatic function does not fire anything. Because not entered this magic function scope. Error message is: 1/1 ErrorException in ContentController.php line 51: Non-static method Illuminate\Database\Eloquent\Model::getTable() should not be called...

Can not access the 3rd table in laravel 5 in 3 tables have relationships

laravel,laravel-4,eloquent,laravel-5
I have these table - users table id name password - keywords table id name user_id - groups table id name keyword_id I want to retrieve logged in user groups $groups = Group::with(['keyword' => function($query){ $query->where('user_id' , Auth::user()->id) }]); but all groups return NOT that groups for that user....

How can I utilize a table and a view within a single Eloquent model based on the SQL statement?

php,mysql,eloquent,laravel-5
Using Laravel 5.1, I have created an Eloquent Model: class Divisions extends Model { } I have a table and a view in my database which are relevant to this model. divisions_info - The table, it will have INSERT and UPDATE queries run, but will never have a SELECT run...

Retrieving the Slug from URL for function (Laravel 5)

php,eloquent,laravel-5,blade,slug
I'm making an App where a group is created by a user. This user can go to the group page (automated unique slug is created for the groups). My goal is for the member who created the group, to be able to make a invite code for that specific group....

Combine accessor and mutator logic to add custom attributes to a model

php,laravel,eloquent,laravel-5
I know about Laravel's accessors and mutators that can adjust attribute values when getting or setting a model. However, this can be done only with existing model attributes. I wonder if there's any way to create a combination of accessor and mutator that would let me set custom attributes for...

Laravel get posts with multiple tags

php,sql-server,laravel,eloquent
I'm working with a laravel belongsToMany relationship between Post and Tag. What I'm trying to do is get all Posts where it has multiple tags. I've tried all sorts of eloquent queries, but I can't get it at all. Currently I can get an array of post_id's and tag_id's, as...

Eloquent model not updating updated_at timestamp

php,laravel,timestamp,eloquent
I'm using Laravel 5.1. To make it simple, I have the following code Migration: Schema::create('sitemap_data', function (Blueprint $table) { // Primary and foreign keys $table->increments('id'); $table->string('postUrl'); // Database functions $table->timestamps(); }); And this is the code somewhere else I'm using $sitemapData = SitemapData::firstOrNew([ 'postUrl' => $post ]); $sitemapData->save(); Now, according...

Eloquent looks for wrong column

php,laravel,eloquent
My migration Schema::create('tickets', function(Blueprint $table) { $table->increments('id'); $table->text('subject'); $table->text('body'); $table->integer('author_id')->unsigned(); $table->timestamps(); }); Schema::table('tickets', function($table) { $table->foreign('author_id')->references('id')->on('users'); }); Relations public function createdTickets() { return $this->hasMany('App\Ticket'); } public function author(){ return $this->belongsTo('App\User', 'author_id'); } And store method...

How to sum groupBy in Laravel5

php,laravel,eloquent
Is a simple question about Eloquent , this eloquents returns correctly the user group by name $pujas = Bid::orderBy('created_at','desc')->take(10)->usuarios()->subasta()->groupBy('id_user')->get(); I need to sum the value of the users import in the auction, the row is called 'importe', the result now with this eloquent is this : UPDATE QUESTION I managed...

Laravel: Retrieve polymorphic attributes efficiently

rest,laravel,polymorphism,eloquent
My actual Question is: How to return attributes to the client which I actually need, throw the rest away and be as efficient as possible? So, I have a construction where I basically have media objects, which can be of different types, like video, picture, link and so on. This...

Larevel/SQL: Query model where relationship = X

php,sql,laravel-4,eloquent
Context I have three models below: listing, rooms and room types - LISTING |-----|-------------|--------------------| | ID | title | description | |-----|-------------|--------------------| | 1 | some title | some description | | 2 | some title | some description | | 3 | some title | some description | etc...

Laravel - Sorted collection output is not an array

php,mysql,sorting,laravel,eloquent
I'm trying to sort a collection by the column name. I am logging the ajax result and when I sort by name I get: Object: {0: Object, 1: Object, ...} But when I sort by the other field (locationId) I get: [Object, Object, ...] Any idea what I'm doing wrong?...

Laravel query. Where unique

php,sql,laravel,eloquent
I got database table like this: **job_id** 5 5 5 6 6 7 8 8 I want to write query, which could select only unique id's. By saying unique I mean select only these values once: 5, 6, 7, 8 Thanks in advance!...

Why Am I Able to Use user() method in laravel, without even defining it

php,laravel,eloquent,laravel-5,laravel-middleware
I do have a UserController and User Model in my Laravel 5 source. Also there is one AuthController is also Present (shipped prebuilt with laravel source). I would like to query data from db in my blades making use of Eloquent Models. However, Neither in my User Model (Eloquent )...

Laravel: take(1)->count(); what does this mean?

laravel,eloquent,relationship
I am studying the source code of a package, rtConner/laravel-tagging. In this package there is a trait called TaggableTrait. On line 179, in a method called addTag(), there is this line which I don't understand: $previousCount = $this->tagged()->where('tag_slug', '=', $tagSlug)->take(1)->count(); What does this line do? In specific, my problem is...

Laravel Eloquent how to return one to many to many collection

php,eloquent,laravel-5
Is it possible to get an eloquent relation based on a One->Many->Many relationship? In the below example, I would want to get all of the gallery_votes for a given user. users +----+---------------+ | id | user_name | +----+---------------+ | 1 | bob | | 2 | sam | +----+---------------+ galleries...

Updating a pivot table

laravel,laravel-4,eloquent,laravel-5
I have a pivot table id | product_id | user_id I wish to update this pivot table, I do so by: Product::find($productId)->attach($userId); This will produce something like id | product_id | user_id 1 1 1 But then when I do it again I do not want to update the pivot...

Laravel 5: Access attribute from other Model

php,eloquent,laravel-5
I'm trying to use a whereBetween inside a whereHas but my whereBetween is not working because inside whereHas is not getting my turned attribute from my User Model: This is my query DB::raw("*, ( 3959 * acos( cos(radians(?)) * cos(radians(latitude)) * cos(radians(longitude) - radians(?)) + sin(radians(?)) * sin(radians(latitude))) ) AS...

Correct form to get last uer id in laravel5

php,orm,user,eloquent
Good Morning ! I am developing a profile user and I have the following doubt. I know that I get my last user which the following form $full = User::orderBy('id','desc')->take(1)->get(); I recieve this json with this eloquent. . [{"id":58,"nif":"AAAA","name":"AAA","cognoms":"AAA","file":"uploads\/\/f0414.gif","birthday":"0000-00-00","presentacion":"descripciones","email":"[email protected]","idempresa":1,"id_poblacion":2254,"id_online":0,"created_at":"2015-05-24 00:00:40","updated_at":"2015-05-24 00:00:40"}] But...

Laravel 5: Chicken and egg when creating a one-to-one relationship

laravel,eloquent
Let's assume I have two Model elements: Person Computer In my application a Person May have one computer (a person has 0..1 computers). So In my User Model, I have: public function computer() { return $this->hasOne('App\Model\Computer'); } In my Computer Model I have: public function owner_user() { return $this->belongsTo('App\Model\User'); }...

How to skip a row with file exists condition in laravel

laravel,search,eloquent
This is for a search query based on many input fields, i'm doing if statements inside the query based on the inputs, for example : $query = Model::all(); if($field = Input::get('field')) $query->where('column_name', $field); but what i want to do also is a condition to skip a row if there is...

DISTINCT method using Laravel 5 eloquent query builder

php,mysql,eloquent,laravel-5
I'm struggling to get unique results when using the DISTINCT method in laravel. This is my query //Get users that are part of this sector $users = DB::table('users')->distinct() ->join('projects', 'users.id', '=', 'projects.userID') ->where('projects.sectorID', '=', $sector->sectorID) ->get(); dd($users); The result shows 3 users with the same ID, when I only want...

Laravel 5.0: Form::select() called twice Eloquent Accessor by select name

php,laravel,eloquent,laravel-5,accessor
Blade template: {!! Form::model($category) !!} {!! Form::select('drinks_id', [...full list...]) !!} {!! Form::close() !!} 'drinks_id' called by Eloquent Accessor: public function getDrinksIdAttribute() { var_dump('get'); return 123; } When Form::select('drinks_id') execute, getDrinksIdAttribute() called twice and print string(3) "get" string(3) "get" from var_dump(). If I write this: {!! Form::model($category) !!} {!! var_dump($category->drinks_id) !!}...

Laravel, WebSockets - Verify user on server

php,session,laravel,eloquent,ratchet
I currently ran into the problem of handling the authentification of a user on the server, using Laravel and RachetPHP. What I tried so far: I changed the driver type of the session to database, giving me an id and payload column. Using \Session::getId() returns a 40 character string. The...

I can't use some Eloquent methods

laravel-4,eloquent,cartalyst-sentry
I'm trying to use Eloquent with a relationship and alwys have th same result: Call to undefined method Illuminate\Database\Query\Builder::xxxx() where xxxx could be "sons" defined in my model or save() if I use another code. First of all I have this two models (simplified): <?php use Cartalyst\Sentry\Users\Eloquent\User as SentryUserModel; class...

Custom accessors Eloquent Model

arrays,laravel,model,eloquent
I have a Eloquent Model and I want to create a customized toArray method... class Posts extends Model { public function scopeActives($query) { return $query->where('status', '=', '1'); } public function toCustomJS() { $array = parent::ToArray(); $array['location'] = someFunction($this->attributes->location); return $array; } } //In my controller: Posts::actives()->get()->toArray(); //this is working Posts::actives()->get()->toCustomJS();...

Eloquent sortBy - Specify asc or desc

php,arrays,laravel-4,eloquent
Trying sort my eloquent collection: $collection->sortBy('field'); There is no information in Laravel 4's docs on how to choose descending or ascending for this sort method. Is it possible?...

Laravel 5 Eloquent Condition (IN)

eloquent,laravel-5
I have the following Model Relationship Models Sector - [id, name] Location - [id, sector_id, name] Sector has many locations Location belongs to sector class Location extends Model { public function sector() { return $this->belongsTo('App\Sector'); } } I want to make the following query using Laravel 5 Eloquent SELECT *...

Laravel getting results from model belongsToMany relationship back to controller

php,laravel,eloquent,laravel-5
I'm using Laravel 5 and Eloquent, I have 3 tables setup: photos +----+---------------+------------------+ | id | photo_name | photo_location | +----+---------------+------------------+ | 1 | kittens.jpg | C:\kittens.jpg | | 2 | puppies.jpg | C:\puppies.jpg | | 3 | airplanes.jpg | C:\airplanes.jpg | | 4 | trains.jpg | C:\trains.jpg | +----+---------------+------------------+...

Access a protected field from queried Eloquent object

php,laravel,laravel-4,eloquent
I query an entity: $trip_redirect_id = Trip::whereUniqueToken($unique_token)->select('id')->get(); and try to get the id value with $trip_redirect_id->id or $trip_redirect_id['id'] but I get exception that the field is not present. When I dump the $trip_redirect_id object, I can see the id and it's value and they are correct (I checked with the...

Laravel 5 Eloquent where and or in Clauses

sql,laravel,eloquent
i try to get results from table with multiple where and/or clauses. My SQL statement is: SELECT * FROM tbl WHERE m__Id = 46 AND t_Id = 2 AND (Cab = 2 OR Cab = 4) How i can get this with Laravel Eloquent? My Code in Laravel is: $BType...

Can you populate an Eloquent model without creating an entry in the database using Laravel 5

php,laravel,eloquent,laravel-5
When I'm adding or editing an entry to my database table websites I load the instance of the website to be modified (or a blank one for creating a website). This works great, this is my controller: <?php namespace App\Http\Controllers\Admin; use App\Http\Controllers\Controller; use Illuminate\Support\Facades\Request; use App\Models\User; use App\Models\Status; use App\Models\Website;...

Laravel Eloquent where and or between in one query

laravel,eloquent,where
Hello what is the Laravel eloquent code for this: SELECT * FROM dtrs inner join emp_informations on dtrs.enrollnum = emp_informations.enrollnum where (emp_informations.EmpID = '07081408') and (date_in between '2015-03-05' and '2015-03-20' and date_out between '2015-03-05' and '2015-03-20') ORDER BY dtrs . date_in DESC Here's my code in eloquent, and it doesn't...

Laravel 4 - Scope to only show rows where another DB has no relational items

laravel-4,eloquent,pivot-table
I have a cars table, and a car_image table. I want to get all the cars that have NO images in the car_image. In my car model I am making a scope: public function scopeNoImages($query) { return $query-> ?? } How can I create a scope that will show only...

Relationship results automatically coming out?

laravel,laravel-4,eloquent,laravel-5
I have a series of relations on my model, here is one of them. class Product extends Model{ public function user(){ return $this->belongsToMany('\App\User'); } } I get all rows with: $data = Product::all() And these are looped through like so: foreach ($data as $value) { var_dump($value->title); } My understanding was...

Laravel getting id from stored object

php,mysql,laravel,eloquent
I have a company table and an attributes table with all sorts of value in it. One company hasMany attributes and an attribute belongsTo a company. Now I have a value inside the attributes table with a 'account_nr_start' (for example, when a new user is added to a company its...

Unable to insert everything in database using laravel

php,laravel,eloquent,laravel-5
While trying to insert new fetched data into Laravel, I am unable to insert 2 fields i.e. type and provider into the database. Here is my code: $user = User::create([ 'name' => $userData->name, 'username' => $userData->name, 'email' => $userData->email, 'password' => 'asdffdas', 'type' => 'standard', 'provider' => $userData->id, 'active' =>...

Three-way many-to-many relationship in Laravel

laravel,eloquent,laravel-5
I have three models that need to be related in a pivot table: User, Student, Plan. So each user can subscribe a student to a plan. What I've found so far is to create a pivot for two of the models, say User and Plan, and attach the student_id as...

Get primary key of Eloquent model instance

php,mysql,laravel,orm,eloquent
I'm happy enough to work on a project with (not) very consistent column names in our MySQL database. We have camelCase, PascalCase, 'Id', ID and it's driving me nuts. I've decided to start using Eloquent in our application (which is NOT Laravel). I would love to have a method of...

Is Eloquent sortBy stable in Laravel 5?

php,eloquent,laravel-5
Is the sorting function on Laravel 5 Eloquent collections a stable sort? A stable sort will not reorder elements with equal sort key. That is, given this input list: | order | value | |-------+-------| | 5 | a | | 2 | b | | 5 | c |...

orWhere giving unexpected result

laravel,laravel-4,eloquent,laravel-5
I want to search pages whose lang_id = 1, I am using following laravel query $result = $this->where('lang_id', $this->langId ); $result->where('title', 'LIKE', '%'.$search.'%') ->orWhere('description', 'LIKE', '%'.$search.'%'); $result->get(); It gives me pages having lang_id other than 1 too. How to fix it?...

Laravel Eloquent combine Model::forceCreate and Model::firstOrCreate

php,laravel,eloquent
Hello world With Laravel & Eloquent, I'd like to : create a model, unless it already exists into the database (like Model::firstOrCreate allows) at the same time, pass it a few attributes, including some which are not listed in the $fillable array of the model (like Model::forceCreate allows). But how...

SubQueries in Laravel 4.2

mysql,laravel-4,eloquent
Can anyone teach me how can we use a query like this in Laravel 4.2 SELECT t.Truck_Number, t.Created_dt, t.Latitude, t.Longitude, t.Speed, t.Heading FROM truckgps t INNER JOIN ( SELECT Truck_Number, max(Created_dt) as MaxDate FROM truckgps GROUP BY Truck_Number ) tm ON t.Truck_Number = tm.Truck_Number AND t.Created_dt = tm.MaxDate this query...

Why do I need use 'with' in Laravel Eloquent?

php,laravel,eloquent
First of all, sorry for my bad English. I have Eloquent query $gigs = Gig::active() ->plusGigs() ->with('member') ->paginate(16); and I have with function in my model public function member() { return $this->belongsTo('App\User', 'USERID', 'USERID') ->select(array( 'USERID', 'username' )) } when I try to use on my view file {{ $gig->member->username...

Laravel: dynamic where clause with Elouquent

laravel,eloquent
I am calling URL with search params which are dynamic. How could I form proper Eloquent query? In theory: query query where(someParam1) query where(someParam2) query orderby(someParam3) query get I need this kind of structure so I can use where clause if param exists. If there is some other way in...

Eloquent Query always returns null for parent table using oneToOne relationship

php,laravel,eloquent,laravel-5,one-to-one
Parent Table users schema | 'id','email','pass' Relationship public function profile() { return $this->hasOne('App\Profile','user_id'); } Other Table profiles schema | 'id','user_id'/*foreign key to users table */ ,'address','city' Relationship public function user() { return $this->belongsTo('App\User','id'); } I'm querying Profile model and would like it to eagerload with User model. public function edit($id){...

Laravel belongsTo throwing undefined function App/BelongsTo() exception

php,sql,laravel,eloquent,belongs-to
I have a comments table and user table with the relationship: user->hasMany('comments') and comment->belongsTo('user'). For some reason with which eludes me, I keep getting this FatalErrorException in Comment.php line 22: Call to undefined function App\belongsTo() My other models have no issue whatsoever with the HasMany relations, however, the comments model...

Laravel5 get all result after 1000 row

mysql,laravel,eloquent
i am migrating Database in which i migration first 1000 rows but problem is that i need all the data after id = 1000 i am not getting the exact result. Please see my query Tried 1 $count = oldo::count(); $skip = 1000; $limit = $count - $skip; // the...

Include model relationships in json response using Eloquent and Laravel 5

php,laravel,eloquent,laravel-5
I have a Model setup as so: <?php namespace App\Models; use Illuminate\Database\Eloquent\Model; class Upload extends Model { /** * The database table used by the model. * * @var string */ protected $table = 'uploads'; /** * The attributes excluded from the model's JSON form. * * @var array */...

Populate form with Auth::user()

php,database,forms,eloquent,laravel-5
I'm trying to populate a form with my logged in user so I can edit some profile information. I currently have this code (only trying to display the email first, will populate the form later once this works): I made an editprofile.blade.php template with: @extends('masterpage') @section('content') <h1> Edit Profile </h1>...

Laravel 5: Get users between a range of age from date field

php,eloquent,laravel-5
I'm having a problem selecting the users between a range of age when the date of birth field in the database is a type date like 1989-09-20. Query DB::raw("*, ( 3959 * acos( cos(radians(?)) * cos(radians(latitude)) * cos(radians(longitude) - radians(?)) + sin(radians(?)) * sin(radians(latitude))) ) AS distance")) ->having('distance', '<', $distance)...

Sync element to a child on Laravel

php,mysql,laravel,eloquent,laravel-5
My Shema database is User Table id login parent Sign Table id name user_id (Sign owner) Pivot table user_sign id user_id sign_id My User model contain public function signs() { return $this->belongsToMany('App\Sign', 'user_sign'); } public function parent(){ return $this->belongsTo('User', 'parent'); } public function children(){ return $this->hasMany('User', 'parent', 'user_id'); } And...

Correct way to run a select query from blades in laravel 5 using eloquent

php,mysql,laravel,eloquent,laravel-5
What is the Correct Way to retrieve a column value based on certain select filter on a Model variable availed by compact method inside the blade. (Larevl 5) I read that Its a bad practice to query database staright from views, and hence i followed the convention to avail the...

Validate an object instead of a value in Laravel

validation,eloquent,laravel-5
In my application I created a POST form which contains an ID of an Object. When I post the form, I want to validate the object for a set of rules, like the age and model relationships of the object. I Created a custom ValidationTrait. Instead of putting values in...

Creating illuminate/html selecter with Eloquent Models

laravel,eloquent
I am trying to make a selector with Laravel illuminate/html and an eloquent models. I need to make it so the option value is id and the text displayed is the name. How can I do this? Thanks!...

Cannot Access Lavavel Collection Properties In Loop

php,laravel,eloquent,laravel-5
I am trying to access a collection and create a new object using part of the results. I keep getting this Undefined offset: 0 and I can't seem to get around it. Here is my foreach loop in my controller; foreach($payments as $payment_key => $payment_value) { //payment_value['Vendor ZIP'] will be...

Laravel orderBy on with

php,laravel,laravel-4,eloquent,laravel-5
I have problem with eloquent query. I am using one to Many Relationship to get 'MenuItems' With the 'Menu'. I want to get all menuItems of a particular menu in sorted by 'sort_order' field Using the code below: Menu::where('slug', 'main-navigation')->with('MenuItems')->orderBy('MenuItems.sort_order', 'asc')->get(); It is not working, is it possible to do...