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 alias a table in Laravel Eloquent queries (or using Query Builder)?

Laravel supports aliases on tables and columns with AS. Try $users = DB::table(‘really_long_table_name AS t’) ->select(‘t.id AS uid’) ->get(); Let’s see it in action with an awesome tinker tool $ php artisan tinker [1] > Schema::create(‘really_long_table_name’, function($table) {$table->increments(‘id’);}); // NULL [2] > DB::table(‘really_long_table_name’)->insert([‘id’ => null]); // true [3] > DB::table(‘really_long_table_name AS t’)->select(‘t.id AS uid’)->get(); // … Read more

Get the Query Executed in Laravel 3/4

Laravel 4+ Note for Laravel 5 users: You’ll need to call DB::enableQueryLog() before executing the query. Either just above the line that runs the query or inside a middleware. In Laravel 4 and later, you have to call DB::getQueryLog() to get all ran queries. $queries = DB::getQueryLog(); $last_query = end($queries); Or you can download a … 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

Automatically deleting related rows in Laravel (Eloquent ORM)

I believe this is a perfect use-case for Eloquent events (http://laravel.com/docs/eloquent#model-events). You can use the “deleting” event to do the cleanup: class User extends Eloquent { public function photos() { return $this->has_many(‘Photo’); } // this is a recommended way to declare event handlers public static function boot() { parent::boot(); static::deleting(function($user) { // before delete() method … Read more

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)