Monday, November 11, 2019

Laravel development environment under Ubuntu 19.10

This guide is on how to install the Laravel framework under Ubuntu and set up a local development environment. 

Reference: Practical Ubuntu Linux Server for beginners

First, we will install Apache & MariaDB:
sudo apt install apache2 mariadb-server mariadb-client
then we will setup default password for the MySQL installation:
sudo mysql_secure_installation
Next, we will log in inside MySQL with: sudo mysql -u root
to create our initial database:
create database laravel;
and create a user for the Laravel installation: laravel with password: password
CREATE USER 'laravel'@'%' IDENTIFIED BY 'password';
at the same time will and grant privileges to the user to all databases:
GRANT ALL PRIVILEGES ON *.* TO 'laravel'@'%' ;
Then we will restart the MariaDB server to activate the changes:
sudo systemctl restart mariadb.service
Now is time to install PHP support for Apache and extensions for Laravel with:
sudo apt install php libapache2-mod-php php-common php-mbstring php-xmlrpc php-soap php-gd php-xml php-mysql php-cli php-zip

optionally we can set limits inside php.ini
sudo nano /etc/php/7.3/apache2/php.ini
memory_limit = 256M
upload_max_filesize = 64M
cgi.fix_pathinfo=0


Next, we will install Curl for the composer to be able to run:
sudo apt install curl
Then to install composer we can use:
curl -sS https://getcomposer.org/installer | sudo php -- --install-dir=/usr/local/bin --filename=composer


/*
only if we want to use the laravel command:
let's update the local path to be able to access composer vendor binaries and particularly being able to run laravel:
export PATH = "$HOME/.config/composer/vendor/bin:$PATH"
if you want the path change to be persistent just add the line into the .bashrc file.
*/

It is time to create our project:
cd /var/www/html/
sudo composer create-project laravel/laravel --prefer-dist 
In order for Laravel artisan, Apache and our user to be able to access, read and write to the framework will need to fix the ownership and the permissions of the installation:
we set www-data as owner and group inside the Laravel installation :

sudo chown www-data:www-data /var/www/html/laravel/ -R
Next, we will make sure that all the existing as well as the newly created files will have rwx permissions and will also belong to the www-data group:
sudo chmod +770 /var/www/html/laravel -R
sudo setfacl -d -m g:www-data:rwx /var/www/html/
All that is left is to add our current user to the www-data group:
sudo usermod -a -G www-data $USER
and will switch the current user context to the www-data group:
newgrp www-data

Let's set up the Apache web-server to serve Laravel:
disabling default Apache site configuration
sudo a2dissite 000-default.conf
enable nice URLs:
sudo a2enmod rewrite

create configuration for laravel:
sudo nano /etc/apache2/sites-available/laravel.conf
  
 ServerName laravel.local
    ServerAdmin webmaster@localhost
    DocumentRoot /var/www/html/laravel/public
   
        AllowOverride All
   

    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined


enable the laravel configuration site:
sudo a2ensite laravel.conf


Installing PHPMyAdmin
sudo apt install php-curl
sudo composer create-project phpmyadmin/phpmyadmin

create configuration for phpmyadmin:
sudo nano /etc/apache2/sites-available/phpmyadmin.conf
   
 ServerName phpmyadmin.local
    ServerAdmin webmaster@localhost
    DocumentRoot /var/www/html/phpmyadmin
   
        AllowOverride All
   

    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined

enable the phpmyadmin configuration site:
sudo a2ensite laravel.conf

In order to activate changes we restart the Apache server:
systemctl restart apache2

Because both of the local domains will be accessible through the same IP 127.0.01 we will add them in the /etc/hosts file:
sudo nano /etc/hosts
127.0.0.1       laravel.local
127.0.0.1       phpmyadmin.local
(now we can browse those two host entries inside a browser)
http://laravel.local
http://phpmyadmin.local


Now let's fix some warnings. To run composer without the need of sudo, we will run:
sudo chown -R $USER ~/.config/composer/vendor/bin/ -R
this will give permissions of our user over the composer executable.

Database setup
open up .env and set our details taken from the mariadb setup:
DB_DATABASE=laravel
DB_USERNAME=laravel
DB_PASSWORD=password


