Laravel Check If Related Model Exists

In php 7.2+ you can’t use count on the relation object, so there’s no one-fits-all method for all relations. Use query method instead as @tremby provided below: $model->relation()->exists() generic solution working on all the relation types (pre php 7.2): if (count($model->relation)) { // exists } This will work for every relation since dynamic properties return … Read more

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

It is really easy to do a bulk insert in Laravel using Eloquent or the query builder. You can use the following approach. $data = [ [‘user_id’=>’Coder 1’, ‘subject_id’=> 4096], [‘user_id’=>’Coder 2’, ‘subject_id’=> 2048], //… ]; Model::insert($data); // Eloquent approach DB::table(‘table’)->insert($data); // Query Builder approach In your case you already have the data within the … Read more

How to select from subquery using Laravel Query Builder?

In addition to @delmadord’s answer and your comments: Currently there is no method to create subquery in FROM clause, so you need to manually use raw statement, then, if necessary, you will merge all the bindings: $sub = Abc::where(..)->groupBy(..); // Eloquent Builder instance $count = DB::table( DB::raw(“({$sub->toSql()}) as sub”) ) ->mergeBindings($sub->getQuery()) // you need to … Read more

Migration: Cannot add foreign key constraint

Add it in two steps, and it’s good to make it unsigned too: public function up() { Schema::create(‘priorities’, function($table) { $table->increments(‘id’, true); $table->integer(‘user_id’)->unsigned(); $table->string(‘priority_name’); $table->smallInteger(‘rank’); $table->text(‘class’); $table->timestamps(‘timecreated’); }); Schema::table(‘priorities’, function($table) { $table->foreign(‘user_id’)->references(‘id’)->on(‘users’); }); }

Laravel – Eloquent “Has”, “With”, “WhereHas” – What do they mean?

With with() is for eager loading. That basically means, along the main model, Laravel will preload the relationship(s) you specify. This is especially helpful if you have a collection of models and you want to load a relation for all of them. Because with eager loading you run only one additional DB query instead of … Read more