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,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....
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...
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); ...
laravel,laravel-4,eloquent,laravel-5
You should use whereHas $groups = Group::whereHas('keyword', function($query) { $query->where('user_id' => Auth::user()->id); })->get(); ...
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...
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...
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...
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...
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!
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...
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...
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...
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...
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...
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(); ...
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...
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.
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...
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; ...
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...
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',...
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...
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...
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...
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...
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...
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...
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...
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...
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...
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()...
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(); ...
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']; /** *...
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(); ...
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....
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,...
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');...
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)) ...
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() ...
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...
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...
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; ...
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...
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...
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...
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...
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)...
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...
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[]...
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...
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 *...
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(); ...
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....
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...
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...
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(); ...
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'...
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]); ...
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...
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); ...
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'))); ...
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);...
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...
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)); }...
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...
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(); ...
database,laravel,view,eloquent
You could create the behaviour you are looking for with the following: Geo_Postal_us::where('postal', $postal)->firstOrFail(); ...
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(); ...
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...
You need to specify the desired column name in both of the relation methods. public function createdTickets() { return $this->hasMany('App\Ticket', 'author_id'); } ...
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...
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...
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);...
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...
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; ...
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'))); ...
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...
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...
for multiple where statements use: $result = Model::whereRaw('(a = ? and b=?) or (c=? and d=?)', ['x','y','z','j'])->get(); ...
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)...
http://laravel.com/api/4.1/Illuminate/Database/Eloquent/Collection.html#method_sortBy $collection->sortBy('field', [], true);//true for descending...
Use the unguarded method: $model = Model::unguarded(function() { return Model::firstOrCreate($attributes); }); ...
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...
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...
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...
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...
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...
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); ...
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...
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(); ...
Use the Query first() method rather than the get() method
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(); // ... } ...
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(); ...
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...