Saturday, March 4, 2023

Valet commands cheet sheets

Starting and Stopping Valet

valet start - Start Valet

valet stop - Stop Valet

valet restart - Restart Valet

Managing Sites

valet park - Map the current directory to a Valet site

valet link [name] - Create a symbolic link for a site

valet secure - Secure a site with HTTPS

valet share - Share a site publicly via ngrok

valet unlink [name] - Remove a symbolic link for a site

valet unsecure - Remove HTTPS from a site

valet forget [name] - Remove a site from Valet

Viewing Logs

valet logs - View the Nginx and PHP error logs

Miscellaneous

valet paths - Display the paths used by Valet

valet open - Open the current site in your default web browser

valet list - List all sites that are mapped in Valet

valet version - Display the current version of Valet

I hope you find this cheet sheet helpful! Let me know if you have any other questions. 

Use multiple php version using valet

 To use multiple PHP versions with Valet on a Mac, you will need to follow these steps:

Install the desired versions of PHP using Homebrew. For example, to install PHP 7.4 and 8.0:

brew install php@7.4

brew install php@8.0

Install Valet if you haven't already:

composer global require laravel/valet

valet install

Install Valet's PHP switcher plugin:

valet install

valet use php@7.4

Create a symbolic link for each version of PHP that you installed. For example:

sudo ln -s /usr/local/opt/php@7.4/bin/php /usr/local/bin/php74

sudo ln -s /usr/local/opt/php@8.0/bin/php /usr/local/bin/php80

Run the following command to add the newly created symbolic links to your $PATH environment variable:


echo 'export PATH="/usr/local/bin:$PATH"' >> ~/.bash_profile

source ~/.bash_profile

Restart Valet:

valet restart

You can now switch between PHP versions using the valet use command. For example, to use PHP 7.4:

valet use php@7.4

To switch back to PHP 8.0:


valet use php@8.0

Note that you will need to install any required PHP extensions for each version of PHP that you use. You can install extensions using Homebrew or by manually compiling and installing them.

Setup mssql using valet in MAC

To set up MS SQL in Valet on a Mac, you will need to follow these steps:

Install the required PHP extensions:

brew tap exolnet/homebrew-deprecated

For php 7.4

brew install php@7.4-mssql

For php 8.0

brew install php@8.0-mssql

Install the SQL Server driver for PHP:

pecl install sqlsrv pdo_sqlsrv

Once the SQL Server driver is installed, add the following lines to your PHP configuration file:

extension=sqlsrv.so

extension=pdo_sqlsrv.so

Install the Microsoft ODBC Driver for SQL Server:

brew tap microsoft/mssql-release https://github.com/Microsoft/homebrew-mssql-release

brew install msodbcsql17

Configure Valet to use MS SQL by adding the following lines to your Valet configuration file ~/.config/valet/config.json:

json

Copy code

"mssql": {

     "port": "1433",

     "dump": false

 }

Restart Valet and you should now be able to use MS SQL in your PHP applications. To test, create a new Laravel project and try connecting to your MS SQL database.


Note: Make sure that your MS SQL server is configured to allow remote connections if you are using a remote server. 

for mac add this path to zshrc file

export PATH="$HOME/.composer/vendor/bin:$PATH"


Saturday, February 11, 2023

5 Ways to Use Raw Database Queries in Laravel

 Laravel has a great database mechanism called Eloquent, also a powerful Query Builder, but sometimes it makes sense to just use plain SQL, in the form of Raw Queries. In this article, I will show you the most common examples of this approach.


1. Most Typical: selectRaw() with Avg/Sum/Count Calculations

If you need to perform groupBy() and then use some aggregation function from MySQL, like AVG() or COUNT(), it’s useful to perform a Raw Query for that specific section.

Example from Laravel documentation:

$users = DB::table('users')
    ->selectRaw('count(*) as user_count, status')
    ->where('status', '<>', 1)
    ->groupBy('status')
    ->get();

Another example:

