Menu
  • HOME
  • TAGS

Adding to a collection?

laravel,laravel-4,eloquent,laravel-5

Just lunch method on existing object: $data->splice(5, 0, [$firstProduct]); (don't rewrite the object itself) Additionaly, use brackets on added element: [$firstProduct] to prevent casting this element to an array and adding all its fields to collections instead of whole object....

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

laravel-4,eloquent,pivot-table

Assuming the car_image consists of the images of the cars: In your Car model: public function images() { return $this->hasMany('CarImage'); } In your CarImage model: public function car() { return $this->belongsTo('Car'); } Now you can load the cars without images like so: return Car::doesntHave('images')->get(); Using: doesntHave....

Correct form to get last uer id in laravel5

php,orm,user,eloquent

Then just add 1 to your variable you got as the last inserted id $model = new User(); $model->save(); $insert_id = $model->id; #This is the last inserted id After this, just add 1 to the variable $insert_id $next_id = $insert_id + 1; If you want to fetch the last two...

Updating a pivot table

laravel,laravel-4,eloquent,laravel-5

You can add a boolean to your sync method which just adds the value and doesn't remove the existing value. The code looks like this. The first value can be an int or array. Product::find(1)->user()->sync([1], false); ...

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

laravel,laravel-4,eloquent,laravel-5

You should use whereHas $groups = Group::whereHas('keyword', function($query) { $query->where('user_id' => Auth::user()->id); })->get(); ...

Validate an object instead of a value in Laravel

validation,eloquent,laravel-5

In Laravel 5 you can create Custom Validation Rules. So you can define custom validation rule, let say ValidObject and assign it to your form request validation rules: $rules = [ ..... 'paritipant_id' => 'required|ValidObject', ]; To create a custom validation rule for ValidObject you can put this code in...

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

php,laravel,eloquent,laravel-5

Here is example for adding custom attributes to your model. $appends array will add those. While querying your table using eloquent, .. respective getters will be called to set the vales. In the following code snippet 'parent_name' and 'parent_img_url' are custom attributes and getParentNameAttribute and getParentNameAttribute are getters. One can...

Laravel update multiple rows using checkboxes

laravel,checkbox,eloquent

So the problem with unchecking boxes and records not updating is that if a checkbox is unchecked it doesn't get submitted as a value. One way to garner which have been unchecked is compare the original data set with the checkboxes submitted, compare them to the stored values and update...

Get primary key of Eloquent model instance

php,mysql,laravel,orm,eloquent

You should have define a protected field in your model telling Eloquent what the primary key column is: protected $primaryKey = 'guid'; Then you can access that property in your model The model's getKey() method should give you value of the primary key, while getKeyName() should tell you what column...

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

Thanks to dondraper_ in the Larachat slack channel, i figured out that when I recently updated the column name from user_id to sender_id I forgot to change the $fillable value. Once $fillable was updated to 'sender_id' it all worked!

orWhere giving unexpected result

laravel,laravel-4,eloquent,laravel-5

It is because you build your query to return all records that have this lang_id and title, OR description starting with some search keyword. And that's why you get another results, because some of them don't meet the lang_id requirement, but they meet the description match. You need to group...

where method not working properly on laravel?

laravel,eloquent,laravel-5,where-clause,php-carbon

You're calling the where() method on an Eloquent Collection, not the relationship query. The where() method on a Collection works differently than the where() method on a query. For the Collection, the second argument is the value to compare, and the function can only do an equals comparison. The third...

Laravel 5 - __callStatic function is working correctly?

php,laravel,eloquent,laravel-5

The getTable method requires an instance of the model object to work. The method itself look like this: public function getTable() { if (isset($this->table)) return $this->table; return str_replace('\\', '', snake_case(str_plural(class_basename($this)))); } And as you can see it uses $this to access the property, which means in needs context given by...

Laravel getting results from model belongsToMany relationship back to controller

php,laravel,eloquent,laravel-5

Use Collection::lists() $locations = Set::find(1)->photos->lists('photo_location'); It will return an array ['C:\kittens.jpg', 'C:\puppies.jpg'] http://laravel.com/api/4.2/Illuminate/Database/Eloquent/Collection.html#method_lists...

Unable to insert everything in database using laravel

php,laravel,eloquent,laravel-5

You have to make sure that the fields are in the $fillable = []; parameter of your model. Mass Assignment When creating a new model, you pass an array of attributes to the model constructor. These attributes are then assigned to the model via mass-assignment. This is convenient; however, can...

Laravel 5 Eloquent Condition (IN)

eloquent,laravel-5

You should use whereIn method and use the get method at the end to actually fetch the objects from DB, like this: $locations = App\Location::whereIn('sector_id', [1,2,3])->get(); ...

Laravel get posts with multiple tags

php,sql-server,laravel,eloquent

It would be a good idea to use whereHas() on the Post model to eager load the tags and get only the Posts which have at least one of those tags. $posts = Post::whereHas('tags', function($q) use ($tags) { $q->whereIn('id', $tags); })->get(); Here, $tags would just be an array of tag...

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

eloquent,laravel-5,relationship

Seems like clients have many services and services have many clients. Many to many relation looks good here. The appointments table would be the pivot table with any extra info if needed.

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

laravel,eloquent,relationship

From the Laravel documentation: take(int $value) Alias to set the "limit" value of the query. So basically what you do is constructing a query with Query Builder and you are literally saying: Select count of all tags, where tag_slug is $tagSlug and return the first row It is equal to...

Access a protected field from queried Eloquent object

php,laravel,laravel-4,eloquent

Turns out, if I use auto-incrementing IDs, I can access the id attribute of the newly created model, right after it has been created in the DB. So, this is the whole fix: $trip->save(); $trip_redirect_id = $trip->id; ...

Laravel - Sorted collection output is not an array

php,mysql,sorting,laravel,eloquent

When you sort by locationId, the keys for the items don't change, since the items were sorted that way already. For example, the keys would stay 0, 1, 2, etc., which is a valid indexed array. However, when you sort by the name field, the keys will move around with...

How to skip a row with file exists condition in laravel

laravel,search,eloquent

Option 1: would be to make an array of the filenames, then utilize the whereIn query builder method, which checks for the occurrence of a column value in an array. $query = Model::query(); $filenames = scandir('/img'); // the following excludes any id's not in the $filenames array $query = $query->whereIn('id',...

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

php,laravel,eloquent

When you use with, laravel knows to pre-fetch the associated members for the gigs as well, in two queries instead of several more. This is known as Eager Loading. So, the query sounds something like, "Get all gigs for the database." "Get the members for all of these gigs." All...

Laravel5 get all result after 1000 row

mysql,laravel,eloquent

You probably want to do the following: <?php $oldOrder = oldo::where('Std_ID', '>', 1000)->paginate(500); This way you select all orders where the ID is more than 1000...

Custom accessors Eloquent Model

arrays,laravel,model,eloquent

get() actually returns a Collection object which contains 0, 1, or many models which you can iterate through so it's no wonder why adding these functions to your model are not working. What you will need to do to get this working is to create your custom Collection class, override...

Creating illuminate/html selecter with Eloquent Models

laravel,eloquent

Use FormBuilder Form::select() and format your collection to assoc array using ->lists(): PHP: $models = DB::table('table_name')->lists('name', 'id'); Blade: {!! Form::select('name', $models) !!} See lists()doc here...

Laravel eloquent returns same row with different where clause

laravel,eloquent

There is an excellent discussion of the issue at MySQL matching unicode characters with ascii version. In order to get this to work as you expect, you need to change the collation from utf8_unicode_ci to utf8_bin. However, you need to keep in mind that there are three collation settings: one...

Self Join in Eloquent - How To Call

laravel,laravel-4,eloquent,laravel-5

I believe your relations are not the way they're supposed to be. Usually it's one column (foreign key - color_id in your case) having a value of the other one (usually primary key - id in your case). What you have is basically a value the records share or a...

how to make a update page with hasMany relatioins in laravel

php,laravel,eloquent

The + sign in PHP is not used for concatenation of strings. It is math operator. To concatenate strings you should use dot (.). So change your code like this: Form::text('a' . $key, $value->arg1) Form::text('b' . $key, $value->arg2) Because previously you were calculating the sum of a and $key, thats...

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

php,laravel,eloquent,laravel-5,laravel-middleware

Whenever you do it automatically or manually some like this if (Auth::attempt(['email' => $email, 'password' => $password])) { } The selected User's Data will be stored in the storage/framework/sessions It will have data something like a:4:{s:6:"_token";s:40:"PEKGoLhoXMl1rUDNNq2besE1iSTtSKylFFIhuoZu";s:9:"_previous";a:1:{s:3:"url";s:43:"http://localhost/Learnings/laravel5/laravel";}s:9:"_sf2_meta";a:3:{s:1:"u";i:1432617607;s:1:"c";i:1432617607;s:1:"l";s:1:"0";}s:5:"flash";a:2:{s:3:"old";a:0:{}s:3:"new";a:0:{}}} The above...

How to sum groupBy in Laravel5

php,laravel,eloquent

i think you must use the drilldown approach and use the sum function of the query builder. $pujas = Bid::take(10)->usuarios()->subasta()->groupBy('id_user')->orderBy('created_at','desc')->get(); and for sum values you can create a service or loop over the users and sum the "imports" or add a new accessor in you model (in order to add...

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

php,mysql,laravel,eloquent

First you need to create proper relations for your eloquent models, like this: City.php class City extends Model { public function payments() { return $this->hasMany('App\Payment'); } } PaymentType.php class PaymentType extends Model { public function payments() { return $this->hasMany('App\Payment'); } } Payment.php class Payment extends Model { public function city()...

Querying one-to-one in laravel

php,laravel-4,orm,eloquent

Hi You can fetch this by this ways : Find Top 10 cities which have the maximum business: $city = City::with('business')->get()->sortBy(function($query) { return $query->business->count(); }, SORT_REGULAR, true) ->take(10); Find Business by city name. Business::whereHas('city', function ($q) { $q->where('name', 'like', 'search_string');//name is the city_name as per your attributes name })->get(); ...

Laravel: Retrieve polymorphic attributes efficiently

rest,laravel,polymorphism,eloquent

You might be almost there. Your getAvatarAttribute() is way too complicated, indeed. You could try to do something like: /** we hide the relation from the json */ protected $hidden = ['avatar']; /** we append the url of the avatar to the json */ protected $appends = ['avatar_url']; /** *...

Laravel. Eloquent query for two tables

php,mysql,sql,laravel,eloquent

Use a join to to identify titles that do not appear in title_count. DB::table('titles')->leftJoin('title_count', 'titles.title_id', '=', 'title_count.title_id') ->select('titles.*') ->whereNull('title_count.title_id') ->get(); ...

Merging collections

laravel,eloquent,laravel-5

Now, when using Product:: you'll get with an Eloquent Collection object which holds your results from using get or any other relationship. The nice thing here is that you can actually choose and customize your Collection, instead of using plain array or something else. Please read additional details here: http://laravel.com/docs/5.1/eloquent-collections#available-methods....

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

laravel,eloquent

For the least amount of database work, you want to create the user first and then create the computer. This way, you can have one save for the user, and then one save for the computer, which is only two writes to the database. If you create the computer first,...

Sync element to a child on Laravel

php,mysql,laravel,eloquent,laravel-5

As far as syncing/attaching you can use this sytanx $user->roles()->sync([1, 2, 3]); As given in Laravel Docs You can do the both checks in the condition of IF and assign in case of true, thats how your controller will look like finally. public function share(Request $request) { $userId = $request->input('user_id');...

Laravel Eloquent where and or between in one query

laravel,eloquent,where

I have changed somethings in your query, please try this : $dtrs=Dtr::Join('emp_informations','dtrs.enrollnum','=','emp_informations.enrolnum') ->where('emp_informations.EmpID','=','07081408') ->whereBetween('dtrs.date_in', array('2015-03-05' , '2015-03-20')) ->whereBetween('dtrs.date_out', array('2015-03-05' , '2015-03-20')) ->orderBy('dtrs.date_in','Desc')->paginate(15); if you have variables, you can make like this: ->whereBetween('dtrs.date_in', array($fromdate , $todate)) ...

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

php,mysql,laravel-4,eloquent

Try this. Service::whereHas('tag', function($query) use ($tagId) { $query->where('tag_id', '=', $tagId); })->get(); Edit: Changed the answer. Previous Answer: Business::with(['services')->whereHas('tag', function($query) use ($tagId) { $query->where('tag_id', '=', $tagId); })->get() ...

Eloquent Query always returns null for parent table using oneToOne relationship

php,laravel,eloquent,laravel-5,one-to-one

You receive null for because your relation definition is wrong. Your profile model should be public function user() { return $this->belongsTo('App\User','user_id'); } The error is because you are trying to get the user object from a collection. Since you have used get() to retrieve data you are receiving a collection...

Tinder Laravel matching between 2 models

php,laravel,laravel-4,eloquent,tinder

As I understand your question, in your application, a user can like an employer, and an employer can like a user. If this is right, it seems clear to me that there are two distinct (many to many) relationships (user => employer, employer => user), and that in your proposed...

Laravel eloquent complex queries on relationships2

php,laravel,eloquent

Since you have the portfolio id, you first find the portfolio, then you get the business for that portfolio, and then you get all the portfolios for that business: $portfolio = Portfolio::find($id); $business = $portfolio->business; $portfolios = $business->portfolio; Or, with a one liner: $portfolios = Portfolio::find($id)->business->portfolio; ...

Laravel 5: Convert query builder to eloquent

php,eloquent,laravel-5,query-builder,php-carbon

If all you want is Carbon::diffForHumans, you can just convert (cast) created_at to Carbon. Some of the possible usage: $dt = ( (Carbon) $row->created_at ) // Casting $dt = Carbon::instance($row->created_at) And I would suggest on keeping Fluent queries instead of converting to Eloquent, as Eloquent is really only good for...

Multiple Where In

mysql,laravel,laravel-4,eloquent,laravel-5

This is very interesting question. 0 = 1 will always be false, so your query will return zero rows. But why is this? Because by setting ->whereIn('size', $size) Laravel assumes that you always want the returned rows to be with one of the sizes in the passed array. If you...

Populate form with Auth::user()

php,database,forms,eloquent,laravel-5

I think that you are just outputting the raw data because probably you are using double brackets {{ }}. As i remember i had a same thing when i migrated a site from laravel 4 to laravel 5. They changed the way blade output and echo the data. try to...

Include model relationships in json response using Eloquent and Laravel 5

php,laravel,eloquent,laravel-5

It is not a good idea to name a relationship the same name as one of the fields on the table. This causes issues (as you've found out) when trying to access the relationship versus accessing the field. Ideally, your mime field should be renamed to mime_id. This conforms to...

Caching issue in angularJS application

angularjs,caching,orm,eloquent,slim

Unless you state it, angular will not cache your $http requests, so most likely the values are being cached by your server. There are a couple of things you can do: Pass a header to the server to ignore the cache (assuming your server will react to that header appropriately)...

Id Column Overwritten by Join

php,mysql,laravel,laravel-4,eloquent

I was able to find a possible solution using this answer: Laravel 4 - JOIN - Same column name Basically, since Laravel does not automatically prefix column names with table_name. for joined tables, we need to manually work around it by aliasing any conflicting column names in joins. Adding this...

Laravel multiple whereIn array

laravel,eloquent

No that's not possible. You have to use whereIn() multiple times (or in a loop). There's no logic that would handle such a parameter correctly: public function whereIn($column, $values, $boolean = 'and', $not = false) { $type = $not ? 'NotIn' : 'In'; // ... irrelevant code omitted ... $this->wheres[]...

Cannot Access Lavavel Collection Properties In Loop

php,laravel,eloquent,laravel-5

You need to do it like this: $postcode_coord = PostcodeCoord::where('postcode', '=', $partial_vendor_zip)->first(); print $postcode_coord->lat; $markers[] = (object)[ "postcode" => $postcode_coord->postcode, "payment_name" => $payment_value['Contract Title'], "full_postcode" => $payment_value['Vendor ZIP'], "lat" => $postcode_coord->lat, "lng" => $postcode_coord->lng, ]; Note the use of first() instead of take(1)->get(), since the latter will return a collection...

Laravel (Eloquent) Table || Peer equivalent

php,laravel,doctrine,eloquent,propel

As mentioned earlier, there is more than one way to accomplish the task, but here's a quick example using Commands. Controller namespace App\Http\Controllers; //... use App\Http\Requests\UpdateUserRequest; use App\Commands\UpdateUser; use App\User; //... class UserController extends Controller { /** * Update the specified resource in storage. * * @param int $id *...

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

sql,laravel,eloquent

You have two options. You can use distinct() or groupBy() Variant 1: $check = DB::table('table as u1') ->join('table as u2','u1.book_id', '=', 'u2.book_id') ->where('u2.user_id', 8)->where('u1.user_id', 3) ->distinct() ->get(); Variant 2: $check = DB::table('table as u1') ->join('table as u2','u1.book_id', '=', 'u2.book_id') ->where('u2.user_id', 8)->where('u1.user_id', 3) ->groupBy('u1.book_id') ->get(); ...

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

php,laravel,eloquent,laravel-5,relationship

You are trying to get id from an null profile. Please check one of your results and see that inside relations property you have profile as null Please check first if profile is null and only after that get your field Good luck....

Retreiving a single colum from a pivot table - Laravel 5

php,laravel,eloquent,laravel-5

I think what will help you achieve this behavior is the lists() method. Try something like $user_genres = auth()->user()->genres()->lists('name','id'); If you are using Forms & HTML package you can just do {!! Form::select('genres',$user_genres,null) !!} And here is your dropdown More info here (scroll down to "Retrieving A List Of Column...

Laravel, WebSockets - Verify user on server

php,session,laravel,eloquent,ratchet

So this is how I solved this a while ago. In my example, I'm working with Socket.IO, but I'm pretty sure you can easily rewrite the Socket.IO part to get it to work with RachetPHP as well. Socket Server The socket server depends on the files cookie.js and array.js, and...

Laravel: dynamic where clause with Elouquent

laravel,eloquent

It's easy with Laravel. Just do something like this: $query = User::where('created_at', '>', '2010-01-01'); if (this == that) { $query = $query->where('this', 'that); } if (this == another_thing) { $query = $query->where('this', 'another_thing'); } $results = $query->get(); ...

Binding vars to raw queries

laravel,laravel-4,eloquent,laravel-5

you must bind variables to raw method not select: $select = "(3959 * acos(cos(radians(:lat)) * cos(radians(lat)) * cos(radians(lng) - radians(:lng)) + sin(radians(:lat)) * sin(radians(lat)))) as distance"; $data = $myModel->select( DB::raw($select,array( 'lat' => $lat, 'lng' => $lng, )))->orderBy('distance', 'ASC')->having('distance', '<', $radius) ->get(); Or use selectRaw method directly: $data = $myModel->selectRaw($select,array( 'lat'...

Laravel getting id from stored object

php,mysql,laravel,eloquent

To get id of created object, you should run: $company = $company->create($request->all()); dd($company->id); instead of $company->create($request->all()); dd($company->id); You can now pass id of company when creating Attribute this way: $attribute->create(array_merge($request->only('attribute_nr', 'value'), ['company_id' => $company->id]); ...

Three-way many-to-many relationship in Laravel

laravel,eloquent,laravel-5

I often use another model to abstract a three-way many to many relations. I explain it: We have our relation i gonna call the relation relation so first the db structure: table relations: id, user_id, student_id, plan_id After we have 4 models on our app: User Student Plan Relation so...

DISTINCT method using Laravel 5 eloquent query builder

php,mysql,eloquent,laravel-5

Try to use group by id $users = DB::table('users')->distinct() ->join('projects', 'users.id', '=', 'projects.userID') ->where('projects.sectorID', '=', $sector->sectorID) ->groupBy('users.id') ->get(); dd($users); ...

Laravel 5: Access attribute from other Model

php,eloquent,laravel-5

I found the solution but was not necessary to access to the attribute from other model, just use this whereBetween. $q->whereBetween(DB::raw('TIMESTAMPDIFF(YEAR,users.date_of_birth,CURDATE())'),array(Input::get('age_from'),Input::get('age_to'))); ...

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

php,mysql,laravel,eloquent

This is how you can do filter in Laravel Eloquent using Query Scope. In Model class Lead extends Model { public function scopeCallDateFrom($query, $date) { if ($date) { return $query->where("call_date", ">=", $date); } else{ return $query; } } public function scopeCallDateTill($query, $date) { if ($date) { return $query->where("call_date", "<=", $date);...

Relationship results automatically coming out?

laravel,laravel-4,eloquent,laravel-5

Relationship results automatically coming out? No, basically when you do $data = Product::all(); foreach ($data as $value) { var_dump($value->title); } You are doing this: select * from products But then on your foreach, since you are trying to access a property that wasn't loaded, you are doing a new...

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

php,laravel,eloquent,laravel-5,accessor

FormBuilder use object_get() helper function for get value from model: /** * Get the model value that should be assigned to the field. * * @param string $name * @return string */ protected function getModelValueAttribute($name) { if (is_object($this->model)) { return object_get($this->model, $this->transformKey($name)); } elseif (is_array($this->model)) { return array_get($this->model, $this->transformKey($name)); }...

Laravel belongsTo throwing undefined function App/BelongsTo() exception

php,sql,laravel,eloquent,belongs-to

Well, this error occurred because I had '.' in place of '->'. I couldn't figure out why it was always throwing the exact same error regardless if I did $this.belongsTo('App\User'); or $this.hasMany('App\User'); or even $this.thecakeisalie('App\User'); until I sat staring at the text between my many models yet again. Then, lo...

Larevel/SQL: Query model where relationship = X

php,sql,laravel-4,eloquent

So after struggling with a complicated SQL query, I landed up using a model accessor to achieve my goal: On the listing model public function bedroomCount() { return $this->rooms() ->selectRaw('listing_id, count(*) as count') ->where('room_type_id', '=', '1') ->groupBy('listing_id'); } And the query $listings = Listing:: has('bedroomCount', '>=', $x) ->get(); ...

findOrFail laravel 5 function for specific filed

database,laravel,view,eloquent

You could create the behaviour you are looking for with the following: Geo_Postal_us::where('postal', $postal)->firstOrFail(); ...

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

php,mysql,eloquent,laravel-5

This might be a solution: use Illuminate\Database\Eloquent\Model; class Division extends Model { public function scopeFromView($query) { return $query->from('divisions_view'); } } Just call the fromView() method in any part of the query like this: Division::fromView()->get(); ...

Laravel orderBy on with

php,laravel,laravel-4,eloquent,laravel-5

try this Menu::where('slug', 'main-navigation')->with([ 'MenuItems' => function($query) { $query->orderBy('MenuItems.sort_order', 'asc') } ])->get(); This will sort all the menu-items under each menu as per sort_order....

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

php,laravel,eloquent

You should use sql joins. Based on the functions you are using laravel. You have model LibraryOne and LibraryTwo. Assuming the actual table name for LibraryOne is libraryOne and LibraryTwo is libraryTwo, your code should look like this: DB::table('libraryOne')->where('libraryOne.user_id', Auth::id())->join('libraryTwo', function($join) { $join->on('libraryOne.book_id', '=', 'libraryTwo.item_id')->where('libraryTwo.user_id', Auth::id()); }) ->get(); This would...

Eloquent looks for wrong column

php,laravel,eloquent

You need to specify the desired column name in both of the relation methods. public function createdTickets() { return $this->hasMany('App\Ticket', 'author_id'); } ...

retrieving multiple records associated to multiple records laravel 4.2

php,laravel,laravel-4,eloquent,blade

You should use Eloquent's relationships to solve this problem. See more here: http://laravel.com/docs/4.2/eloquent#relationships The way I see it currently is that you have three models that you're working with: Quiz, Question and Answer - right? From your question I gather the following: A Quiz will have many Questions An Answer...

Creating an Eloquent Object with relation included

php,laravel,eloquent,laravel-5,foreign-key-relationship

You may try something like the following. At first save the parent model like this: $user = new \App\User; $user->first_name = $request->input('first_name'); // ... $user->save(); Then create and save the related model using something like this: $profile = new \App\Profile(['mobile_no' => $request->input('mobile')]); $user->profile()->save($profile); Also make sure you have created the...

Laravel Eloquent: access method parameter within chunk Closure

php,laravel,static,scope,eloquent

The use keyword allow the anonymous function to inherit variables from the parent scope. class MyModel extends Eloquent { // ... table stuff public static function doSomething (Closure $thing) { $dispatcher = static::getEventDispatcher(); static::unsetEventDispatcher(); // note the use keyword static::chunk(100, function ($records) use ($thing) { foreach($records as $model) { $thing($model);...

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

mysql,laravel,laravel-4,eloquent

Have a look at the Forms & HTML helper of laravel. Generating A Drop-Down List With Selected Default echo Form::select('size', array('L' => 'Large', 'S' => 'Small'), 'S'); where the first argument is the name of the select box. The second argument is an array of all entries in the box...

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

php,mysql,laravel,eloquent,laravel-5

In User model public function group() { return $this->belongsTo('App\Group'); } In Group model public function users() { return $this->hasMany('App\User'); } In your controller $users = \App\User::with('group')->get(); return view('user.index', compact('users')); Now in your view you can do $user->group->name; ...

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

php,eloquent,laravel-5

I found the solution and is touse this wheteBetween. $q->whereBetween(DB::raw('TIMESTAMPDIFF(YEAR,users.date_of_birth,CURDATE())'),array(Input::get('age_from'),Input::get('age_to'))); ...

Laravel 5 No query results for model redirect page

laravel,view,eloquent

Suggestion 1 $postal = $request->input('postal'); $get_all= Geo_Postal_us::where('postal', $postal)->first(); if($get_all) { $count=count($get_all); return view('test.show',compact('get_all','count')); } return Redirect::back()->with('message','No results found'); This will check if get_all is found and if is found will return test.show view else will redirect to previous view with message No results found . If you want to declare...

Is Eloquent sortBy stable in Laravel 5?

php,eloquent,laravel-5

The source code can be found in Illuminate/Support/Collection.php: public function sortBy($callback, $options = SORT_REGULAR, $descending = false) { $results = []; if ( ! $this->useAsCallable($callback)) { $callback = $this->valueRetriever($callback); } // First we will loop through the items and get the comparator from a callback // function which we were...

Laravel 4 eloquent WHERE with AND and OR?

laravel-4,eloquent

for multiple where statements use: $result = Model::whereRaw('(a = ? and b=?) or (c=? and d=?)', ['x','y','z','j'])->get(); ...

Advanced nested AND clause in Laravel 5 Eloquent

laravel,eloquent,laravel-5

You should use "advanced where". Instead of a column name you feed the where with a function. For more clarity look it up here http://laravel.com/docs/5.0/queries#advanced-wheres. Your code should look like the one below: $relatedArticles = Article::where('id', '<>', $article->id); if (!is_null($article->tags)) { $relatedArticles->where(function($query) use ($article) { foreach (explode(',', $article->tags) as $tag)...

Eloquent sortBy - Specify asc or desc

php,arrays,laravel-4,eloquent

http://laravel.com/api/4.1/Illuminate/Database/Eloquent/Collection.html#method_sortBy $collection->sortBy('field', [], true);//true for descending...

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

php,laravel,eloquent

Use the unguarded method: $model = Model::unguarded(function() { return Model::firstOrCreate($attributes); }); ...

I can't use some Eloquent methods

laravel-4,eloquent,cartalyst-sentry

While I was waiting for an answer ;), I still having problems with Eloquent methods. I cant use something as $user->books()->get() or ->attach() in a relation many to many users and books, also with User::with('books') I have the same problem Call to undefined method Illuminate\Database\Query\Builder::xxxx() My problem is becouse of...

save one to one relationship. foreign keys in both tables

laravel,eloquent,foreign-key-relationship,one-to-one

First your users table does not need a pet_id. Drop it. Then Users Model public function pet() { return $this->hasOne('App\Pet'); // Changed form hasMany to hasOne } Pet Model public function user() { return $this->belongsTo('App\User'); } Now create a new User $user = \App\User::create($data); // You need to set $fillable...

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

mysql,laravel,eloquent

Just chain the where method anywhere before get, since your condition will be applied on the notifications table: Notification::select('notification_types.*', DB::raw('count(*) as total')) ->join('notification_types', 'notifications.type_id', '=', 'notification_types.id') ->where('reciever_id', $receiverId) ->groupBy('type_id') ->get(); Also, there's no need with this query to group by notifications.type_id, type_id will do, because there are no ambiguities created...

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

Do you have good reason to believe that scandir on a directory with a large number of folders will actually slow you down? You can do your query like this: if(Input::has('field')){ $filenames = scandir('img/folders'); $query = Model::whereIn('id', $filenames)->get(); } Edit 1 You may find these links useful: PHP: scandir() is...

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

php,mysql,database,laravel,eloquent

If you are using WAMP, your webserver and command line are using different php configurations. Be sure to enable the pdo_mysql extension in both config files or using the WAMP options....

Laravel query. Where unique

php,sql,laravel,eloquent

How about: $jobs = DB::table('my_job_table') ->groupBy('job_id') ->get(); Eloquent: First, you need a model. You could generate this by using php artisan. php artisan make:model jobs (I assume you have done this already) This will create a model in /your_project/app/Job.php Now you can use Eloquent (here in a route, to see...

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

php,postgresql,laravel,eloquent,laravel-5

Based on this answer, I used raw queries using DB::select() as following: $sql = "SELECT * FROM ( SELECT ROW_NUMBER() OVER (PARTITION BY category_id ORDER BY date DESC) AS r, t.* FROM posts t) x full outer join categories t2 on x.category_id = t2.id WHERE x.r <= 5"; DB::select($sql); ...

SubQueries in Laravel 4.2

mysql,laravel-4,eloquent

If you have two tables...I have one solution for your question.. you dont need use joins for this. Table1 name 'truckgps' and table 2 name 'truckgpss' My Ans $truckgps = DB::table('truckgps')->select('Truck_Number','Created','Latitude','Longitude','Speed','Heading ')->get(); foreach ($truckgps as $t) { $result = DB::table('truckgpss')->select('MAX(Created_dt) AS MaxDate ','Truck_Number')->where('MaxDate','=',$t->Created_dt )->where('Truck_Number','=',$t->Truck_Number)->groupBy('Truck_Number') ->get(); // if u need...

Facing issue while reusing mongo connection

php,mongodb,eloquent

After calling first() the limit is being set to 1 which is why get returns one record. Following code works:- $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->newQuery()->from('employees')->get(); ...

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

php,json,eloquent,laravel-5

Use the Query first() method rather than the get() method

Retrieving the Slug from URL for function (Laravel 5)

php,eloquent,laravel-5,blade,slug

Fixed it: Route: $router->post('invites/{slug}', ['as' => 'invite.create', 'uses' => '[email protected]']); My form: {!! Form::open(['route' => ['invite.create', $group->slug]]) !!} {!! Form::submit('Generate invite code', ['class' => 'btn btn-primary']) !!} {!! Form::close() !!} The function: public function createInviteCode($slug) { $group = Group::where('slug', $slug)->firstOrFail(); // ... } ...

Laravel 5 Eloquent where and or in Clauses

sql,laravel,eloquent

Using advanced wheres: CabRes::where('m__Id', 46) ->where('t_Id', 2) ->where(function($q) { $q->where('Cab', 2) ->orWhere('Cab', 4); }) ->get(); Or, even better, using whereIn(): CabRes::where('m__Id', 46) ->where('t_Id', 2) ->whereIn('Cab', $cabIds) ->get(); ...

Laravel Eloquent how to return one to many to many collection

php,eloquent,laravel-5

The "has many through" relation provides a convenient short-cut for accessing distant relations via an intermediate relation. class User extends Model implements AuthenticatableContract, CanResetPasswordContract {{ ... public function galleries() { return $this->hasMany('App\Gallery'); } public function votes() { return $this->hasManyThrough('App\GalleryVote', 'App\Gallery'); } } Now $user->votes will return all votes for that...