Laravel - serve with custom port without --port option

Is there any way to serve a laravel application in a custom port without using --port or any web servers like nginx, apache, ... ? maybe we can change source codes. is it possible ?


Solution 1

You can go to this file:

vendor/laravel/framework/src/Illuminate/Foundation/Console/ServeCommand.php

and change the default port at the line 87.

87     ['port', null, InputOption::VALUE_OPTIONAL, 'The port to serve the application on.', 8000],

This way will let you use php artisan serve command with that port you set in that file. (Default is 8000).

But remember it is not recommended to change code inside vendor folder.


Solution 2

you could make an alias with wanted port, something like:

paserve=php artisan serve --port=8080

and then when you call paserve you get the app served on that port


The right answer is great! But I made a different solution that worked very well for me on Laravel 8

First of all, create a new command using:

php artisan make:command RunServer or any name you want

Then I copied the content inside vendor/laravel/framework/src/Illuminate/Foundation/Console/ServeCommand.php class to my RunServer class

(Remember to change the protected $name, i used 'run' instead of serve)

And all I have done was add a new .env variable Eg.: APP_DEFAULT_PORT

Add a new variable on config/app.php => 'default_port' => env('APP_DEFAULT_PORT'),

and call this variable inside my RunServer class changing this line

$port = $port ?: 8000;

to

$port = config('app.default_port');