Laravel
Find the official Laravel docs here.
Installation
If not already installed, install PHP. This is for Fedora 36 with PHP-FPM for NGINX:
sudo dnf upgrade --refresh -y
sudo dnf install http://rpms.remirepo.net/fedora/remi-release-36.rpm -y
sudo dnf module enable php:remi-8.1 -y
sudo dnf install php php-fpm php-cli php-fpm php-curl php-mysql php-mysqli php-mysqlnd php-gd php-opcache php-zip php-intl php-common php-bcmath php-imagick php-xmlrpc php-json php-readline php-memcached php-mcrypt php-redis php-mbstring php-apcu php-xml php-dom php-redis php-memcached php-memcache php-pear php-tidy -y
Make sure nginx.conf has suitable PHP config and unix socket path points to installed one:
location ~ \.php$ {
try_files $uri =404;
fastcgi_pass unix:/run/php-fpm/www.sock;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
Or use dockerized environment instead, this one contains PHP+NGINX+MariaDB:
git clone https://git.zcyph.cc/zcyph/nginx-php-mariadb.git
Install Composer:
php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');"
php -r "if (hash_file('sha384', 'composer-setup.php') === '55ce33d7678c5a611085589f1f3ddf8b3c52d662cd01d4ba75c0ee0459970c2200a51f492d557530c71c15d8dba01eae') { echo 'Installer verified'; } else { echo 'Installer corrupt'; unlink('composer-setup.php'); } echo PHP_EOL;"
php composer-setup.php
php -r "unlink('composer-setup.php');"
sudo mv composer.phar /usr/local/bin/composer
Install Laravel globally via Composer:
composer global require laravel/installer
New Project
Create new projects like this:
laravel new example-app
Optionally serve up the development environment with:
php artisan serve, or just point webserver to Laravel public dir.
Existing Project
Make sure PHP & extenions, Composer, Laravel, NGINX & MariaDB are installed. Then from Laravel project root dir, run:
composer install
To install project dependencies. Run:
php artisan key:generate
And fill out the database info in .env.
Permissions for ./storage and ./bootstrap/cache may need to be set to 777 for development on Fedora, obviously don't use that in production.
Populate the database with:
php artisan migrate
Events
Events must be registered in /app/Providers/EventServiceProvider.php. For example, here we register an Event of PaymentReceived and a Listener of ActivateAccount:
protected $listen = [
PaymentReceived::class => [
ActivateAccount::class,
],
];
An Event signifies something has happened.
A Listener executes things to be triggered on said Event.
Generate an Event that corresponds to a new payment being received with:
php artisan make:event PaymentReceived
Then edit the newly created /app/Events/PaymentReceived.php and ensure it references the appropriate Model (in this case, App\Models\Payment) and defines a new payment as an Event:
<?php
namespace App\Events;
use App\Models\Payment;
use Illuminate\Broadcasting\Channel;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
class PaymentCreated
{
use Dispatchable, InteractsWithSockets, SerializesModels;
/**
* The payment instance.
*
* @var \App\Models\Payment
*/
public $payment;
/**
* Create a new event instance.
*
* @param \App\Models\Payment $payment
* @return void
*/
public function __construct(Payment $payment)
{
$this->payment = $payment;
}
/**
* Get the channels the event should broadcast on.
*
* @return \Illuminate\Broadcasting\Channel|array
*/
public function broadcastOn()
{
return new PrivateChannel('channel-name');
}
}
Next, generate a corresponding Listener linked to the Event:
php artisan make:listener PaymentWatcher --event=PaymentCreated
Edit the new Listener that was created in /app/Listeners/PaymentWatcher.php and make sure it references the Event and performs the desired tasks:
<?php
namespace App\Listeners;
use App\Events\PaymentCreated;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;
class PaymentWatcher
{
/**
* Create the event listener.
*
* @return void
*/
public function __construct()
{
//
}
/**
* Handle the event.
*
* @param \App\Events\PaymentCreated $event
* @return void
*/
public function handle(PaymentCreated $event)
{
$payment = $event->payment;
dd($payment);
}
}
To register the Event, edit /app/Providers/EventServiceProvider.php, make sure it references both the Event and Listener, and add them to the $listen array:
<?php
namespace App\Providers;
use App\Events\PaymentCreated;
use App\Listeners\PaymentWatcher;
use Illuminate\Auth\Events\Registered;
use Illuminate\Auth\Listeners\SendEmailVerificationNotification;
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;
use Illuminate\Support\Facades\Event;
class EventServiceProvider extends ServiceProvider
{
/**
* The event listener mappings for the application.
*
* @var array<class-string, array<int, class-string>>
*/
protected $listen = [
Registered::class => [
SendEmailVerificationNotification::class,
],
PaymentCreated::class => [
PaymentWatcher::class,
],
];
/**
* Register any events for your application.
*
* @return void
*/
public function boot()
{
//
}
/**
* Determine if events and listeners should be automatically discovered.
*
* @return bool
*/
public function shouldDiscoverEvents()
{
return false;
}
}
Task Scheduler
One option is to use an invokable object. In /app/Console/Kernel.php:
<?php
namespace App\Console;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
use App\SchedulerServices\PaymentChecker;
class Kernel extends ConsoleKernel
{
/**
* Define the application's command schedule.
*
* @param \Illuminate\Console\Scheduling\Schedule $schedule
* @return void
*/
protected function schedule(Schedule $schedule)
{
// $schedule->command('inspire')->hourly();
// $schedule->command('check-for-payments')->everyMinute();
$schedule->call(new PaymentChecker)->everyMinute();
}
/**
* Register the commands for the application.
*
* @return void
*/
protected function commands()
{
$this->load(__DIR__.'/Commands');
require base_path('routes/console.php');
}
}
new PaymentChecker calls the invokable object, which it can do because it's defined at the top:
use App\SchedulerServices\PaymentChecker;.
Next, create file & folder App\SchedulerServices\PaymentChecker.php:
<?php
namespace App\SchedulerServices;
class PaymentChecker
{
public function __invoke()
{
dd('yes');
}
}
Test it with:
php artisan schedule:run
or
php artisan schedule:work
or
php artisan schedule:test
Unfortunately task output appears not to work with callbacks/invokable objects, only commands. To log output, n Kernel.php do:
$schedule->command('accountcheck:endsub')
->daily()
->appendOutputTo('storage/logs/accountchecker.log');
Deployment
Whether using local DNS / local HTTPS in development, or actually deploying, get rid of mixed content errors by adding this to ./routes/web.php:
if (App::environment('production')) {
URL::forceScheme('https');
}
And update the .env:
APP_URL=https://proot.zcyph.cc
ASSET_URL="${APP_URL}"
The Docker Way
Instead of installing and maintaining PHP, Composer, Laravel, Breeze, NodeJS, SQL and NGINX all on the host machine, you can use a more contained, reproducible and portable development environment that more closely resembles a production environment, with local DNS and HTTPS.
git clonethe nginx-php-mariadb repo- set desired port numbers in
docker-compose.yml - set hostname in
./nginx/conf.d/app.conf MARIADB_ROOT_HOST: '%'is set to allow access to DB container from host machine- set
MARIADB_DATABASEindocker-compose.yml - set desired
appnameindocker-compose.ymlfor each container
Then bring up the stack with docker-compose up -d --build.
Laravel requires an empty folder to install into, so install it with:
docker-compose exec app composer create-project laravel/laravel appname
Then move the project into current directory:
sudo cp -rT appname .
sudo rm -R appname
NOTE: It won't work if appname is app, as there is already a folder called app.
Permissions
Make sure the PHP container has set permissions matching current user (ie: 1000:1000 - check current user ID with id).
Set appropriate directory and file permissions (replace . with directory as needed):
sudo find . -type f -exec chmod 664 {} \;
sudo find . -type d -exec chmod 775 {} \;
sudo chown -R md:md storage bootstrap/cache
Database
Be sure to edit .env with appropriate db settings. Example:
DB_CONNECTION=mysql
DB_HOST=db
DB_PORT=3306
DB_DATABASE=prootdb
DB_USERNAME=root
Here db refers to the Docker service name, which only works if they are on the same docker network subnet.
On first run, docker stack will create database automatically if properly defined in the docker-compose.yml.
Although the database itself is created, the tables are not yet, so do the migration to create them:
docker-compose exec app php artisan migrate
Ensure the correct configuration is set in Traefik and Pihole for local DNS & HTTPS. In ./traefik/data/config.yml:
http:
routers:
proot:
entryPoints:
- https
rule: "Host(`proot.zcyph.cc`)"
middlewares:
- default-headers
tls:
certResolver: cloudflare
service: proot
services:
proot:
loadBalancer:
servers:
- url: "http://192.168.1.129:8140"
passHostHeader: true
And in pi.zcyph.cc, go to Local DNS -> CNAME Records and add Domain of appname.zcyph.cc with Target of server.zcyph.cc, then do docker-compose restart from within the Traefik directory, or docker restart traefik.
The Laravel app should now be available at https://appname.zcyph.cc.
Jetstream
Jetstream provides scaffolding for user authentication, 2FA, user profiles and Livewire, all with Tailwind.
docker-compose exec app composer require laravel/jetstream
docker-compose exec app php artisan jetstream:install livewire
docker-compose exec app php artisan migrate