$products = DB::table('products')
    ->leftjoin('category','category.product_id','=','products.id')
    ->selectRaw('COUNT(*) as nbr', 'products.*')
    ->groupBy('products.id')
    ->get();

Another example – we can even perform avg() and count() in the same statement.

$salaries = DB::table('salaries')
    ->selectRaw('companies.name as company_name, avg(salary) as avg_salary, count(*) as people_count')
    ->join('companies', 'salaries.company_id', '=', 'companies.id')
    ->groupBy('companies.id')
    ->orderByDesc('avg_salary')
    ->get();

2. Filtering YEARS: groupByRaw, orderByRaw and havingRaw

What if you want to add some SQL calculations inside of “group by” or “order by”?
We have methods like groupByRaw() and orderByRaw() for this. Also, we can use additional “where” statement after grouping, by “having” SQL statement with havingRaw().

For example, how to group by a YEAR of a certain date/time field?

$results = User::selectRaw('YEAR(birth_date) as year, COUNT(id) as amount')
    ->groupByRaw('YEAR(birth_date)')
    ->havingRaw('YEAR(birth_date) > 2000')
    ->orderByRaw('YEAR(birth_date)')
    ->get();

3. Calculating one field with sub-query: selectRaw()

If you want to return one specific column as a calculation from other columns, and you want that calculation to happen in SQL query, here’s how it can look:

$products = Product::select('id', 'name')
    ->selectRaw('price - discount_price AS discount')
    ->get();

Another example – CASE statement of SQL:

$users = DB::table('users')
    ->select('name', 'surname')  
    ->selectRaw("(CASE WHEN (gender = 1) THEN 'M' ELSE 'F' END) as gender_text")
    ->get();

4. Old SQL Query? Just use DB::select()

A pretty typical example is when you have an SQL statement from some older project, and you need to convert it to Eloquent or Query Builder.

Guess what, you don’t have to. DB::select() is a perfectly fine statement.

$results = DB::select('select * from users where id = ?', [1]);

5. DB::statement() – Usually in Migrations

If you need to execute some SQL query, without processing any results, like INSERT or UPDATE without any parameters, you can use DB::statement().

In my experience, it’s often used in database migrations, when some table structure changes and old data needs to be updated with a new structure.

DB::statement('UPDATE users SET role_id = 1 WHERE role_id IS NULL AND YEAR(created_at) > 2020');

Also, DB::statement() can perform any SQL query with schema, outside of columns or values.

DB::statement('DROP TABLE users');
DB::statement('ALTER TABLE projects AUTO_INCREMENT=123');

Warning: be careful with parameters, always validate them

Short final notice.

The biggest danger in Raw Queries is that they are not automatically secured, so if you are passing any parameters to the query, please triple-check and validate that they have correct values (like a number and not a string) and in a correct format. 

Ref link: https://blog.quickadminpanel.com/5-ways-to-use-raw-database-queries-in-laravel/

Sunday, January 22, 2023

Set cron for laravel in ngnix server

SSH into your server and navigate to the root directory of your Laravel application.

Run the command crontab -e to open the cron tab editor.

If you want to run cron in every minute then : 

Add the following line to the editor: * * * * * php /path/to/your/laravel/installation/artisan schedule:run >> /dev/null 2>&1

Save and exit the editor.

This will run the Laravel task scheduler every minute.


Note: You should replace the /path/to/your/laravel/installation/ with the actual path of your laravel installation in the server.


Alternatively, you can also add the cron job using the cron command. You can do this by running the following command:


* * * * * cd /path/to/your/laravel/installation && php artisan schedule:run >> /dev/null 2>&1

This will change the current working directory to your laravel installation and runs the schedule:run command every minute.

If you want to run cron in every day: 

0 0 * * * cd /path/to/your/laravel/installation && php artisan schedule:run >> /dev/null 2>&1
This will change the current working directory to your laravel installation and runs the schedule:run command every day at 00:00 (midnight)

