Youtube channel !

Be sure to visit my youtube channel

Thursday, April 21, 2022

Simple Laravel REST API


1) Create the user model in models/UserModel.php 

php artisan make:model User

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;

class User extends Authenticatable
{
use HasApiTokens, HasFactory, Notifiable;

/**
* The attributes that are mass assignable.
*
* @var array<int, string>
*/
protected $fillable = [
'name',
'email',
'password',
];

/**
* The attributes that should be hidden for serialization.
*
* @var array<int, string>
*/
protected $hidden = [
'password',
'remember_token',
];

/**
* The attributes that should be cast.
*
* @var array<string, string>
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
}

 

2) 

create validation for the update requests:  php artisan make:request UserUpdateRequest

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class UserUpdateRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}

/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'name'=>'required',
'email'=>'required|email',
// 'password'=>''
];
}
}


 and for the post request:

php artisan make:request UserPostRequest

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class UserPostRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}

/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'name'=>'required',
'email'=>'required|email',
'password'=>'required'
];
}
}


 

 

create user controller based on the user model: php artisan make:controller UserController --model=User --resource

<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use App\Http\Requests\UserPostRequest;
use App\Http\Requests\UserUpdateRequest;
use App\Http\Resources\UserCollection;
use App\Http\Resources\UserResource;
use App\Models\User;
use Illuminate\Support\Facades\Hash;

class UserController extends Controller
{
public function index()
{
return new UserCollection(User::paginate(5));
}

public function store(UserPostRequest $request)
{
$userData = $request->validated();
$userData['password'] = Hash::make($userData['password']);
$userData['email_verified_at'] = now();

$user = User::forceCreate($userData);
return new UserResource($user);
}

public function show(User $user) //route model binding
{
return new UserResource($user);
}

public function update(User $user, UserUpdateRequest $request)
{
$user->update($request->validated());
}

public function destroy(User $user)
{
$user->delete();
return response()->noContent();
}
}



3) create resources/UserCollection:  php artisan make:resource UserCollection

to return user collection and user resource, when required by the user controller.

<?php

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\ResourceCollection;

class UserCollection extends ResourceCollection
{
/**
* Transform the resource collection into an array.
*
* @param \Illuminate\Http\Request $request
* @return array|\Illuminate\Contracts\Support\Arrayable|\JsonSerializable
*/

public function toArray($request)
{
return
[
'data'=>$this->collection,
'total_count'=> $this->total()
];
}
}

 

create UserResource: //expose which fields to be returned in the json response.

<?php

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\JsonResource;

class UserResource extends JsonResource
{
/**
* Transform the resource into an array.
*
* @param \Illuminate\Http\Request $request
* @return array|\Illuminate\Contracts\Support\Arrayable|\JsonSerializable
*/
public function toArray($request)
{
return [
'id' => $this->id,
'name' => $this->name,
'email' => $this->email,
];
}
}

 

4) enable the requests to be performed, and add validation rules when posting and updating information, inside Requests/UserPostRequest.php

php artisan make:request UserPostRequest

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class UserPostRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}

/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'name'=>'required',
'email'=>'required|email',
'password'=>'required'
];
}
}

for updating info:

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class UserUpdateRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}

/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'name'=>'required',
'email'=>'required|email',
];
}
}

 

6) add routes/api.php in order to redirect /users to the index() method of the UserController.
<?php

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;

use App\Http\Resources\UserCollection;
use App\Models\User;
use App\Http\Controllers\UserController;

Route::apiResource('users', UserController::class);

Cheers!

Wednesday, April 20, 2022

WSL2 - how to make it accessible through outher machines

1) enable wildcard listening address of the app like 0.0.0.0

ss -anpst will show you the on which address/port the app is listening to.

2) use powershell to setup portproxy to forward all the outside requests to the windows machine to land in the WSL2 system:

netsh interface portproxy add v4tov4 listenport=3000 listenaddress=0.0.0.0 connectport=3000 connectaddress=localhost

listenport and listenaddress are on the Windows side.

connectport and connectaddress are on the WSL2 side.

(for a node app the listening port (connectport) is usually 3000, check you app listening port in 1)

verify with:  netsh interface portproxy show all

3) open port 3000 on the firewall with:

netsh advfirewall firewall add rule name="WSL2 app" dir=in action=allow protocol=TCP localport=3000

verify from the windows defender firewall, advanced settings, inbound rules.

Cheers !

Thursday, April 14, 2022

NativeScript - IOS Xcode build and development settings

Instructions for MAC M1 instance:

1) Update your package.json with the latest tns-ios version!

2) run from /platforms directory: tns platform remove ios, tns platform install ios 

3) tns prepare ios, and follow the settings for:

Xcode 12

build:

and development(emulator):

Keep in mind to change for build the VALID_ARCHS to x86_64, and

for developments to arm64 respectively.

 

for Xcode 13 build just change the VALID_ARCHS to:

Thursday, April 07, 2022

Install Laravel Sail on Windows


 

10 Steps to install Laravel Sail and start developing web applications under WSL:

1. from Turn Windows features on and off:

