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

Set port for php artisan.php serve

Laravel 5.8 to 8.0 and above Simply pass it as a paramter: php artisan serve –port=8080 You may also bind to a specific host by: php artisan serve –host=0.0.0.0 –port=8080 Or (for Laravel 6+) you can provide defaults by setting SERVER_PORT and SERVER_HOST in your .env file. You might need to do php artisan cache: … Read more

What are the Differences Between “php artisan dump-autoload” and “composer dump-autoload”?

Laravel’s Autoload is a bit different: It will in fact use Composer for some stuff It will call Composer with the optimize flag It will ‘recompile‘ loads of files creating the huge bootstrap/compiled.php And also will find all of your Workbench packages and composer dump-autoload them, one by one.

Laravel redirect back to original destination after login

For Laravel 5.3 and above Check Scott’s answer below. For Laravel 5 up to 5.2 Simply put, On auth middleware: // redirect the user to “/login” // and stores the url being accessed on session if (Auth::guest()) { return redirect()->guest(‘login’); } return $next($request); On login action: // redirect the user back to the intended page … Read more