Reputation: 5551
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 ?
Upvotes: 0
Views: 3281
Reputation: 981
php artisan make:command RunServer
RunServer
class should be extened from original ServeCommand
.
Rename the command, in my case it 'run' in protected $name
Add getEnvPort()
method, see below. It extract port from APP_URL if it is specified.
Override protected port()
method (copy all code of them). It has changes only on this line $port = $port ?: $this->getEnvPort();
In the .env
set:
APP_URL=http://localhost:9090
Then
php artisan run
yarn dev
(it also get port from APP_URL)
Enjoy it!
class RunServer extends ServeCommand
{
protected $name = 'run';
/**
* @return int|mixed|string
*/
protected function port()
{
$port = $this->input->getOption('port');
if (is_null($port)) {
[, $port] = $this->getHostAndPort();
}
$port = $port ?: $this->getEnvPort();;
return $port + $this->portOffset;
}
protected function getEnvPort(): ? int
{
return parse_url(config('app.url'), PHP_URL_PORT) ?: 8000;
}
}
Upvotes: 1
Reputation: 11
Well, speaking about setting up a default port to listen to it's not necessary to create a custom command but just to set SERVER_PORT=<a free port number> in .env file.
Since v5.8 up to now ServeCommand getOptions() function is taking care about the SERVER_PORT environment variable and that is the easiest solution for such a case:
Best, K.
Upvotes: 1
Reputation: 76
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');
Upvotes: 3
Reputation: 15047
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.
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
Upvotes: 4