You can adjust the time in the cron schedule by modifying the first two fields. The first field is for minutes (0-59), the second field is for hours (0-23), the third field is for day of the month (1-31), the fourth field is for months (1-12) and the fifth field is for day of the week (0-7) (both 0 and 7 mean Sunday).

Make sure that your Nginx server have the correct permissions to execute the cron job, and also make sure that your laravel application have the correct permissions to write to log files, cache and other necessary files.

You can also verify that the cron job is running correctly by checking the logs of the cron jobs, usually located in the /var/log/cron or /var/log/syslog directory. 

It is not necessary to set up a cron job in the cron tab when using Supervisor to manage your Laravel task scheduler.

setup laravel supervisor in ngnix server

 Install Supervisor:


sudo apt-get install supervisor

Create a new configuration file for your Laravel task scheduler in the /etc/supervisor/conf.d/ directory. The file should be named laravel-worker.conf

Add the following configuration to the file:

Copy code

[program:laravel-worker]

process_name=%(program_name)s_%(process_num)02d

command=php /path/to/your/laravel/installation/artisan schedule:run

autostart=true

autorestart=true

user=www-data

redirect_stderr=true

Replace /path/to/your/laravel/installation/ with the actual path of your Laravel installation.

Update the Supervisor's configuration by running the command:

Copy code

sudo supervisorctl reread

Start the Laravel task scheduler process by running the command:

Copy code

sudo supervisorctl start laravel-worker

With this configuration, Supervisor will start the Laravel task scheduler process when the server boots, and it will automatically restart the process if it crashes. It also keeps track of the process and log any errors that may occur.


You can also use sudo supervisorctl stop laravel-worker to stop the process or sudo supervisorctl status laravel-worker to check the status of the process.


You can also use sudo supervisorctl tail -f laravel-worker to see the logs of the process


Note: Make sure you have supervisor installed in your server and you have the correct permissions to manage the process.


Also, make sure your Nginx server have the correct permissions to execute the cron job, and also make sure that your laravel application have the correct permissions to write to log files, cache and other necessary files.

To restart Supervisor, you can use the following command:

sudo service supervisor restart

Alternatively, you can also use the following command:

sudo systemctl restart supervisor

This command is used to restart the supervisor service on systems that use systemd.

You can also use the following command to check the status of the Supervisor service:

sudo service supervisor status

or

sudo systemctl status supervisor

This command will show you if the service is running or not and if there are any errors.

Please note that after restarting supervisor, you will need to update the process by running the following command:

sudo supervisorctl update

Example for laravel cron job which will send 2 birhtday notification mail to user first is one day before and second is the day when birthday is

In your terminal, navigate to the root directory of your Laravel application.

Run the command crontab -e to open the cron tab editor.

Add the following line to the editor: * * * * * php /path/to/your/laravel/installation/artisan schedule:run >> /dev/null 2>&1

Save and exit the editor.

This will run the Laravel task scheduler every minute.


Next, you can define two new tasks in your app/Console/Kernel.php file that will send birthday notifications to users.


use App\User;

use Carbon\Carbon;

use Illuminate\Console\Scheduling\Schedule;

use Illuminate\Support\Facades\Mail;


class Kernel extends ConsoleKernel

{

    protected function schedule(Schedule $schedule)

    {

        $schedule->call(function () {

            $users = User::all();

            foreach ($users as $user) {

                if($user->birthday->isToday()) {

                    Mail::to($user->email)->send(new BirthdayEmail($user));

                }

                if($user->birthday->isTomorrow()) {

                    Mail::to($user->email)->send(new BirthdayReminderEmail($user));

                }

            }

        })->daily();

    }

}

In model: 

use Carbon\Carbon;


class User extends Authenticatable

{

    // other model properties and methods


    public function isToday()

    {

        return Carbon::today()->isSameDay($this->birthday);

    }

   public function isTomorrow()

    {

        return Carbon::tomorrow()->isSameDay($this->birthday);

    }

    public function isTwoDaysBefore()

    {

        return Carbon::now()->addDays(2)->isSameDay($this->birthday);

    }

}