Development helping utilities
We will help VSCode to recognize methods inside facades and models:

composer require --dev barryvdh/laravel-ide-helper
php artisan ide-helper:generate
php artisan ide-helper:meta
php artisan ide-helper:models --nowrite
-> in order to place the generated phpdoc to a separate file
in order when you have updates/changes inside the versions of the models/packages/facades your IDE to auto-regenerate the files, inside composer.json scripts place:
"post-update-cmd": [
        "Illuminate\\Foundation\\ComposerScripts::postUpdate",
        "@php artisan ide-helper:generate",
        "@php artisan ide-helper:meta",

        "@php artisan ide-helper:models --nowrite"
]


Navigation inside Visual Studio Code
inside /var/www/html/laravel we start the editor:
code .
Inside VSCode:
Press alt + c to toggle case sensitive highlighting and install the following extensions:
Laravel blade snippets, Laravel extra IntelliSense, Laravel goto view, PHP debug, PHP intelephense, PHP namespace resolver. (and optional: Local History)
Go to user settings" > "extensions" > "blade Configuration" use formatting
Notes on general navigation and debugging through code when developing:
With Ctrl+click we can navigate through locations such as controllers, classes, and blade templates. To return back to the previous location just press: Ctrl+Alt+-.
To search inside of all files inside the project we can use: CTRL+SHIFT+F
In order to list all available classes, methods and properties inside of a file just use:
CTRL+Shift+O
beforehand is needed from preferences to disable the integrated suggestions for php: "php.suggest.basic": false

We will install debugbar for in-browser debugging purposes:
sudo composer require barryvdh/laravel-debugbar --dev
Debugbar also very nicely displays the current ones used by our request while browsing. To debug inside the code, we can also use: dd('what we want to debug'); In case we have lots of variables just place them inside of an array:
$test[]=$var1;
$test[]=$var2;
and then dd($test); will output them all. Try also dd(__METHOD__); It will give you the invocation method location and name.
For adding/removing multiple lines comments toggle: Ctrl + /
in case you would like to know all the available routes, you can use: php artisan route:list

Let's go to the frontend part:
Let's install npm, here is how to get its latest version of:
curl https://www.npmjs.com/install.sh | sudo sh
Now follows the latest version of nodejs from nodesource:
from nodesource
curl -sL https://deb.nodesource.com/setup_13.x | sudo -E bash -
sudo apt-get install -y nodejs

We will require the user interface library and will place it inside as a development dependency:
composer require laravel/ui --dev
Now we add VUE as user interface framework (if you don't want to create the default authentication just omit --auth)
php artisan ui vue --auth
We will install the required laravel UI package dependencies using npm, and when we have them we will compile a development version of all the front-end JavaScript and CSS styles:
npm install && npm run dev
In case of problems during the packages' installation we will do:
npm cache clean --force
and then repeat the last build with npm install && npm run dev
(if you look at the contents of webpack.mix.js, you will see that they point from /resources/ to /public/ directory, so when running npm run dev, actually we grab and compile those resources and place the output inside /public/css and public/js directories)

After our DB connection is setup we can do: php artisan migrate to create our first migration. This is important because this migration will create tables for authentication. When the migration completes we can test the authentication, by creating a user and logging inside the laravel system.

Now we will discuss the simple Laravel flow. In order to protect certain route such as /home, we can use:
$this->middleware('auth');
You can see the function inside the constructor of this controller: public function __construct(){$this->middleware('auth');}
At the same time, how do we know when we type /home in our browser that exactly App/Http/Controllers/HomeController.php will be loaded?
well lets enter inside of /routes directory: web.php
let's focus on the line:
Route::get('/home', 'HomeController@index')->name('home');
which says: if we request /home the HomeController with method index will be loaded.
Then if we follow HomeController.php index.php we see:
public function index(){return view('home');}
return view('home') - simply means load up home.blade.view - this is where our HTML template resides. Go ahead make some changes inside and reload the /home URL to see them live:
Inside home.blade.php we can place:
@auth
You are logged in!
{{Auth::user()->name}}
@else
still not logged in.
@endauth
and inside welcome.blade.php:
@guest
Hi guest!
@endguest
Just save and see the change!

Congratulations!

Subscribe To My Channel for updates