choose Windows subsystem for Linux (WSL) -> and restart the system

2. update the kernel of WSL from https://wslstorestorage.blob.core.windows.net/wslblob/wsl_update_x64.msi

3. set the default version to 2: wsl --set-default-version 2

4. install from Microsoft Store: Ubuntu

open Command prompt, and type ubuntu

5. Update the ubuntu system:

sudo apt-update && sudo apt dist-upgrade -y

6. Setup Docker: Install Docker Desktop

Go to Settings(icon) then check: General->Use the WSL2 based engine, as well as

Resources->WSL INTEGRATION-> enable integration with my default WSL distro, check also Ubuntu and restart the Docker Desktop app.

7. run inside Ubuntu: curl -a https://laravel.build/example-app | bash

8. start the containers with: ./vendor/bin/sail up

9. you can browse: 127.0.0.1:80

10. in another terminal of Ubunu run: code .

so that you can edit your files inside Visual Studio Code.

Cheers!

Wednesday, April 06, 2022

Install WIFI on Ubuntu linux via terminal


 

Steps:

with lsusb we can first see if the device is recognised correctly.

then type: iwconfig then use the Tab key to get to your device name

then edit /etc/wpa_supplicant/wpa.conf

and place there:

network={

ssid="network_id",

psk="encoded_password"

(you need to supply your own network_id and encoded_password,

you can get the encoded_password by typing:

sudo wpa_passphrase your_ssid

then type a password

and you'll get sample config file with the encoded password, you can overwrite the original file with.

Next: start the wpa supplicant with:

suto wpa_supplicant -Dnext -iwxl...(wifi interface id) -cwpa.conf

 

Enjoy!

Laravel RabbitMQ queues


 

In order to connect Laravel with RabbitMQ we will need the following library:

composer require vladimir-yuldashev/laravel-queue-rabbitmq
then
in config/queue.php add the following configuration:
'connections' => [
    // ...

    'rabbitmq' => [
    
       'driver' => 'rabbitmq',
       'queue' => env('RABBITMQ_QUEUE', 'default'),
       'connection' => PhpAmqpLib\Connection\AMQPLazyConnection::class,
   
       'hosts' => [
           [
               'host' => env('RABBITMQ_HOST', '127.0.0.1'),
               'port' => env('RABBITMQ_PORT', 5672),
               'user' => env('RABBITMQ_USER', 'guest'),
               'password' => env('RABBITMQ_PASSWORD', 'guest'),
               'vhost' => env('RABBITMQ_VHOST', '/'),
           ],
       ],
   
       'options' => [
           'ssl_options' => [
               'cafile' => env('RABBITMQ_SSL_CAFILE', null),
               'local_cert' => env('RABBITMQ_SSL_LOCALCERT', null),
               'local_key' => env('RABBITMQ_SSL_LOCALKEY', null),
               'verify_peer' => env('RABBITMQ_SSL_VERIFY_PEER', true),
               'passphrase' => env('RABBITMQ_SSL_PASSPHRASE', null),
           ],
           'queue' => [
               'job' => VladimirYuldashev\LaravelQueueRabbitMQ\Queue\Jobs\RabbitMQJob::class,
           ],
       ],
   
       /*
        * Set to "horizon" if you wish to use Laravel Horizon.
        */
       'worker' => env('RABBITMQ_WORKER', 'default'),
        
    ],

    // ...    
], 
 
then you need to edit the .env file, supplying your settings under the rabbitMQ section:
RABBITMQ_HOST, RABBITMQ_PORT, RABBITMQ_USER, RABBITMQ_PASSWORD, RABBITMQ_VHOST 

also for the QUEUE_CONNECTION you should supply: rabbitmq

Now lets create a job in the terminal with:

php artisan make:job TestJob
it will handle all the incoming queue events. It's contents under /jobs:
private $data;
    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($data)
    {
        //
         $this->data = $data;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        print_r($this->data);
    } 
 
Finally we connect and run the created above job handler in order to handle event. Inside EventServiceProvider.php
inside the boot() function add:
$this->app->bind(
TestJob::class."@handle",
fn($job)=>{$job->handle()} // this will run the handle() function from above.
Then inside of a controller you can run:
use App\Jobs\TestJob;
TestJob::Dispatch('hello'); 
you can see inside of the queue with: php artisan queue:work

Cheers!

Install Angular Material on Ubuntu

Here is how to install Angular Material on Ubuntu:

 

1. Install NODEJS/NPM

inside of a terminal type: sudo apt install nodejs

as an alternative you can use nvm:

curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.1/install.sh | bash 

then just type: nvm install --lts

this will download install and use latest long-term supported version of node.

 

2. Install the angular CLI

with npm i -g @angular/cli

 

3. Create new project: ng new myproject

 

4. Add Material Design: ng add @angular/material

 

5. Restart ng serve if running and enjoy your Material enabled project!

Subscribe To My Channel for updates

Things to do after install Fedora 43

#!/bin/bash # 1. SETUP REPOSITORIES echo ">>> Setting up Repositories (RPM Fusion, Copr, Cisco)..." # Install RPM Fusion ...