Snippets Collections
1.-Preparar el entorno base:
Instala Docker y Docker Compose en tu sistema para poder construir y manejar contenedores.

2.-Crear estructura de proyecto Laravel:
Puedes crear el proyecto Laravel localmente o usar un contenedor PHP con Composer para generarlo.
Si ya tienes un proyecto Laravel, colócalo en una carpeta donde trabajes con Docker.

3.-Crear archivo Dockerfile para PHP + Apache2 + extensiones relevantes:
Usarás la imagen base oficial de PHP 8.4 con Apache.
Instalarás las extensiones necesarias para Laravel y PostgreSQL, por ejemplo: pdo_pgsql, pgsql, zip, curl, xml, mbstring.
Copiarás el código fuente Laravel al contenedor.
Ejemplo básico de Dockerfile:
FROM php:8.4-apache

RUN apt-get update && apt-get install -y \
    libpq-dev \
    libzip-dev \
    zip \
    unzip \
    && docker-php-ext-install pdo_pgsql pgsql zip bcmath

COPY . /var/www/html/

RUN chown -R www-data:www-data /var/www/html \
    && a2enmod rewrite
    
4.-Configurar Docker Compose para los servicios:
Define servicios para PHP-Apache y PostgreSQL.
Vincula volúmenes para código y datos persistentes.
Configura variables de entorno para Laravel (DB connection).
Ejemplo básico de docker-compose.yml:
version: '3.8'

services:
  app:
    build:
      context: .
      dockerfile: Dockerfile
    ports:
      - "8080:80"
    volumes:
      - ./:/var/www/html
    depends_on:
      - db

  db:
    image: postgres:15
    environment:
      POSTGRES_DB: laravel
      POSTGRES_USER: laraveluser
      POSTGRES_PASSWORD: laravelpass
    volumes:
      - pgdata:/var/lib/postgresql/data

volumes:
  pgdata:

5.-Configurar archivo .env de Laravel:
Ajusta las variables para conectarse a la base de datos PostgreSQL dentro del contenedor:

DB_CONNECTION=pgsql
DB_HOST=db
DB_PORT=5432
DB_DATABASE=laravel
DB_USERNAME=laraveluser
DB_PASSWORD=laravelpass

6.-Construir e iniciar los contenedores Docker:
En la terminal, ejecutar:
docker-compose up --build
Esto facilita manejar dependencias y la base de datos dentro del entorno Docker.

Resumen y conceptos clave:
Dockerfile: define cómo construir la imagen personalizada PHP+Apache con las extensiones necesarias.
Docker Compose: orquesta múltiples contenedores (app y db), redes y volúmenes.
Volúmenes: aseguran que tu código y los datos de la base de datos persistan fuera de los contenedores.
Laravel .env: configura la conexión a la base de datos PostgreSQL dentro de la red Docker.
Comandos Artisan dentro del contenedor mantienen el entorno controlado y consistente.
Este proceso modular te permite entender cómo Docker puede contenerizar un proyecto web completo con backend, webserver y base de datos separados pero comunicados, facilitando el desarrollo y pruebas locales sin alterar tu sistema nativo.
cd /var/www/html/jobran/indicadores/
 php yii serve --docroot "backend/web"
en esta ruta:
/usr/local/sbin/ajustes_pantalla.sh

crear:
bajar la temperatura de color de la pantalla:
#!/bin/bash
# Ajustar temperatura de color
sct 2450
# Ajustar brillo con xcalib
xcalib -co 80 -a

Crea un archivo de servicio para systemd en /etc/systemd/system/, por ejemplo:
sudo nano /etc/systemd/system/ajustes_pantalla.service
codigo:
[Unit]
Description=Servicio de ajustes de pantalla
After=network.target

[Service]
Type=simple
ExecStart=/usr/local/sbin/ajustes_pantalla.sh
Restart=on-failure

[Install]
WantedBy=multi-user.target

Guarda y cierra el archivo.
Recarga systemd para detectar el nuevo servicio:
sudo systemctl enable ajustes_pantalla.service

sudo systemctl restart ajustes_pantalla.service

reducir brillo de pantalla: 
xcalib -co 80 -a

verificar el estado del servicio:
systemctl status ajustes_pantalla.service
cd /var/www/html/jobran/indicadores/
php yii serve --docroot "backend/web"

combinar dos base de datos sql

si quieres ver el contenido de un archivo sql puedes usar:
nano diferencias.sql 

ejemplo para entrar en una que tiene nombre separados por espacios:
cd BASES\ DE\ DATOS\ SQL/

instalar java 
sudo apt update
sudo apt install default-jre
sudo apt install default-jdk
java -version

instalar la herramiuenta para comparar dos bases de datos 
sudo apt update
sudo apt install apgdiff

comando para comparar dos bases de datos sql
apgdiff esquema1.sql esquema2.sql > cambios.sql

conectarse a postgres 

psql -h localhost -U postgres -W

crear la base de datos 
create database dbname;

si tienes el error de que el archivo tiene owner utiliza estos comando
1.-sed '/ALTER SEQUENCE .* OWNER TO/d' indicadores_jobran.sql > jobran_sin_owner.sql
sed '/ALTER SEQUENCE .* OWNER TO/d' indicadores_produccion.sql > prduccion_sin_owner.sql
3.-apgdiff --ignore-start-with jobran_sin_owner.sql prduccion_sin_owner.sql > diferencias.sql


este comando te permite buscar el archivo apgdiff en tu sistema
find ~ -name "apgdiff*.jar"

conectar a una base de datos 
psql -h localhost -U postgres -W


respaldar base de datos 
pg_dump -s -U nameuserdb -h host dbname > sqlcratedname.sql

respaldar sin permisos owner
pg_dump -s --no-owner -U postgres -h host dbname > sqlcratedname.sql

dar permiso para leer pero esto no es necesario 
ya que se insalo usando apt install
chmod +r apgdiff.jar

tambien puedes comparar 
Consultas SQL para comparar tablas y columnas
Si prefieres comparar directamente desde SQL, puedes consultar las tablas del sistema:

Listar tablas:

sql
SELECT table_name FROM information_schema.tables WHERE table_schema = 'public';
Listar columnas de una tabla:

Listar columnas de una tablas:
sql
SELECT column_name, data_type FROM information_schema.columns WHERE table_name = 'nombre_tabla';



El comando mv en Linux se utiliza principalmente para dos funciones importantes:

Mover archivos o directorios de una ubicación a otra dentro del sistema de archivos. Por ejemplo, puedes mover un archivo del directorio actual a otro directorio especificado. También permite mover directorios completos con todo su contenido.

Renombrar archivos o directorios. Al usar mv, si especificas un nuevo nombre en la misma ubicación, en lugar de mover, cambiarás el nombre del archivo o directorio.

mv [opciones] origen destino
Para crear un clúster de base de datos PostgreSQL en Termux, puedes seguir estos pasos básicos:
Instala PostgreSQL en Termux:

pkg install postgresql

Crea un directorio donde se guardarán los datos de PostgreSQL (por ejemplo en tu home):
mkdir ~/datos_psql

Inicializa el clúster de base de datos PostgreSQL en ese directorio:
initdb ~/datos_psql

Inicia el servidor de PostgreSQL apuntando al directorio de datos creado:
pg_ctl -D ~/datos_psql start

Puedes crear una base de datos con:
createdb nombre_base_de_datos

Para acceder a la consola de PostgreSQL, usa:
psql nombre_base_de_datos

Para detener el servidor:
pg_ctl -D ~/datos_psql stop

Ver clústeres/instancias creadas (Debian/Ubuntu)
pg_lsclusters

En Termux, PostgreSQL generalmente se maneja como una única instancia manualmente configurada e iniciada en el directorio de datos que tú especifiques con initdb y pg_ctl. Para "ver el estado" o existencia de tu clúster en Termux, debes revisar manualmente si el directorio de datos existe y si el servidor está en ejecución, ya que no hay un comando integrado tipo pg_lsclusters.

Puedes hacer esto en Termux con comandos típicos del sistema, por ejemplo:

Ver si el directorio de datos está creado (ejemplo con directorio por defecto en Termux):

ls ~/datos_psql

Verificar si el proceso de PostgreSQL está corriendo:
ps aux | grep postgres


En C, la función main devuelve un valor entero que indica el estado con el que el programa terminó y ese valor es enviado al sistema operativo.

Si usas return 0; al final de main, estás indicando que el programa finalizó correctamente, sin errores.

Si usas un valor diferente de 0, ese valor representa un estado de terminación anormal o un código de error o excepción. Por ejemplo, return 1; puede significar que ocurrió algún error durante la ejecución.

Este valor devuelto puede ser utilizado por otros programas, scripts o el sistema operativo para saber si el programa tuvo éxito o si ocurrió algún problema. Es común utilizar diferentes valores diferentes de cero para indicar distintos tipos de errores, facilitando así la gestión y diagnóstico cuando tu programa es ejecutado dentro de un entorno más grande, como scripts batch o sistemas operativos.

Además, existen constantes simbólicas estándar definidas en <stdlib.h> que puedes usar para estos fines:

EXIT_SUCCESS (equivalente a 0, indica éxito)

EXIT_FAILURE (indica fallo)

Ejemplos de uso:

int main() {
    // código
    return 0;
}

#include <stdlib.h>

int main() {
    if (/* algún error */) {
        return EXIT_FAILURE;  // Indica fallo
    }
    return EXIT_SUCCESS;  // Indica éxito
}
uses
  ZConnection, ZDataset;

var
  Conn: TZConnection;
  Query: TZQuery;
begin
  Conn := TZConnection.Create(nil);
  Conn.Protocol := 'postgresql';
  Conn.HostName := 'localhost';
  Conn.Database := 'mi_basedatos';
  Conn.User := 'usuario';
  Conn.Password := 'contraseña';
  Conn.Connect;

  Query := TZQuery.Create(nil);
  Query.Connection := Conn;
  Query.SQL.Text := 'SELECT * FROM tabla;';
  Query.Open;

  while not Query.EOF do
  begin
    writeln(Query.FieldByName('campo').AsString);
    Query.Next;
  end;

  Query.Close;
  Conn.Disconnect;
end.
program Promedio;
var
  n, i: integer;
  suma: real;
  numeros: array of real;
begin
  writeln('¿Cuántos números desea ingresar?');
  readln(n);
  SetLength(numeros, n);
  suma := 0;
  for i := 0 to n-1 do
  begin
    writeln('Ingrese el número ', i+1, ':');
    readln(numeros[i]);
    suma := suma + numeros[i];
  end;
  writeln('El promedio es: ', suma/n:0:2);
end.
program Primo;
var
  n, i: integer;
  esPrimo: boolean;
begin
  writeln('Ingrese un número:');
  readln(n);
  esPrimo := true;
  if n < 2 then
    esPrimo := false
  else
    for i := 2 to n div 2 do
      if n mod i = 0 then
      begin
        esPrimo := false;
        break;
      end;
  if esPrimo then
    writeln(n, ' es un número primo')
  else
    writeln(n, ' no es un número primo');
end.
program Factorial;
var
  n, i: integer;
  factorial: longint;
begin
  writeln('Ingrese un número:');
  readln(n);
  factorial := 1;
  for i := 1 to n do
    factorial := factorial * i;
  writeln('El factorial de ', n, ' es ', factorial);
end.
git clone https://github.com/tfkhdyt/termux-fpc.git

cd termux-fpc
./install.sh

pas nombre_archivo.pas
Si en tu proyecto Yii2 no tienes el archivo console.php, eso significa que no tienes configurada aún la aplicación para la consola (la línea de comandos), que es necesaria para ejecutar comandos como las migraciones.

Para resolverlo, debes crear ese archivo manualmente desde cero dentro de la carpeta config/ de tu proyecto.

Aquí te dejo un ejemplo básico y funcional para que crees tu propio archivo console.php de configuración para la consola en Yii2:

<?php

return [
    'id' => 'app-console',
    'basePath' => dirname(__DIR__),  // Ruta base de tu proyecto
    'controllerNamespace' => 'app\commands', // Ruta por defecto para los controladores de consola
    // Aquí agregas la configuración de conexión a la base de datos
    'components' => [
        'db' => [
            'class' => 'yii\db\Connection',
            'dsn' => 'mysql:host=localhost;dbname=tu_base_de_datos', // Cambia esto por tu configuración
            'username' => 'tu_usuario',
            'password' => 'tu_contraseña',
            'charset' => 'utf8',
        ],
    ],
    // Configurar el controlador de migraciones extendido de la extensión bizley
    'controllerMap' => [
        'migration' => [
            'class' => 'bizley\migration\controllers\MigrationController',
        ],
    ],
];

      Además de crear este archivo, asegúrate de tener el script de entrada para consola que por defecto es el archivo yii (sin extensión) que está en la raíz del proyecto, el cual usa este archivo de configuración para correr comandos. Este archivo debería lucir así:
      
      #!/usr/bin/env php
<?php
defined('YII_DEBUG') or define('YII_DEBUG', true);
defined('YII_ENV') or define('YII_ENV', 'dev');

require __DIR__ . '/vendor/autoload.php';
require __DIR__ . '/vendor/yiisoft/yii2/Yii.php';

$config = require __DIR__ . '/config/console.php';

$application = new yii\console\Application($config);
$exitCode = $application->run();
exit($exitCode);

Resumen de la solución si no tienes console.php
Crea el archivo config/console.php con la configuración mínima requerida (como conexión a DB, controlador de migraciones, etc.).

Asegúrate de tener el archivo ejecutable yii en la raíz del proyecto que carga esa configuración para comandos de consola.

Con eso ya podrás usar comandos Yii como yii migrate y el controlador personalizado para migraciones.
composer require --dev bizley/migration

Configurar el controlador en console.php:
Agrega esto para registrar el controlador de migraciones extendido:

¿Qué es el controlador en controllerMap?
En Yii2, los controladores son clases que contienen la lógica que se ejecuta cuando llamas a un comando o accedes a una ruta web.

En la aplicación de consola, cada comando corresponde a un controlador.

controllerMap es una configuración especial que permite registrar o sobrescribir controladores específicos para la aplicación.
'controllerMap' => [
    'migration' => [
        'class' => 'bizley\migration\controllers\MigrationController',
    ],
],
  Aquí se le está diciendo a Yii2 que cuando ejecutes comandos relacionados con migration (migraciones), debe usar NO el controlador de migraciones por defecto que trae Yii2, sino otro controlador que ofrece la extensión bizley/yii2-migration.
Ese controlador extendido está implementado en la clase PHP bizley\migration\controllers\MigrationController, que viene con la extensión que instalaste.
Esto permite agregar funcionalidades avanzadas al comando yii migration usando ese controlador.
return [
    'id' => 'app-console',
    'basePath' => dirname(__DIR__),
    'controllerMap' => [
        'migration' => [
            'class' => 'bizley\migration\controllers\MigrationController',
        ],
    ],
    // otras configuraciones...
];


¿Dónde se añade esto?
En el archivo console.php de configuración, que es un archivo donde se define un array grande con la configuración, agregarías esta parte dentro del array principal, generalmente así:

  Generar migraciones a partir de la base de datos existente:

Para generar migración de una tabla específica:
  php yii migration/create nombre_tabla

  Para generar migraciones para varias tablas separadas por coma:
  php yii migration/create tabla1,tabla2,tabla3
  
Para generar migraciones para todas las tablas de la base de datos:
  php yii migration/create "*"
1. Usando pg_dump (fuera de psql)
Este es el método más común y recomendado para respaldar una base de datos PostgreSQL.

Respaldar una base de datos completa:
pg_dump -U usuario -h localhost -p 5432 -F c -b -v -f "backup_file.backup" nombre_basedatos

-U: Usuario de PostgreSQL.
-h: Host del servidor (usar localhost si es local).
-p: Puerto (por defecto es 5432).
-F c: Formato personalizado (compacto y comprimido, ideal para restauración).
-b: Incluye objetos grandes (BLOBs).
-v: Modo verbose (muestra detalles del proceso).
-f: Ruta del archivo de salida.
nombre_basedatos: Nombre de la base de datos a respaldar.

Respaldar en formato SQL plano (legible):
pg_dump -U usuario -h localhost -p 5432 -f "backup_file.sql" nombre_basedatos
Sin -F c, se genera un archivo SQL plano (puede ser grande).

Respaldar solo el esquema (sin datos):
pg_dump -U usuario -h localhost -p 5432 -s -f "esquema.sql" nombre_basedatos
-s: Solo estructura (schema), sin datos.

Respaldar tablas específicas:
pg_dump -U usuario -h localhost -p 5432 -t tabla1 -t tabla2 -f "tablas.sql" nombre_basedatos
-t: Especifica las tablas a incluir.

2. Desde la consola psql (exportar datos)
Si ya estás dentro de psql, puedes exportar datos con \copy (pero no es un backup completo como pg_dump):

Exportar una tabla a CSV:
\copy (SELECT * FROM tabla) TO 'ruta/archivo.csv' WITH CSV HEADER;

Exportar resultados de una consulta:
\copy (SELECT col1, col2 FROM tabla WHERE condicion) TO 'ruta/resultado.csv' WITH CSV;

3. Restaurar un backup
Para restaurar un backup creado con pg_dump:
Restaurar backup en formato personalizado (-F c):
pg_restore -U usuario -h localhost -p 5432 -d nombre_basedatos -v "backup_file.backup"

Restaurar backup SQL plano:
psql -U usuario -h localhost -p 5432 -d nombre_basedatos -f "backup_file.sql"

Notas importantes:
PostgreSQL debe estar en el PATH para que funcionen los comandos pg_dump y pg_restore.
Si tienes problemas de permisos, usa sudo -u postgres antes del comando (en Linux).
Para respaldar todas las bases de datos de un cluster, usa pg_dumpall.



$usuarios = User::with(['persona', 'persona.genero', 'institutos'])
              ->select('users.*')
              ->take(5) // o ->limit(5)
              ->get();

Si necesitas paginación manual (avanzar de 5 en 5):
Si quieres controlar el "offset" (desplazamiento) manualmente, puedes combinar skip() y take():

$page = request('page', 1); // Página actual, por defecto 1
$perPage = 5; // Registros por página

$usuarios = User::with(['persona', 'persona.genero', 'institutos'])
              ->select('users.*')
              ->skip(($page - 1) * $perPage) // Salta los registros anteriores
              ->take($perPage) // Toma solo 5
              ->get();

Diferencia con paginate():
paginate() es más completo (maneja automáticamente la lógica de paginación y genera enlaces)

take()/limit() con skip() es más manual pero te da control directo
$usuarios = User::with(['persona', 'persona.genero', 'institutos'])
              ->select('users.*')
              ->paginate(5);

Alternativas:
Paginar con parámetro desde request (para que el cliente pueda cambiar el tamaño de página):

$usuarios = User::with(['persona', 'persona.genero', 'institutos'])
              ->select('users.*')
              ->paginate(request('per_page', 5)); // 5 por defecto

Simple paginación (solo next/previous, sin números de página):
$usuarios = User::with(['persona', 'persona.genero', 'institutos'])
              ->select('users.*')
              ->simplePaginate(5);

Cómo usar en la vista:
En tu controlador:
return view('tu_vista', ['usuarios' => $usuarios]);

En tu vista Blade:
@foreach($usuarios as $usuario)
    <!-- Mostrar datos del usuario -->
@endforeach

{{ $usuarios->links() }} <!-- Esto mostrará los enlaces de paginación -->
  
  Diferencia con paginate():
paginate() es más completo (maneja automáticamente la lógica de paginación y genera enlaces)

take()/limit() con skip() es más manual pero te da control directo
1.-si tienes esto: 

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Tu título aquí</title>

    <!-- Aquí agregas el token CSRF -->
     <meta name="csrf-token" content="{{ csrf_token() }}"> 

    <!-- Otros estilos y scripts -->
    <link rel="stylesheet" href="...">
</head>

puedes hacer simplemente esto segun esta es la manera estandar y mas sencilla:
$.ajaxSetup({
  headers: {
    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
  }
}); 

2.- si tienes esto: 

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Tu título aquí</title>

    <!-- Aquí agregas el token CSRF -->
     <meta name="csrf-token" content="{{ csrf_token() }}"> 

    <!-- Otros estilos y scripts -->
    <link rel="stylesheet" href="...">
</head>

puedes hacer dos cosas capturar una variable dentro de una script asi:

const token = document.querySelector('meta[name="csrf-token"]').getAttribute('content');

luego haces esto:
$('#usuarios').DataTable({
  ajax: {
    url: '/usuarios/data',   // URL al método que devuelve JSON
    type: 'POST'  ,
     data: {
      _token: token, // CSRF token
    } //linea relevante es esta

  },
  processing: true,
  serverSide: true,
  columns: [
    { data: 'persona.nombres' },
    { data: 'persona.apellidos' },
    { data: 'persona.email' },
    { data: 'institutos' },
    { data: 'persona.genero.nombre' },
    { data: 'fecha_nacimiento2' },
    { data: 'acciones' }
  ],
  language: {
    url: "/js/es-ES.json",


  },
  pageLength: 3,

});

3.- @push('scripts')
            <script>
                const token = '{{ csrf_token() }}';
  			 </script>

            @stack('scripts')
        @endpush

luego haces esto:
$('#usuarios').DataTable({
  ajax: {
    url: '/usuarios/data',   // URL al método que devuelve JSON
    type: 'POST'  ,
     data: {
      _token: token, // CSRF token
    } //linea relevante es esta

  },
  processing: true,
  serverSide: true,
  columns: [
    { data: 'persona.nombres' },
    { data: 'persona.apellidos' },
    { data: 'persona.email' },
    { data: 'institutos' },
    { data: 'persona.genero.nombre' },
    { data: 'fecha_nacimiento2' },
    { data: 'acciones' }
  ],
  language: {
    url: "/js/es-ES.json",


  },
  pageLength: 3,

});


 public function crear(Request $request)
    {

        if ($request->isMethod('post')) {
            
            DB::beginTransaction();

            try {
                // Primero crea la persona
                $persona = \App\Models\Personas::create([
                    'cedula' => $request->documento,
                    'nombres' => mb_strtoupper($request->nombres, 'UTF-8'),
                    'apellidos' => mb_strtoupper($request->apellidos, 'UTF-8'),
                    'telefono' => $request->telefono,
                    'email' => $request->email,
                    'fecha_nacimiento' => $request->fecha_nacimiento ?: null,
                    'genero_id' => $request->genero_id,
                ]);

                // Luego crea el usuario, asignando el persona_id recién creado
                $usuario = User::create([
                    'activo' => true,
                    'role_id' => 3,
                    'username' => $request->username,
                    'password' => Hash::make($request->contrasena),
                    'fecha_registro' => now(),
                    'persona_id' => $persona->id,
                    'user_id' => Auth::id(), // equivalente a Auth::user()->id y más seguro
                    'ip' => $request->ip(),
                ]);

                // Finalmente crea la relación con el ente/instituto
                $user_ente = \App\Models\UserInstituto::create([
                    'user_id' => $usuario->id,
                    'instituto_id' => $request->instituto_id,
                    'activo' => true,
                ]);

                DB::commit();

                return redirect()->route('usuarios.index')->with('success', 'Usuario creado exitosamente');
            } catch (\Exception $e) {
                DB::rollback();
                return redirect()->back()->withErrors(['error' => 'Error al crear el usuario: ' . $e->getMessage()]);
            }
            // return redirect()->route('usuarios.crear', ['success' => 'Usuario creado exitosamente.']);
            return redirect()->route('usuarios.index')->with('success', 'Usuario creado exitosamente.');

        } else {
            $Genero = \App\Models\Genero::get()->pluck("nombre", "id");
            $Instituto = \App\Models\Instituto::get()->pluck("nombre", "id");

            //  dd($Ente);
            return view('users.crear', compact('Instituto', 'Genero'));
           


        }
    }
composer require barryvdh/laravel-debugbar --dev
App\Models\NameOfYourModel::factory()->create()     
Route::get('/house/{id}', function ($id) {

    $house = House::find($id);
    return view('house',['house' => $house]);
});
@foreach( $listings as $listing)
@if($listing['is_featured'])
<div class="bg-gray-50 rounded-lg shadow-md overflow-hidden">
    <div class="p-6">
        <h3 class="text-xl font-semibold text-gray-800 mb-2">{{ $listing['address']}}</h3>
        <p class="text-gray-600 mb-4">${{ number_format( $listing['price'])}} • {{ $listing['bed']}}
            Bed
            • {{ $listing['bath']}} Bath</p>
    </div>
</div>
@endif
@endforeach
  return [
            'address' => fake()->address(),
            'price' => fake()->numberBetween(1000000, 8000000),
            'bed' => fake()->numberBetween(4, 8),
            'bath' => fake()->numberBetween(4, 8),
            'is_featured' => 0,

        ];
Route::get('/', function () {
    $listings = Listing::with('employer')->get();
    return view('listings',['listings' => $listings]);
});
Route::get('/listings', function () {
    return view('listings',[ 'listings' => Listing::all()]);
});
<?php

namespace App\Providers;

use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        if (env('DB_LOGQUERIES')) {
            DB::listen(function ($query) {
                Log::info('Query executed: ' . $query->sql, ['bindings' => $query->bindings]);
            });
        }
    }

    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }
}
Dappfort specializes in BRC20 wallet development, providing businesses with a secure, scalable, and budget-friendly solution for managing BRC-20 tokens. Our development process focuses on optimizing costs while ensuring high security, seamless user experience, and robust functionality.

Key Features:

Affordable Development – Cost-effective solutions tailored to your business needs. 
Secure Asset Management – Advanced encryption and multi-signature security. 
Seamless Transactions – Fast and efficient token transfers on the Bitcoin blockchain. 
User-Friendly Interface – Intuitive design for hassle-free access. 
Scalability & Customization – Adaptable to evolving market demands.

At Dappfort, we ensure your BRC20 wallet is built with cutting-edge technology while keeping development costs under control.

Get in touch to develop a cost-effective BRC20 wallet today!

Instant Reach Experts: 
Visit us : https://www.dappfort.com/cryptocurrency-wallet-development-company/ 
Contact : +91 8838534884 
Mail : sales@dappfort.com
DappFort delivers world-class P2P crypto exchange development, helping businesses enter the digital asset market with confidence. Our platforms feature advanced matching engines, dispute resolution, and AI-driven analytics for seamless trading. With multi-currency and multi-payment support, we enhance user accessibility. Get started today and dominate the crypto exchange industry!

Instant Reach Experts: 
Visit us : https://www.dappfort.com/cryptocurrency-exchange-development-company/
Contact : +91 8838534884 
Mail : sales@dappfort.com
Maximize your crypto gains with Dappfort high-performance Crypto Trading Bot Development services. Our bots integrate with major exchanges, use AI-driven strategies, and provide real-time analytics. Trade smarter, faster, and with reduced risks. Let’s build your profit-generating trading bot now!

Instant Reach Experts:

Contact : +91 8838534884 
Mail : sales@dappfort.com
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class TestController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        //
    }
    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        //
    }
    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        //
    }
    /**
     * Display the specified resource.
     */
    public function show(string $id)
    {
        //
    }
    /**
     * Show the form for editing the specified resource.
     */
    public function edit(string $id)
    {
        //
    }
    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, string $id)
    {
        //
    }
    /**
     * Remove the specified resource from storage.
     */
    public function destroy(string $id)
    {
        //
    }
}
 public function states()
  {
      return $this->belongsToMany(
          State::class, // Related model
          'user_state', // Pivot table name
          'user_id', // Foreign key on the pivot table (points to User)
          'state_abbrev', // Foreign key on the pivot table (points to State)
          'id', // Local key on the User model
          'state_abbrev' // Local key on the State model
      )->withPivot('state_abbrev'); // include any info from the pivot table
  }
Route::get('/test', function() {
    return response()->json([
        'message' => 'مرحباً بك في API التجريبي',
        'status' => 'success',
        'timestamp' => now(),
        'data' => [
            'items' => [
                ['id' => 1, 'name' => 'عنصر 1'],
                ['id' => 2, 'name' => 'عنصر 2'],
                ['id' => 3, 'name' => 'عنصر 3']
            ]
        ]
    ]);
});

Route::post('/test', function(Request $request) {
    return response()->json([
        'message' => 'تم استلام البيانات بنجاح',
        'received_data' => $request->all(),
        'timestamp' => now()
    ], 201);
});
In today's digital era, a strong online presence is essential for business success. VFIX Technology, based in Delhi, is recognized as the best website designing company in Delhi and a leading provider of cutting-edge solutions, including app development, e-commerce websites, and website customization. Our goal is to empower businesses with tailored technology solutions that drive growth and customer satisfaction.
Expert App Development for Seamless User Experiences
At VFIX Technology, we specialize in creating intuitive and high-performance mobile apps. Whether you're looking for an app for Android or iOS, we ensure that your users have a seamless experience. From idea conceptualization to final deployment, our app development services cover all stages, offering:

    Custom app solutions for businesses of all sizes
    User-friendly interfaces designed to enhance engagement
    Robust, scalable, and secure apps

By leveraging the latest technologies, our team delivers apps that not only meet your requirements but also exceed your expectations. Whether you need a dynamic mobile presence or a customized app tailored to your industry, we’re here to help you take your mobile strategy to the next level.
<?php
// تأكد من تثبيت مكتبة apple-signin-php باستخدام Composer
require_once 'vendor/autoload.php';

use AppleSignIn\ASDecoder;

// إعدادات قاعدة البيانات
$servername = "localhost";
$username = "nullsafety_app";
$password = "gQ0T(DHze!5L";
$dbname = "nullsafety_app";

// إعدادات Apple Sign In
$LOGIN_APPLE_CLIENT_ID = "io.fitness.club";
$LOGIN_APPLE_SECRET = "eyJraWQiOiJMQ1hESDJSTDJSIiwiYWxnIjoiRVMyNTYifQ.eyJpc3MiOiI2TFRESjJITldZIiwiaWF0IjoxNjk3MTQ2MDU2LCJleHAiOjE3MTI2OTgwNTYsImF1ZCI6Imh0dHBzOi8vYXBwbGVpZC5hcHBsZS5jb20iLCJzdWIiOiJpby5maXRuZXNzLmNsdWIifQ.D4YPbDBiRv76ToNUa9Lll1F82uohsgIUzIN4x-NBNahfZuC_A8LTNzFuaBDCBp4m5ohPa9eTc2xoK4NRJjWJWA";

// إنشاء اتصال
$conn = new mysqli($servername, $username, $password, $dbname);

// التحقق من الاتصال
if ($conn->connect_error) {
    die("فشل الاتصال: " . $conn->connect_error);
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // استلام البيانات من Apple
    $id_token = $_POST['id_token'];
    
    try {
        // فك تشفير وتحقق من الـ token
        $appleSignInPayload = ASDecoder::getAppleSignInPayload($id_token);
        
        // استخراج معلومات المستخدم
        $email = $appleSignInPayload->getEmail();
        $user_id = $appleSignInPayload->getUser();
        // الاسم غير متوفر دائمًا، لذا نحتاج للتحقق
        $name = isset($_POST['user']) ? json_decode($_POST['user'])->name : null;
        
        // التحقق مما إذا كان المستخدم موجودًا بالفعل
        $stmt = $conn->prepare("SELECT id FROM users WHERE apple_id = ?");
        $stmt->bind_param("s", $user_id);
        $stmt->execute();
        $result = $stmt->get_result();
        
        if ($result->num_rows > 0) {
            // المستخدم موجود بالفعل، قم بتحديث المعلومات إذا لزم الأمر
            $stmt = $conn->prepare("UPDATE users SET email = ?, name = ? WHERE apple_id = ?");
            $stmt->bind_param("sss", $email, $name, $user_id);
        } else {
            // مستخدم جديد، قم بإدراجه في قاعدة البيانات
            $stmt = $conn->prepare("INSERT INTO users (apple_id, email, name) VALUES (?, ?, ?)");
            $stmt->bind_param("sss", $user_id, $email, $name);
        }
        
        if ($stmt->execute()) {
            echo "تم تسجيل الدخول وحفظ البيانات بنجاح!";
        } else {
            echo "حدث خطأ أثناء حفظ البيانات: " . $stmt->error;
        }
        
    } catch (Exception $e) {
        echo "حدث خطأ: " . $e->getMessage();
    }
}

$conn->close();
?>

<!DOCTYPE html>
<html>
<head>
    <title>تسجيل الدخول باستخدام Apple</title>
</head>
<body>
    <div id="appleid-signin" data-color="black" data-border="true" data-type="sign in"></div>
    <script type="text/javascript" src="https://appleid.cdn-apple.com/appleauth/static/jsapi/appleid/1/en_US/appleid.auth.js"></script>
    <script type="text/javascript">
        AppleID.auth.init({
            clientId : '<?php echo $LOGIN_APPLE_CLIENT_ID; ?>',
            scope : 'name email',
            redirectURI : 'https://developer.null-safety.com/',
            state : 'YOUR_STATE_VALUE'
        });
    </script>
</body>
</html>
if (!function_exists('dd')) {
    function dd(...$vars)
    {
        // ألوان مختلفة ومتناغمة
        $colors = [
            '#ff9999', '#66b3ff', '#99ff99', '#ffcc99', '#c2c2f0',
            '#ffb3e6', '#c2f0c2', '#ffccff', '#ffb3b3', '#c2c2c2'
        ];
        $colorCount = count($colors);
        
        // الحصول على معلومات إضافية
        $backtrace = debug_backtrace();
        $debugInfo = [
            'line' => $backtrace[0]['line'],
            'file' => $backtrace[0]['file'],
            'function' => $backtrace[1]['function'] ?? 'N/A',
            'request' => $_REQUEST,
            'session' => $_SESSION ?? []
        ];

        // عرض المعلومات الافتراضية إذا لم يتم تمرير أي متغيرات
        if (empty($vars)) {
            $vars[] = [
                'file' => $debugInfo['file'],
                'line' => $debugInfo['line'],
                'function' => $debugInfo['function'],
                'request' => $debugInfo['request'],
                'session' => $debugInfo['session'],
            ];
        }

        echo '<div style="font-family: Arial, sans-serif; line-height: 1.5;">';
        
        foreach ($vars as $index => $var) {
            // حدد اللون بناءً على الفهرس
            $color = $colors[$index % $colorCount];
            
            echo '<div style="background-color: ' . $color . '; padding: 10px; border-radius: 5px; margin-bottom: 10px; color: #fff;">';
            
            // عنوان البلوك
            echo '<strong>Breakpoint (' . $debugInfo['file'] . ' on line ' . $debugInfo['line'] . ') ---> Function: ' . $debugInfo['function'] . '</strong><br>';
            echo '<strong>Request Data:</strong><br>';
            echo '<pre>' . json_encode($debugInfo['request'], JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) . '</pre>';
            echo '<strong>Session Data:</strong><br>';
            echo '<pre>' . json_encode($debugInfo['session'], JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) . '</pre>';
            
            // عرض المتغيرات
            echo '<strong>Variable ' . ($index + 1) . ':</strong><br>';
            if (is_array($var) || is_object($var)) {
                echo '<pre>' . json_encode($var, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) . '</pre>';
            } elseif (is_bool($var) || is_null($var)) {
                var_dump($var);
            } else {
                echo htmlspecialchars($var, ENT_QUOTES, 'UTF-8');
            }
            
            echo '</div>';
        }
        
        echo '</div>';
        die(1);
    }
}
<?php
namespace App\Http\Controllers\Callback;

use App\Models\Gig;
use App\Models\User;
use App\Models\Order;
use Razorpay\Api\Api;
use App\Models\OrderItem;
use App\Models\GigUpgrade;
use Illuminate\Support\Str;
use App\Models\OrderInvoice;
use Illuminate\Http\Request;
use App\Models\DepositWebhook;
use App\Models\CheckoutWebhook;
use App\Models\OrderItemUpgrade;
use App\Models\DepositTransaction;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Http;
use App\Models\AutomaticPaymentGateway;
use App\Notifications\User\Buyer\OrderPlaced;
use App\Notifications\User\Seller\PendingOrder;

class RazorpayController extends Controller
{
    public $gateway = "razorpay";
    public $status  = "paid";
    public $settings;


    /**
     * Payment gateway callback
     *
     * @param Request $request
     * @return mixed
     */
    public function callback(Request $request)
    {
        try {
            
            // Get payment gateway settings
            $settings       = AutomaticPaymentGateway::where('slug', $this->gateway)
                                                     ->where('is_active', true)
                                                     ->firstOrFail();

            // Set settings
            $this->settings = $settings;

            // Get payment id
            $payment_id     = $request->get('payment_id');

            // Get order id
            $order_id       = $request->get('order_id');

            // Get signature
            $signature      = $request->get('signature');

            // Get action
            $action         = $request->get('action');

            // Check webhook event
            if ( $payment_id && $order_id && $signature ) {

                // Check if payment succeeded
                $response = $this->verify($payment_id, $order_id, $signature);

                // Check if payment succeeded
                if ( is_array($response) && $response['success'] === TRUE) {

                    // Check if deposit callback
                    if ($action === "D") {
                        
                        // Get saved webhook data in our database
                        $data = DepositWebhook::where('payment_id', $order_id)
                                                ->where('payment_method', $this->gateway)
                                                ->where('status', 'pending')
                                                ->firstOrFail();
        
                        // Handle deposit callback
                        $this->deposit($data->user_id, $data->amount, $order_id);

                        // Delete saved webhook data in our database
                        $data->delete();

                        // Redirecting
                        return $this->redirect('deposit');

                    }
    
                    // Check if checkout callback
                    if ($action === "G") {
                        
                        // Get saved webhook data in our database
                        $data = CheckoutWebhook::where('payment_id', $order_id)
                                                ->where('payment_method', $this->gateway)
                                                ->where('status', 'pending')
                                                ->firstOrFail();
    
                        // Get cart
                        $cart = $data->data['cart'];
    
                        // Get user
                        $user = User::where('id', $data->data['buyer_id'])->firstOrFail();
        
                        // Handle deposit callback
                        $this->checkout($cart, $user, $order_id);

                        // Delete saved webhook data in our database
                        $data->delete();

                        // Redirecting
                        return $this->redirect('gigs');
    
                    }

                }

            }

            // In case failed redirect to home page
            return redirect('/');

        } catch (\Throwable $th) {

            // Error
            throw $th;

        }
    }


    /**
     * Verify if payment succeeded
     *
     * @param string $id
     * @return array
     */
    private function verify($payment_id, $order_id, $signature)
    {
        try {

            // Get payment gateway keys
            $key_id        = $this->settings?->settings['key_id'];
            $key_secret    = $this->settings?->settings['key_secret'];

            // Set api
            $api           = new Api($key_id, $key_secret);

            // Let's verify first the signature
            $api->utility->verifyPaymentSignature([
                'razorpay_signature'  => $signature,
                'razorpay_payment_id' => $payment_id,
                'razorpay_order_id'   => $order_id
            ]);

            // Fetch this payment
            $fetch_payment = $api->payment->fetch($payment_id);

            // Check if payment authorized
            if ($fetch_payment->status === 'authorized') {
                
                // Let capture this payment
                $payment = $api->payment->fetch($payment_id)->capture([
                    'amount'   => $fetch_payment->amount,
                    'currency' => $fetch_payment->currency
                ]);

            } else if ($fetch_payment->status === 'captured') {
                
                // Set payment
                $payment = $fetch_payment;

            } else {

                // Payment failed
                return [
                    'success'  => false,
                    'message'  => __('messages.t_we_could_not_handle_ur_payment')
                ];

            }

            // Check if payment succeeded
            if ( $payment && $payment->status === 'captured' ) {
                
                // Done
                return [
                    'success'  => true,
                    'response' => $payment
                ];

            } else {

                // Failed
                return [
                    'success' => false,
                    'message' => __('messages.t_error_stripe_payment_failed')
                ];

            }

        } catch (\Throwable $th) {
            
            // Error
            return [
                'success' => false,
                'message' => __('messages.t_toast_something_went_wrong')
            ];

        }
    }


    /**
     * Deposit funds into user's account
     *
     * @param int $user_id
     * @param mixed $amount
     * @param string $payment_id
     * @return void
     */
    private function deposit($user_id, $amount, $payment_id)
    {
        try {
            
            // Set amount
            $amount                  = convertToNumber($amount);
            
            // Calculate fee from this amount
            $fee                     = convertToNumber($this->fee('deposit', $amount)); 

            // Make transaction
            $deposit                 = new DepositTransaction();
            $deposit->user_id        = $user_id;
            $deposit->transaction_id = $payment_id;
            $deposit->payment_method = $this->gateway;
            $deposit->amount_total   = $amount;
            $deposit->amount_fee     = $fee;
            $deposit->amount_net     = $amount - $fee;
            $deposit->currency       = $this->settings->currency;
            $deposit->exchange_rate  = $this->settings->exchange_rate;
            $deposit->status         = $this->status;
            $deposit->ip_address     = request()->ip();
            $deposit->save();

            // Get user
            $user                    = User::where('id', $user_id)->firstOrFail();

            // Add funds
            $user->balance_available = convertToNumber($user->balance_available) + convertToNumber($deposit->amount_net);
            $user->save();

            // Send  a notification
            $this->notification('deposit', $user);

        } catch (\Throwable $th) {

            // Error
            throw $th;

        }
    }


    /**
     * Checkout
     *
     * @param array $cart
     * @param object $user
     * @param string $payment_id
     * @return void
     */
    private function checkout($cart, $user, $payment_id)
    {
        try {

            // Set empty variables
            $subtotal = 0;
            $total    = 0;
            $tax      = 0;
            $fee      = 0;

            // Loop through items in cart
            foreach ($cart as $key => $item) {
                    
                // Add gig price to subtotal
                $subtotal += convertToNumber($item['gig']['price']) * convertToNumber($item['quantity']);

                // Check if item has upgrades
                $upgrades  = $item['upgrades'];

                // Loop through upgrades
                if ( isset($upgrades) && is_array($upgrades) && count($upgrades) ) {
                    
                    // Loop through upgrades
                    foreach ($upgrades as $j => $upgrade) {
                        
                        // Check if upgrade checked
                        if ( isset($upgrade['checked']) && $upgrade['checked'] == 1 ) {
                            
                            // Add upgrade price to subtotal
                            $subtotal += convertToNumber($upgrade['price']) * convertToNumber($item['quantity']);

                        }

                    }

                }

            }

            // Get commission settings
            $commission_settings = settings('commission');

            // Check if taxes enabled
            if ($commission_settings->enable_taxes) {
                
                // Check if type of taxes percentage
                if ($commission_settings->tax_type === 'percentage') {
                    
                    // Set tax amount
                    $tax       = convertToNumber(bcmul($subtotal, $commission_settings->tax_value) / 100);

                } else {
                    
                    // Set tax amount
                    $tax       = convertToNumber($commission_settings->tax_value);

                }

            }

            // Calculate payment gateway fee
            $fee                   = convertToNumber($this->fee( 'gigs', $subtotal ));
            
            // Calculate total price
            $total                 = $subtotal + $tax + $fee;
        
            // Get user billing address
            $billing_info          = $user->billing;

            // Set unique id for this order
            $uid                   = uid();

            // Get buyer id
            $buyer_id              = $user->id;

            // Save order
            $order                 = new Order();
            $order->uid            = $uid;
            $order->buyer_id       = $buyer_id;
            $order->total_value    = $total;
            $order->subtotal_value = $subtotal;
            $order->taxes_value    = $tax;
            $order->save();

            // Loop through items in cart
            foreach ($cart as $key => $item) {
                    
                // Get gig
                $gig = Gig::where('uid', $item['id'])->with('owner')->active()->first();

                // Check if gig exists
                if ($gig) {
                    
                    // Set quantity
                    $quantity        = isset($item['quantity']) ? convertToNumber($item['quantity']) : 1;

                    // Set gig upgrades
                    $upgrades        = isset($item['upgrades']) && is_array($item['upgrades']) && count($item['upgrades']) ? $item['upgrades'] : [];

                    // Set empty variable
                    $upgrades_amount = 0;

                    // Loop through upgrades
                    foreach ($upgrades as $index => $upgrade) {
                        
                        // Check if upgrade is selected
                        if ( isset($upgrade['checked']) && $upgrade['checked'] == 1 ) {
                            
                            $upgrades_amount += convertToNumber($upgrade['price']) * $quantity;

                        }

                    }

                    // Set item total price
                    $item_total = $upgrades_amount + ( convertToNumber($item['gig']['price']) * $quantity );

                    // Calculate commission first
                    if ($commission_settings->commission_from === 'orders') {
                        
                        // Check commission type
                        if ($commission_settings->commission_type === 'percentage') {
                            
                            // Calculate commission
                            $commission = convertToNumber($commission_settings->commission_value) * $item_total / 100;
    
                        } else {
    
                            // Fixed amount
                            $commission = convertToNumber($commission_settings->commission_value);
    
                        }

                    } else {
                        
                        // No commission
                        $commission = 0;

                    }

                    // Save order item
                    $order_item                         = new OrderItem();
                    $order_item->uid                    = uid();
                    $order_item->order_id               = $order->id;
                    $order_item->gig_id                 = $gig->id;
                    $order_item->owner_id               = $gig->user_id;
                    $order_item->quantity               = $quantity;
                    $order_item->has_upgrades           = count($upgrades) ? true : false;
                    $order_item->total_value            = $item_total;
                    $order_item->profit_value           = $item_total - $commission;
                    $order_item->commission_value       = $commission;
                    $order_item->save();

                    // Loop through upgrades again
                    foreach ($upgrades as $index => $value) {
                        
                        // Check if upgrade is selected
                        if ( isset($upgrade['checked']) && $upgrade['checked'] == 1 ) {
                        
                            // Get upgrade
                            $upgrade = GigUpgrade::where('uid', $value['id'])->where('gig_id', $gig->id)->first();
    
                            // Check if upgrade exists
                            if ($upgrade) {
                                
                                // Save item upgrade
                                $order_item_upgrade             = new OrderItemUpgrade();
                                $order_item_upgrade->item_id    = $order_item->id;
                                $order_item_upgrade->title      = $upgrade->title;
                                $order_item_upgrade->price      = $upgrade->price;
                                $order_item_upgrade->extra_days = $upgrade->extra_days;
                                $order_item_upgrade->save();
    
                            }

                        }
                        
                    }

                    // Update seller pending balance
                    $gig->owner()->update([
                        'balance_pending' => convertToNumber($gig->owner->balance_pending) + convertToNumber($order_item->profit_value)
                    ]);

                    // Increment orders in queue
                    $gig->increment('orders_in_queue');

                    // Order item placed successfully
                    // Let's notify the seller about new order
                    $gig->owner->notify( (new PendingOrder($order_item))->locale(config('app.locale')) );

                    // Check user's level
                    check_user_level($buyer_id);

                    // Send notification
                    notification([
                        'text'    => 't_u_received_new_order_seller',
                        'action'  => url('seller/orders/details', $order_item->uid),
                        'user_id' => $order_item->owner_id
                    ]);

                }

            }

            // Save invoice
            $invoice                 = new OrderInvoice();
            $invoice->order_id       = $order->id;
            $invoice->payment_method = $this->gateway;
            $invoice->payment_id     = $payment_id;
            $invoice->firstname      = $billing_info->firstname ?? $user->username;
            $invoice->lastname       = $billing_info->lastname ?? $user->username;
            $invoice->email          = $user->email;
            $invoice->company        = !empty($billing_info->company) ? clean($billing_info->company) : null;
            $invoice->address        = !empty($billing_info->address) ? clean($billing_info->address) : "NA";
            $invoice->status         = 'paid';
            $invoice->save();

            // Update balance
            $user->update([
                'balance_purchases' => convertToNumber($user->balance_purchases) + convertToNumber($total)
            ]);

            // Now everything succeeded
            // Let's empty the cart
            session()->forget('cart');

            // Now let's notify the buyer that his order has been placed
            $user->notify( (new OrderPlaced($order))->locale(config('app.locale')) );

        } catch (\Throwable $th) {
            
            // Error
            throw $th;

        }
    }


    /**
     * Calculate fee value
     *
     * @param string $type
     * @param mixed $amount
     * @return mixed
     */
    private function fee($type, $amount = null)
    {
        try {
            
            // Set amount for deposit
            $amount = convertToNumber($amount) * $this->settings?->exchange_rate / settings('currency')->exchange_rate;

            // Remove long decimal
            $amount = convertToNumber( number_format($amount, 2, '.', '') );

            // Check fee type
            switch ($type) {
    
                // Deposit
                case 'deposit':
    
                    // Get deposit fixed fee
                    if (isset($this->settings->fixed_fee['deposit'])) {
                        
                        // Set fixed fee
                        $fee_fixed = convertToNumber($this->settings->fixed_fee['deposit']);
    
                    } else {
    
                        // No fixed fee
                        $fee_fixed = 0;
    
                    }
    
                    // Get deposit percentage fee
                    if (isset($this->settings->percentage_fee['deposit'])) {
                        
                        // Set percentage fee
                        $fee_percentage = convertToNumber($this->settings->percentage_fee['deposit']);
    
                    } else {
    
                        // No percentage fee
                        $fee_percentage = 0;
    
                    }
    
                    // Calculate percentage of this amount 
                    $fee_percentage_amount = $this->exchange( $fee_percentage * $amount / 100, $this->settings->exchange_rate );

                    // Calculate exchange rate of this fixed fee
                    $fee_fixed_exchange    = $this->exchange( $fee_fixed,  $this->settings->exchange_rate);
                    
                    // Calculate fee value and visible text
                    if ($fee_fixed > 0 && $fee_percentage > 0) {
                        
                        // Calculate fee value
                        $fee_value = convertToNumber($fee_percentage_amount) + convertToNumber($fee_fixed_exchange);
    
                    } else if (!$fee_fixed && $fee_percentage > 0) {
                        
                        // Calculate fee value
                        $fee_value = convertToNumber($fee_percentage_amount);
    
                    } else if ($fee_fixed > 0 && !$fee_percentage) {
    
                        // Calculate fee value
                        $fee_value = convertToNumber($fee_fixed_exchange);
                        
                    } else if (!$fee_percentage && !$fee_fixed) {
                        
                        // Calculate fee value
                        $fee_value = 0;
    
                    }
                    
                    // Return fee value
                    return number_format($fee_value, 2, '.', '');
    
                break;

                // Gigs
                case 'gigs':

                    // Get gigs fixed fee
                    if (isset($this->settings->fixed_fee['gigs'])) {
                        
                        // Set fixed fee
                        $fee_fixed = convertToNumber($this->settings->fixed_fee['gigs']);
    
                    } else {
    
                        // No fixed fee
                        $fee_fixed = 0;
    
                    }
    
                    // Get gigs percentage fee
                    if (isset($this->settings->percentage_fee['gigs'])) {
                        
                        // Set percentage fee
                        $fee_percentage = convertToNumber($this->settings->percentage_fee['gigs']);
    
                    } else {
    
                        // No percentage fee
                        $fee_percentage = 0;
    
                    }
    
                    // Calculate percentage of this amount 
                    $fee_percentage_amount = $this->exchange( $fee_percentage * $amount / 100, $this->settings->exchange_rate );

                    // Calculate exchange rate of this fixed fee
                    $fee_fixed_exchange    = $this->exchange( $fee_fixed,  $this->settings->exchange_rate);
    
                    // Calculate fee value and visible text
                    if ($fee_fixed > 0 && $fee_percentage > 0) {
                        
                        // Calculate fee value
                        $fee_value = convertToNumber($fee_percentage_amount) + convertToNumber($fee_fixed_exchange);
    
                    } else if (!$fee_fixed && $fee_percentage > 0) {
                        
                        // Calculate fee value
                        $fee_value = convertToNumber($fee_percentage_amount);
    
                    } else if ($fee_fixed > 0 && !$fee_percentage) {
    
                        // Calculate fee value
                        $fee_value = convertToNumber($fee_fixed_exchange);
                        
                    } else if (!$fee_percentage && !$fee_fixed) {
                        
                        // Calculate fee value
                        $fee_value = 0;
    
                    }
    
                    // Return fee value
                    return $fee_value;

                break;
    
            }

        } catch (\Throwable $th) {
            
            // Something went wrong
            return 0;

        }
    }


    /**
     * Calculate exchange rate
     *
     * @param mixed $amount
     * @param mixed $exchange_rate
     * @param boolean $formatted
     * @param string $currency
     * @return mixed
     */
    private function exchange($amount, $exchange_rate, $formatted = false, $currency = null)
    {
        try {

            // Convert amount to number
            $amount                = convertToNumber($amount);

            // Get currency settings
            $currency_settings     = settings('currency');

            // Get default currency exchange rate
            $default_exchange_rate = convertToNumber($currency_settings->exchange_rate);

            // Get exchanged amount
            $exchanged_amount      = convertToNumber( $amount *  $default_exchange_rate / $exchange_rate );

            // Check if we have to return a formatted value
            if ($formatted) {
                
                return money( $exchanged_amount, $currency, true )->format();

            }

            // Return max deposit
            return convertToNumber(number_format( $exchanged_amount, 2, '.', '' ));

        } catch (\Throwable $th) {

            // Something went wrong
            return $amount;

        }
    }


    /**
     * Send a notification to user
     *
     * @param string $type
     * @param object $user
     * @return void
     */
    private function notification($type, $user)
    {
        try {
            
            // Check notification type
            switch ($type) {

                // Deposit funds
                case 'deposit':
                    


                break;

                // Gig checkout
                case 'gig':
                    
                    

                break;

                // Project payment
                case 'project':
                    
                    

                break;

                // Bid payment
                case 'bid':
                    
                    

                break;

            }

        } catch (\Throwable $th) {
            
            // Something went wrong
            return;

        }
    }


    /**
     * Redirecting
     *
     * @param string $type
     * @param string $status
     * @return void
     */
    private function redirect($type, $status = 'success')
    {
        // Check where to redirect
        switch ($type) {

            // Deposit history
            case 'deposit':
                
                // Check if payment succeeded
                if ($status === 'success') {
                    
                    // Redirect to deposit history page
                    return redirect('account/deposit/history')->with('success', __('messages.t_ur_transaction_has_completed'));

                } else if ($status === 'pending') {
                    
                    // Redirect to deposit history page
                    return redirect('account/deposit/history')->with('success', __('messages.t_mollie_payment_pending'));

                }
                

            break;

            // Gigs order
            case 'gigs':
                
                // Check if payment succeeded
                if ($status === 'success') {
                    
                    // Redirect to deposit history page
                    return redirect('account/orders')->with('success', __('messages.t_submit_ur_info_now_seller_start_order'));

                } else if ($status === 'pending') {
                    
                    // Redirect to deposit history page
                    return redirect('account/orders')->with('success', __('messages.t_mollie_payment_pending'));

                }

            break;

        }
    }
}
<?php
namespace App\Http\Controllers\Callback;

use App\Models\Gig;
use App\Models\User;
use App\Models\Order;
use App\Models\OrderItem;
use App\Models\GigUpgrade;
use App\Models\OrderInvoice;
use Illuminate\Http\Request;
use App\Models\DepositWebhook;
use App\Models\CheckoutWebhook;
use App\Models\OrderItemUpgrade;
use App\Models\DepositTransaction;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Http;
use App\Models\AutomaticPaymentGateway;
use App\Notifications\User\Buyer\OrderPlaced;
use App\Notifications\User\Seller\PendingOrder;

class PaymobPkController extends Controller
{
    public $gateway = "paymob-pk";
    public $status  = "paid";
    public $settings;


    /**
     * Payment gateway callback
     *
     * @param Request $request
     * @return mixed
     */
    public function callback(Request $request)
    {
        try {
            
            // Get payment gateway settings
            $settings       = AutomaticPaymentGateway::where('slug', $this->gateway)
                                                     ->where('is_active', true)
                                                     ->firstOrFail();

            // Set settings
            $this->settings = $settings;

            // Get transaction id
            $transaction_id = $request->get('id');

            // Check webhook event
            if ( $transaction_id ) {

                // Check if payment succeeded
                $response = $this->verify($transaction_id);
                
                // Check if payment succeeded
                if ( is_array($response) && $response['success'] === TRUE) {
                    
                    // Get action
                    $action   = $response['response']['obj']['order']['shipping_data']['shipping_method'];

                    // Check if deposit callback
                    if ( isset($action) && $action === "D" ) {
                        
                        // Get saved webhook data in our database
                        $data = DepositWebhook::where('payment_id', $transaction_id)
                                                ->where('payment_method', $this->gateway)
                                                ->where('status', 'pending')
                                                ->firstOrFail();
        
                        // Handle deposit callback
                        $this->deposit($data->user_id, $data->amount, $transaction_id);

                        // Delete saved webhook data in our database
                        $data->delete();

                        // Redirecting
                        return $this->redirect('deposit');

                    }
    
                    // Check if checkout callback
                    if ( isset($action) && $action === "G" ) {
                        
                        // Get saved webhook data in our database
                        $data = CheckoutWebhook::where('payment_id', $transaction_id)
                                                ->where('payment_method', $this->gateway)
                                                ->where('status', 'pending')
                                                ->firstOrFail();
    
                        // Get cart
                        $cart = $data->data['cart'];
    
                        // Get user
                        $user = User::where('id', $data->data['buyer_id'])->firstOrFail();
        
                        // Handle deposit callback
                        $this->checkout($cart, $user, $transaction_id);

                        // Delete saved webhook data in our database
                        $data->delete();

                        // Redirecting
                        return $this->redirect('gigs');
    
                    }

                }

            }

            // In case failed redirect to home page
            return redirect('/');

        } catch (\Throwable $th) {

            // Error
            throw $th;

        }
    }


    /**
     * Verify if payment succeeded
     *
     * @param string $id
     * @return array
     */
    private function verify($id)
    {
        try {

            // Get auth token
            $auth    = Http::acceptJson()->post('https://pakistan.paymob.com/api/auth/tokens', [
                                            'api_key' => $this->settings?->settings['api_key'],
                                        ])->json();

            // Check if token is set
            if (isset($auth['token'])) {

                // Get payment details
                $payment = Http::withToken($auth['token'])
                                ->get("https://pakistan.paymob.com/api/acceptance/transactions/$id")
                                ->json();

                // Check if payment succeeded
                if ( is_array($payment) && isset($payment['obj']['success']) && $payment['obj']['success'] == true ) {
                    
                    // Done
                    return [
                        'success'  => true,
                        'response' => $payment
                    ];

                } else {

                    // Failed
                    return [
                        'success' => false,
                        'message' => __('messages.t_error_stripe_payment_failed')
                    ];

                }

            } else {

                // Failed
                return [
                    'success' => false,
                    'message' => __('messages.t_error_stripe_payment_failed')
                ];

            }

        } catch (\Throwable $th) {
            
            // Error
            return [
                'success' => false,
                'message' => __('messages.t_toast_something_went_wrong')
            ];

        }
    }


    /**
     * Deposit funds into user's account
     *
     * @param int $user_id
     * @param mixed $amount
     * @param string $payment_id
     * @return void
     */
    private function deposit($user_id, $amount, $payment_id)
    {
        try {
            
            // Set amount
            $amount                  = convertToNumber($amount);
            
            // Calculate fee from this amount
            $fee                     = convertToNumber($this->fee('deposit', $amount)); 

            // Make transaction
            $deposit                 = new DepositTransaction();
            $deposit->user_id        = $user_id;
            $deposit->transaction_id = $payment_id;
            $deposit->payment_method = $this->gateway;
            $deposit->amount_total   = $amount;
            $deposit->amount_fee     = $fee;
            $deposit->amount_net     = $amount - $fee;
            $deposit->currency       = $this->settings->currency;
            $deposit->exchange_rate  = $this->settings->exchange_rate;
            $deposit->status         = $this->status;
            $deposit->ip_address     = request()->ip();
            $deposit->save();

            // Get user
            $user                    = User::where('id', $user_id)->firstOrFail();

            // Add funds
            $user->balance_available = convertToNumber($user->balance_available) + convertToNumber($deposit->amount_net);
            $user->save();

            // Send  a notification
            $this->notification('deposit', $user);

        } catch (\Throwable $th) {

            // Error
            throw $th;

        }
    }


    /**
     * Checkout
     *
     * @param array $cart
     * @param object $user
     * @param string $payment_id
     * @return void
     */
    private function checkout($cart, $user, $payment_id)
    {
        try {

            // Set empty variables
            $subtotal = 0;
            $total    = 0;
            $tax      = 0;
            $fee      = 0;

            // Loop through items in cart
            foreach ($cart as $key => $item) {
                    
                // Add gig price to subtotal
                $subtotal += convertToNumber($item['gig']['price']) * convertToNumber($item['quantity']);

                // Check if item has upgrades
                $upgrades  = $item['upgrades'];

                // Loop through upgrades
                if ( isset($upgrades) && is_array($upgrades) && count($upgrades) ) {
                    
                    // Loop through upgrades
                    foreach ($upgrades as $j => $upgrade) {
                        
                        // Check if upgrade checked
                        if ( isset($upgrade['checked']) && $upgrade['checked'] == 1 ) {
                            
                            // Add upgrade price to subtotal
                            $subtotal += convertToNumber($upgrade['price']) * convertToNumber($item['quantity']);

                        }

                    }

                }

            }

            // Get commission settings
            $commission_settings = settings('commission');

            // Check if taxes enabled
            if ($commission_settings->enable_taxes) {
                
                // Check if type of taxes percentage
                if ($commission_settings->tax_type === 'percentage') {
                    
                    // Set tax amount
                    $tax       = convertToNumber(bcmul($subtotal, $commission_settings->tax_value) / 100);

                } else {
                    
                    // Set tax amount
                    $tax       = convertToNumber($commission_settings->tax_value);

                }

            }

            // Calculate payment gateway fee
            $fee                   = convertToNumber($this->fee( 'gigs', $subtotal ));
            
            // Calculate total price
            $total                 = $subtotal + $tax + $fee;
        
            // Get user billing address
            $billing_info          = $user->billing;

            // Set unique id for this order
            $uid                   = uid();

            // Get buyer id
            $buyer_id              = $user->id;

            // Save order
            $order                 = new Order();
            $order->uid            = $uid;
            $order->buyer_id       = $buyer_id;
            $order->total_value    = $total;
            $order->subtotal_value = $subtotal;
            $order->taxes_value    = $tax;
            $order->save();

            // Loop through items in cart
            foreach ($cart as $key => $item) {
                    
                // Get gig
                $gig = Gig::where('uid', $item['id'])->with('owner')->active()->first();

                // Check if gig exists
                if ($gig) {
                    
                    // Set quantity
                    $quantity        = isset($item['quantity']) ? convertToNumber($item['quantity']) : 1;

                    // Set gig upgrades
                    $upgrades        = isset($item['upgrades']) && is_array($item['upgrades']) && count($item['upgrades']) ? $item['upgrades'] : [];

                    // Set empty variable
                    $upgrades_amount = 0;

                    // Loop through upgrades
                    foreach ($upgrades as $index => $upgrade) {
                        
                        // Check if upgrade is selected
                        if ( isset($upgrade['checked']) && $upgrade['checked'] == 1 ) {
                            
                            $upgrades_amount += convertToNumber($upgrade['price']) * $quantity;

                        }

                    }

                    // Set item total price
                    $item_total = $upgrades_amount + ( convertToNumber($item['gig']['price']) * $quantity );

                    // Calculate commission first
                    if ($commission_settings->commission_from === 'orders') {
                        
                        // Check commission type
                        if ($commission_settings->commission_type === 'percentage') {
                            
                            // Calculate commission
                            $commission = convertToNumber($commission_settings->commission_value) * $item_total / 100;
    
                        } else {
    
                            // Fixed amount
                            $commission = convertToNumber($commission_settings->commission_value);
    
                        }

                    } else {
                        
                        // No commission
                        $commission = 0;

                    }

                    // Save order item
                    $order_item                         = new OrderItem();
                    $order_item->uid                    = uid();
                    $order_item->order_id               = $order->id;
                    $order_item->gig_id                 = $gig->id;
                    $order_item->owner_id               = $gig->user_id;
                    $order_item->quantity               = $quantity;
                    $order_item->has_upgrades           = count($upgrades) ? true : false;
                    $order_item->total_value            = $item_total;
                    $order_item->profit_value           = $item_total - $commission;
                    $order_item->commission_value       = $commission;
                    $order_item->save();

                    // Loop through upgrades again
                    foreach ($upgrades as $index => $value) {
                        
                        // Check if upgrade is selected
                        if ( isset($upgrade['checked']) && $upgrade['checked'] == 1 ) {
                        
                            // Get upgrade
                            $upgrade = GigUpgrade::where('uid', $value['id'])->where('gig_id', $gig->id)->first();
    
                            // Check if upgrade exists
                            if ($upgrade) {
                                
                                // Save item upgrade
                                $order_item_upgrade             = new OrderItemUpgrade();
                                $order_item_upgrade->item_id    = $order_item->id;
                                $order_item_upgrade->title      = $upgrade->title;
                                $order_item_upgrade->price      = $upgrade->price;
                                $order_item_upgrade->extra_days = $upgrade->extra_days;
                                $order_item_upgrade->save();
    
                            }

                        }
                        
                    }

                    // Update seller pending balance
                    $gig->owner()->update([
                        'balance_pending' => convertToNumber($gig->owner->balance_pending) + convertToNumber($order_item->profit_value)
                    ]);

                    // Increment orders in queue
                    $gig->increment('orders_in_queue');

                    // Order item placed successfully
                    // Let's notify the seller about new order
                    $gig->owner->notify( (new PendingOrder($order_item))->locale(config('app.locale')) );

                    // Check user's level
                    check_user_level($buyer_id);

                    // Send notification
                    notification([
                        'text'    => 't_u_received_new_order_seller',
                        'action'  => url('seller/orders/details', $order_item->uid),
                        'user_id' => $order_item->owner_id
                    ]);

                }

            }

            // Save invoice
            $invoice                 = new OrderInvoice();
            $invoice->order_id       = $order->id;
            $invoice->payment_method = $this->gateway;
            $invoice->payment_id     = $payment_id;
            $invoice->firstname      = $billing_info->firstname ?? $user->username;
            $invoice->lastname       = $billing_info->lastname ?? $user->username;
            $invoice->email          = $user->email;
            $invoice->company        = !empty($billing_info->company) ? clean($billing_info->company) : null;
            $invoice->address        = !empty($billing_info->address) ? clean($billing_info->address) : "NA";
            $invoice->status         = 'paid';
            $invoice->save();

            // Update balance
            $user->update([
                'balance_purchases' => convertToNumber($user->balance_purchases) + convertToNumber($total)
            ]);

            // Now everything succeeded
            // Let's empty the cart
            session()->forget('cart');

            // Now let's notify the buyer that his order has been placed
            $user->notify( (new OrderPlaced($order))->locale(config('app.locale')) );

        } catch (\Throwable $th) {
            
            // Error
            throw $th;

        }
    }


    /**
     * Calculate fee value
     *
     * @param string $type
     * @param mixed $amount
     * @return mixed
     */
    private function fee($type, $amount = null)
    {
        try {
            
            // Set amount for deposit
            $amount = convertToNumber($amount) * $this->settings?->exchange_rate / settings('currency')->exchange_rate;

            // Remove long decimal
            $amount = convertToNumber( number_format($amount, 2, '.', '') );

            // Check fee type
            switch ($type) {
    
                // Deposit
                case 'deposit':
    
                    // Get deposit fixed fee
                    if (isset($this->settings->fixed_fee['deposit'])) {
                        
                        // Set fixed fee
                        $fee_fixed = convertToNumber($this->settings->fixed_fee['deposit']);
    
                    } else {
    
                        // No fixed fee
                        $fee_fixed = 0;
    
                    }
    
                    // Get deposit percentage fee
                    if (isset($this->settings->percentage_fee['deposit'])) {
                        
                        // Set percentage fee
                        $fee_percentage = convertToNumber($this->settings->percentage_fee['deposit']);
    
                    } else {
    
                        // No percentage fee
                        $fee_percentage = 0;
    
                    }
    
                    // Calculate percentage of this amount 
                    $fee_percentage_amount = $this->exchange( $fee_percentage * $amount / 100, $this->settings->exchange_rate );

                    // Calculate exchange rate of this fixed fee
                    $fee_fixed_exchange    = $this->exchange( $fee_fixed,  $this->settings->exchange_rate);
                    
                    // Calculate fee value and visible text
                    if ($fee_fixed > 0 && $fee_percentage > 0) {
                        
                        // Calculate fee value
                        $fee_value = convertToNumber($fee_percentage_amount) + convertToNumber($fee_fixed_exchange);
    
                    } else if (!$fee_fixed && $fee_percentage > 0) {
                        
                        // Calculate fee value
                        $fee_value = convertToNumber($fee_percentage_amount);
    
                    } else if ($fee_fixed > 0 && !$fee_percentage) {
    
                        // Calculate fee value
                        $fee_value = convertToNumber($fee_fixed_exchange);
                        
                    } else if (!$fee_percentage && !$fee_fixed) {
                        
                        // Calculate fee value
                        $fee_value = 0;
    
                    }
                    
                    // Return fee value
                    return number_format($fee_value, 2, '.', '');
    
                break;

                // Gigs
                case 'gigs':

                    // Get gigs fixed fee
                    if (isset($this->settings->fixed_fee['gigs'])) {
                        
                        // Set fixed fee
                        $fee_fixed = convertToNumber($this->settings->fixed_fee['gigs']);
    
                    } else {
    
                        // No fixed fee
                        $fee_fixed = 0;
    
                    }
    
                    // Get gigs percentage fee
                    if (isset($this->settings->percentage_fee['gigs'])) {
                        
                        // Set percentage fee
                        $fee_percentage = convertToNumber($this->settings->percentage_fee['gigs']);
    
                    } else {
    
                        // No percentage fee
                        $fee_percentage = 0;
    
                    }
    
                    // Calculate percentage of this amount 
                    $fee_percentage_amount = $this->exchange( $fee_percentage * $amount / 100, $this->settings->exchange_rate );

                    // Calculate exchange rate of this fixed fee
                    $fee_fixed_exchange    = $this->exchange( $fee_fixed,  $this->settings->exchange_rate);
    
                    // Calculate fee value and visible text
                    if ($fee_fixed > 0 && $fee_percentage > 0) {
                        
                        // Calculate fee value
                        $fee_value = convertToNumber($fee_percentage_amount) + convertToNumber($fee_fixed_exchange);
    
                    } else if (!$fee_fixed && $fee_percentage > 0) {
                        
                        // Calculate fee value
                        $fee_value = convertToNumber($fee_percentage_amount);
    
                    } else if ($fee_fixed > 0 && !$fee_percentage) {
    
                        // Calculate fee value
                        $fee_value = convertToNumber($fee_fixed_exchange);
                        
                    } else if (!$fee_percentage && !$fee_fixed) {
                        
                        // Calculate fee value
                        $fee_value = 0;
    
                    }
    
                    // Return fee value
                    return $fee_value;

                break;
    
            }

        } catch (\Throwable $th) {
            
            // Something went wrong
            return 0;

        }
    }


    /**
     * Calculate exchange rate
     *
     * @param mixed $amount
     * @param mixed $exchange_rate
     * @param boolean $formatted
     * @param string $currency
     * @return mixed
     */
    private function exchange($amount, $exchange_rate, $formatted = false, $currency = null)
    {
        try {

            // Convert amount to number
            $amount                = convertToNumber($amount);

            // Get currency settings
            $currency_settings     = settings('currency');

            // Get default currency exchange rate
            $default_exchange_rate = convertToNumber($currency_settings->exchange_rate);

            // Get exchanged amount
            $exchanged_amount      = convertToNumber( $amount *  $default_exchange_rate / $exchange_rate );

            // Check if we have to return a formatted value
            if ($formatted) {
                
                return money( $exchanged_amount, $currency, true )->format();

            }

            // Return max deposit
            return convertToNumber(number_format( $exchanged_amount, 2, '.', '' ));

        } catch (\Throwable $th) {

            // Something went wrong
            return $amount;

        }
    }


    /**
     * Send a notification to user
     *
     * @param string $type
     * @param object $user
     * @return void
     */
    private function notification($type, $user)
    {
        try {
            
            // Check notification type
            switch ($type) {

                // Deposit funds
                case 'deposit':
                    


                break;

                // Gig checkout
                case 'gig':
                    
                    

                break;

                // Project payment
                case 'project':
                    
                    

                break;

                // Bid payment
                case 'bid':
                    
                    

                break;

            }

        } catch (\Throwable $th) {
            
            // Something went wrong
            return;

        }
    }


    /**
     * Redirecting
     *
     * @param string $type
     * @param string $status
     * @return void
     */
    private function redirect($type, $status = 'success')
    {
        // Check where to redirect
        switch ($type) {

            // Deposit history
            case 'deposit':
                
                // Check if payment succeeded
                if ($status === 'success') {
                    
                    // Redirect to deposit history page
                    return redirect('account/deposit/history')->with('success', __('messages.t_ur_transaction_has_completed'));

                } else if ($status === 'pending') {
                    
                    // Redirect to deposit history page
                    return redirect('account/deposit/history')->with('success', __('messages.t_mollie_payment_pending'));

                }
                

            break;

            // Gigs order
            case 'gigs':
                
                // Check if payment succeeded
                if ($status === 'success') {
                    
                    // Redirect to deposit history page
                    return redirect('account/orders')->with('success', __('messages.t_submit_ur_info_now_seller_start_order'));

                } else if ($status === 'pending') {
                    
                    // Redirect to deposit history page
                    return redirect('account/orders')->with('success', __('messages.t_mollie_payment_pending'));

                }

            break;

        }
    }
}
<?php
namespace App\Http\Controllers\Callback;

use App\Models\Gig;
use App\Models\User;
use App\Models\Order;
use App\Models\OrderItem;
use App\Models\GigUpgrade;
use Illuminate\Support\Str;
use App\Models\OrderInvoice;
use Illuminate\Http\Request;
use App\Models\DepositWebhook;
use App\Models\CheckoutWebhook;
use App\Models\OrderItemUpgrade;
use App\Models\DepositTransaction;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Http;
use App\Models\AutomaticPaymentGateway;
use App\Notifications\User\Buyer\OrderPlaced;
use App\Notifications\User\Seller\PendingOrder;

class FlutterwaveController extends Controller
{
    public $gateway = "flutterwave";
    public $status  = "paid";
    public $settings;


    /**
     * Payment gateway callback
     *
     * @param Request $request
     * @return mixed
     */
    public function callback(Request $request)
    {
        try {
            
            // Get payment gateway settings
            $settings       = AutomaticPaymentGateway::where('slug', $this->gateway)
                                                     ->where('is_active', true)
                                                     ->firstOrFail();

            // Set settings
            $this->settings = $settings;

            // Get transaction id
            $transaction_id = $request->get('transaction_id');

            // Check webhook event
            if ( $transaction_id ) {

                // Check if payment succeeded
                $response = $this->verify($transaction_id);
                
                // Check if payment succeeded
                if ( is_array($response) && $response['success'] === TRUE) {
                    
                    // Get order id
                    $order_id = $response['response']['data']['tx_ref'];

                    // Check if deposit callback
                    if (Str::startsWith($order_id, "DD")) {
                        
                        // Get saved webhook data in our database
                        $data = DepositWebhook::where('payment_id', $order_id)
                                                ->where('payment_method', $this->gateway)
                                                ->where('status', 'pending')
                                                ->firstOrFail();
        
                        // Handle deposit callback
                        $this->deposit($data->user_id, $data->amount, $order_id);

                        // Delete saved webhook data in our database
                        $data->delete();

                        // Redirecting
                        return $this->redirect('deposit');

                    }
    
                    // Check if checkout callback
                    if (Str::startsWith($order_id, "GG")) {
                        
                        // Get saved webhook data in our database
                        $data = CheckoutWebhook::where('payment_id', $order_id)
                                                ->where('payment_method', $this->gateway)
                                                ->where('status', 'pending')
                                                ->firstOrFail();
    
                        // Get cart
                        $cart = $data->data['cart'];
    
                        // Get user
                        $user = User::where('id', $data->data['buyer_id'])->firstOrFail();
        
                        // Handle deposit callback
                        $this->checkout($cart, $user, $order_id);

                        // Delete saved webhook data in our database
                        $data->delete();

                        // Redirecting
                        return $this->redirect('gigs');
    
                    }

                }

            }

            // In case failed redirect to home page
            return redirect('/');

        } catch (\Throwable $th) {

            // Error
            throw $th;

        }
    }


    /**
     * Verify if payment succeeded
     *
     * @param string $id
     * @return array
     */
    private function verify($id)
    {
        try {

            // Get payment gateway keys
            $secret_key = $this->settings?->settings['secret_key'];

            $response   = Http::withHeaders([
                                    'Authorization' => 'Bearer ' . $secret_key,
                                    'Accept'        => 'application/json',
                                ])->get("https://api.flutterwave.com/v3/transactions/$id/verify")->json();

            // Check if payment succeeded
            if ( is_array($response) && $response['status'] === 'success' ) {
                
                // Done
                return [
                    'success'  => true,
                    'response' => $response
                ];

            } else {

                // Failed
                return [
                    'success' => false,
                    'message' => __('messages.t_error_stripe_payment_failed')
                ];

            }

        } catch (\Throwable $th) {
            
            // Error
            return [
                'success' => false,
                'message' => __('messages.t_toast_something_went_wrong')
            ];

        }
    }


    /**
     * Deposit funds into user's account
     *
     * @param int $user_id
     * @param mixed $amount
     * @param string $payment_id
     * @return void
     */
    private function deposit($user_id, $amount, $payment_id)
    {
        try {
            
            // Set amount
            $amount                  = convertToNumber($amount);
            
            // Calculate fee from this amount
            $fee                     = convertToNumber($this->fee('deposit', $amount)); 

            // Make transaction
            $deposit                 = new DepositTransaction();
            $deposit->user_id        = $user_id;
            $deposit->transaction_id = $payment_id;
            $deposit->payment_method = $this->gateway;
            $deposit->amount_total   = $amount;
            $deposit->amount_fee     = $fee;
            $deposit->amount_net     = $amount - $fee;
            $deposit->currency       = $this->settings->currency;
            $deposit->exchange_rate  = $this->settings->exchange_rate;
            $deposit->status         = $this->status;
            $deposit->ip_address     = request()->ip();
            $deposit->save();

            // Get user
            $user                    = User::where('id', $user_id)->firstOrFail();

            // Add funds
            $user->balance_available = convertToNumber($user->balance_available) + convertToNumber($deposit->amount_net);
            $user->save();

            // Send  a notification
            $this->notification('deposit', $user);

        } catch (\Throwable $th) {

            // Error
            throw $th;

        }
    }


    /**
     * Checkout
     *
     * @param array $cart
     * @param object $user
     * @param string $payment_id
     * @return void
     */
    private function checkout($cart, $user, $payment_id)
    {
        try {

            // Set empty variables
            $subtotal = 0;
            $total    = 0;
            $tax      = 0;
            $fee      = 0;

            // Loop through items in cart
            foreach ($cart as $key => $item) {
                    
                // Add gig price to subtotal
                $subtotal += convertToNumber($item['gig']['price']) * convertToNumber($item['quantity']);

                // Check if item has upgrades
                $upgrades  = $item['upgrades'];

                // Loop through upgrades
                if ( isset($upgrades) && is_array($upgrades) && count($upgrades) ) {
                    
                    // Loop through upgrades
                    foreach ($upgrades as $j => $upgrade) {
                        
                        // Check if upgrade checked
                        if ( isset($upgrade['checked']) && $upgrade['checked'] == 1 ) {
                            
                            // Add upgrade price to subtotal
                            $subtotal += convertToNumber($upgrade['price']) * convertToNumber($item['quantity']);

                        }

                    }

                }

            }

            // Get commission settings
            $commission_settings = settings('commission');

            // Check if taxes enabled
            if ($commission_settings->enable_taxes) {
                
                // Check if type of taxes percentage
                if ($commission_settings->tax_type === 'percentage') {
                    
                    // Set tax amount
                    $tax       = convertToNumber(bcmul($subtotal, $commission_settings->tax_value) / 100);

                } else {
                    
                    // Set tax amount
                    $tax       = convertToNumber($commission_settings->tax_value);

                }

            }

            // Calculate payment gateway fee
            $fee                   = convertToNumber($this->fee( 'gigs', $subtotal ));
            
            // Calculate total price
            $total                 = $subtotal + $tax + $fee;
        
            // Get user billing address
            $billing_info          = $user->billing;

            // Set unique id for this order
            $uid                   = uid();

            // Get buyer id
            $buyer_id              = $user->id;

            // Save order
            $order                 = new Order();
            $order->uid            = $uid;
            $order->buyer_id       = $buyer_id;
            $order->total_value    = $total;
            $order->subtotal_value = $subtotal;
            $order->taxes_value    = $tax;
            $order->save();

            // Loop through items in cart
            foreach ($cart as $key => $item) {
                    
                // Get gig
                $gig = Gig::where('uid', $item['id'])->with('owner')->active()->first();

                // Check if gig exists
                if ($gig) {
                    
                    // Set quantity
                    $quantity        = isset($item['quantity']) ? convertToNumber($item['quantity']) : 1;

                    // Set gig upgrades
                    $upgrades        = isset($item['upgrades']) && is_array($item['upgrades']) && count($item['upgrades']) ? $item['upgrades'] : [];

                    // Set empty variable
                    $upgrades_amount = 0;

                    // Loop through upgrades
                    foreach ($upgrades as $index => $upgrade) {
                        
                        // Check if upgrade is selected
                        if ( isset($upgrade['checked']) && $upgrade['checked'] == 1 ) {
                            
                            $upgrades_amount += convertToNumber($upgrade['price']) * $quantity;

                        }

                    }

                    // Set item total price
                    $item_total = $upgrades_amount + ( convertToNumber($item['gig']['price']) * $quantity );

                    // Calculate commission first
                    if ($commission_settings->commission_from === 'orders') {
                        
                        // Check commission type
                        if ($commission_settings->commission_type === 'percentage') {
                            
                            // Calculate commission
                            $commission = convertToNumber($commission_settings->commission_value) * $item_total / 100;
    
                        } else {
    
                            // Fixed amount
                            $commission = convertToNumber($commission_settings->commission_value);
    
                        }

                    } else {
                        
                        // No commission
                        $commission = 0;

                    }

                    // Save order item
                    $order_item                         = new OrderItem();
                    $order_item->uid                    = uid();
                    $order_item->order_id               = $order->id;
                    $order_item->gig_id                 = $gig->id;
                    $order_item->owner_id               = $gig->user_id;
                    $order_item->quantity               = $quantity;
                    $order_item->has_upgrades           = count($upgrades) ? true : false;
                    $order_item->total_value            = $item_total;
                    $order_item->profit_value           = $item_total - $commission;
                    $order_item->commission_value       = $commission;
                    $order_item->save();

                    // Loop through upgrades again
                    foreach ($upgrades as $index => $value) {
                        
                        // Check if upgrade is selected
                        if ( isset($upgrade['checked']) && $upgrade['checked'] == 1 ) {
                        
                            // Get upgrade
                            $upgrade = GigUpgrade::where('uid', $value['id'])->where('gig_id', $gig->id)->first();
    
                            // Check if upgrade exists
                            if ($upgrade) {
                                
                                // Save item upgrade
                                $order_item_upgrade             = new OrderItemUpgrade();
                                $order_item_upgrade->item_id    = $order_item->id;
                                $order_item_upgrade->title      = $upgrade->title;
                                $order_item_upgrade->price      = $upgrade->price;
                                $order_item_upgrade->extra_days = $upgrade->extra_days;
                                $order_item_upgrade->save();
    
                            }

                        }
                        
                    }

                    // Update seller pending balance
                    $gig->owner()->update([
                        'balance_pending' => convertToNumber($gig->owner->balance_pending) + convertToNumber($order_item->profit_value)
                    ]);

                    // Increment orders in queue
                    $gig->increment('orders_in_queue');

                    // Order item placed successfully
                    // Let's notify the seller about new order
                    $gig->owner->notify( (new PendingOrder($order_item))->locale(config('app.locale')) );

                    // Check user's level
                    check_user_level($buyer_id);

                    // Send notification
                    notification([
                        'text'    => 't_u_received_new_order_seller',
                        'action'  => url('seller/orders/details', $order_item->uid),
                        'user_id' => $order_item->owner_id
                    ]);

                }

            }

            // Save invoice
            $invoice                 = new OrderInvoice();
            $invoice->order_id       = $order->id;
            $invoice->payment_method = $this->gateway;
            $invoice->payment_id     = $payment_id;
            $invoice->firstname      = $billing_info->firstname ?? $user->username;
            $invoice->lastname       = $billing_info->lastname ?? $user->username;
            $invoice->email          = $user->email;
            $invoice->company        = !empty($billing_info->company) ? clean($billing_info->company) : null;
            $invoice->address        = !empty($billing_info->address) ? clean($billing_info->address) : "NA";
            $invoice->status         = 'paid';
            $invoice->save();

            // Update balance
            $user->update([
                'balance_purchases' => convertToNumber($user->balance_purchases) + convertToNumber($total)
            ]);

            // Now everything succeeded
            // Let's empty the cart
            session()->forget('cart');

            // Now let's notify the buyer that his order has been placed
            $user->notify( (new OrderPlaced($order))->locale(config('app.locale')) );

        } catch (\Throwable $th) {
            
            // Error
            throw $th;

        }
    }


    /**
     * Calculate fee value
     *
     * @param string $type
     * @param mixed $amount
     * @return mixed
     */
    private function fee($type, $amount = null)
    {
        try {
            
            // Set amount for deposit
            $amount = convertToNumber($amount) * $this->settings?->exchange_rate / settings('currency')->exchange_rate;

            // Remove long decimal
            $amount = convertToNumber( number_format($amount, 2, '.', '') );

            // Check fee type
            switch ($type) {
    
                // Deposit
                case 'deposit':
    
                    // Get deposit fixed fee
                    if (isset($this->settings->fixed_fee['deposit'])) {
                        
                        // Set fixed fee
                        $fee_fixed = convertToNumber($this->settings->fixed_fee['deposit']);
    
                    } else {
    
                        // No fixed fee
                        $fee_fixed = 0;
    
                    }
    
                    // Get deposit percentage fee
                    if (isset($this->settings->percentage_fee['deposit'])) {
                        
                        // Set percentage fee
                        $fee_percentage = convertToNumber($this->settings->percentage_fee['deposit']);
    
                    } else {
    
                        // No percentage fee
                        $fee_percentage = 0;
    
                    }
    
                    // Calculate percentage of this amount 
                    $fee_percentage_amount = $this->exchange( $fee_percentage * $amount / 100, $this->settings->exchange_rate );

                    // Calculate exchange rate of this fixed fee
                    $fee_fixed_exchange    = $this->exchange( $fee_fixed,  $this->settings->exchange_rate);
                    
                    // Calculate fee value and visible text
                    if ($fee_fixed > 0 && $fee_percentage > 0) {
                        
                        // Calculate fee value
                        $fee_value = convertToNumber($fee_percentage_amount) + convertToNumber($fee_fixed_exchange);
    
                    } else if (!$fee_fixed && $fee_percentage > 0) {
                        
                        // Calculate fee value
                        $fee_value = convertToNumber($fee_percentage_amount);
    
                    } else if ($fee_fixed > 0 && !$fee_percentage) {
    
                        // Calculate fee value
                        $fee_value = convertToNumber($fee_fixed_exchange);
                        
                    } else if (!$fee_percentage && !$fee_fixed) {
                        
                        // Calculate fee value
                        $fee_value = 0;
    
                    }
                    
                    // Return fee value
                    return number_format($fee_value, 2, '.', '');
    
                break;

                // Gigs
                case 'gigs':

                    // Get gigs fixed fee
                    if (isset($this->settings->fixed_fee['gigs'])) {
                        
                        // Set fixed fee
                        $fee_fixed = convertToNumber($this->settings->fixed_fee['gigs']);
    
                    } else {
    
                        // No fixed fee
                        $fee_fixed = 0;
    
                    }
    
                    // Get gigs percentage fee
                    if (isset($this->settings->percentage_fee['gigs'])) {
                        
                        // Set percentage fee
                        $fee_percentage = convertToNumber($this->settings->percentage_fee['gigs']);
    
                    } else {
    
                        // No percentage fee
                        $fee_percentage = 0;
    
                    }
    
                    // Calculate percentage of this amount 
                    $fee_percentage_amount = $this->exchange( $fee_percentage * $amount / 100, $this->settings->exchange_rate );

                    // Calculate exchange rate of this fixed fee
                    $fee_fixed_exchange    = $this->exchange( $fee_fixed,  $this->settings->exchange_rate);
    
                    // Calculate fee value and visible text
                    if ($fee_fixed > 0 && $fee_percentage > 0) {
                        
                        // Calculate fee value
                        $fee_value = convertToNumber($fee_percentage_amount) + convertToNumber($fee_fixed_exchange);
    
                    } else if (!$fee_fixed && $fee_percentage > 0) {
                        
                        // Calculate fee value
                        $fee_value = convertToNumber($fee_percentage_amount);
    
                    } else if ($fee_fixed > 0 && !$fee_percentage) {
    
                        // Calculate fee value
                        $fee_value = convertToNumber($fee_fixed_exchange);
                        
                    } else if (!$fee_percentage && !$fee_fixed) {
                        
                        // Calculate fee value
                        $fee_value = 0;
    
                    }
    
                    // Return fee value
                    return $fee_value;

                break;
    
            }

        } catch (\Throwable $th) {
            
            // Something went wrong
            return 0;

        }
    }


    /**
     * Calculate exchange rate
     *
     * @param mixed $amount
     * @param mixed $exchange_rate
     * @param boolean $formatted
     * @param string $currency
     * @return mixed
     */
    private function exchange($amount, $exchange_rate, $formatted = false, $currency = null)
    {
        try {

            // Convert amount to number
            $amount                = convertToNumber($amount);

            // Get currency settings
            $currency_settings     = settings('currency');

            // Get default currency exchange rate
            $default_exchange_rate = convertToNumber($currency_settings->exchange_rate);

            // Get exchanged amount
            $exchanged_amount      = convertToNumber( $amount *  $default_exchange_rate / $exchange_rate );

            // Check if we have to return a formatted value
            if ($formatted) {
                
                return money( $exchanged_amount, $currency, true )->format();

            }

            // Return max deposit
            return convertToNumber(number_format( $exchanged_amount, 2, '.', '' ));

        } catch (\Throwable $th) {

            // Something went wrong
            return $amount;

        }
    }


    /**
     * Send a notification to user
     *
     * @param string $type
     * @param object $user
     * @return void
     */
    private function notification($type, $user)
    {
        try {
            
            // Check notification type
            switch ($type) {

                // Deposit funds
                case 'deposit':
                    


                break;

                // Gig checkout
                case 'gig':
                    
                    

                break;

                // Project payment
                case 'project':
                    
                    

                break;

                // Bid payment
                case 'bid':
                    
                    

                break;

            }

        } catch (\Throwable $th) {
            
            // Something went wrong
            return;

        }
    }


    /**
     * Redirecting
     *
     * @param string $type
     * @param string $status
     * @return void
     */
    private function redirect($type, $status = 'success')
    {
        // Check where to redirect
        switch ($type) {

            // Deposit history
            case 'deposit':
                
                // Check if payment succeeded
                if ($status === 'success') {
                    
                    // Redirect to deposit history page
                    return redirect('account/deposit/history')->with('success', __('messages.t_ur_transaction_has_completed'));

                } else if ($status === 'pending') {
                    
                    // Redirect to deposit history page
                    return redirect('account/deposit/history')->with('success', __('messages.t_mollie_payment_pending'));

                }
                

            break;

            // Gigs order
            case 'gigs':
                
                // Check if payment succeeded
                if ($status === 'success') {
                    
                    // Redirect to deposit history page
                    return redirect('account/orders')->with('success', __('messages.t_submit_ur_info_now_seller_start_order'));

                } else if ($status === 'pending') {
                    
                    // Redirect to deposit history page
                    return redirect('account/orders')->with('success', __('messages.t_mollie_payment_pending'));

                }

            break;

        }
    }
}
<?php
namespace App\Http\Controllers\Callback;

use App\Models\Gig;
use App\Models\User;
use App\Models\Order;
use App\Models\OrderItem;
use App\Models\GigUpgrade;
use Illuminate\Support\Str;
use App\Models\OrderInvoice;
use Illuminate\Http\Request;
use App\Models\DepositWebhook;
use App\Models\CheckoutWebhook;
use App\Models\OrderItemUpgrade;
use App\Models\DepositTransaction;
use App\Http\Controllers\Controller;
use App\Models\AffiliateTransaction;
use App\Models\AffiliateRegisteration;
use App\Models\AutomaticPaymentGateway;
use App\Notifications\User\Buyer\OrderPlaced;
use App\Notifications\User\Seller\PendingOrder;
use Srmklive\PayPal\Services\PayPal as PayPalClient;

class PaypalController extends Controller
{
    public $gateway = "paypal";
    public $status  = "paid";
    public $settings;


    /**
     * Payment gateway callback
     *
     * @param Request $request
     * @return mixed
     */
    public function callback(Request $request)
    {
        try {
            
            // Get payment gateway settings
            $settings       = AutomaticPaymentGateway::where('slug', $this->gateway)
                                                     ->where('is_active', true)
                                                     ->firstOrFail();

            // Set settings
            $this->settings = $settings;

            // Get transaction id
            $transaction_id = $request->get('order');

            // Check webhook event
            if ( $transaction_id ) {

                // Check if payment succeeded
                $response = $this->verify($transaction_id);
                
                // Check if payment succeeded
                if ( is_array($response) && $response['success'] === TRUE) {
                    
                    // Get order id
                    $order_id = $response['response']['purchase_units'][0]['payments']['captures'][0]['invoice_id'];

                    // Check if deposit callback
                    if (Str::startsWith($order_id, "D-")) {
                        
                        // Get saved webhook data in our database
                        $data = DepositWebhook::where('payment_id', $order_id)
                                                ->where('payment_method', $this->gateway)
                                                ->where('status', 'pending')
                                                ->firstOrFail();
        
                        // Handle deposit callback
                        $this->deposit($data->user_id, $data->amount, $order_id);

                        // Delete saved webhook data in our database
                        $data->delete();

                        // Redirecting
                        return $this->redirect('deposit');

                    }
    
                    // Check if checkout callback
                    if (Str::startsWith($order_id, "G-")) {
                        
                        // Get saved webhook data in our database
                        $data = CheckoutWebhook::where('payment_id', $order_id)
                                                ->where('payment_method', $this->gateway)
                                                ->where('status', 'pending')
                                                ->firstOrFail();
    
                        // Get cart
                        $cart = $data->data['cart'];
    
                        // Get user
                        $user = User::where('id', $data->data['buyer_id'])->firstOrFail();
        
                        // Handle deposit callback
                        $this->checkout($cart, $user, $order_id);

                        // Delete saved webhook data in our database
                        $data->delete();

                        // Redirecting
                        return $this->redirect('gigs');
    
                    }

                }

            }

            // In case failed redirect to home page
            return redirect('/');

        } catch (\Throwable $th) {

            // Error
            throw $th;

        }
    }


    /**
     * Verify if payment succeeded
     *
     * @param string $id
     * @return array
     */
    private function verify($id)
    {
        
            // Get payment gateway keys
            $client_id     = $this->settings?->settings['client_id'];
            $client_secret = $this->settings?->settings['client_secret'];
            $env           = $this->settings?->settings['env'];

            // Set gateway config
            $config = [
                'mode' => 'sandbox' ,
                'live' => [
                    'client_id'     => $client_id,
                    'client_secret' => $client_secret,
                    'app_id'        => '',
                ],
                'sandbox' => [
                    'client_id'     => $client_id,
                    'client_secret' => $client_secret,
                    'app_id'        => '',
                ],
                'payment_action' => 'Sale',
                'currency'       => $this->settings?->currency,
                'notify_url'     => 'https://2lancer.ma/paypal/notify',
                'locale'         => 'en_US',
                'validate_ssl'   => true,
            ];

            // Set paypal provider and config
            $client = new PayPalClient();
    
            // Set client credentials
            $client->setApiCredentials($config);

            // Get paypal access token
            $client->getAccessToken();

            // Capture this order
            $order  = $client->capturePaymentOrder($id);

            // Check if payment succeeded
            if ( is_array($order) && isset($order['status']) && $order['status'] === 'COMPLETED' ) {
                
                // Done
                return [
                    'success'  => true,
                    'response' => $order
                ];

            } else {

                // Failed
                return [
                    'success' => false,
                    'message' => __('messages.t_error_stripe_payment_failed')
                ];

            }

       
    }


    /**
     * Deposit funds into user's account
     *
     * @param int $user_id
     * @param mixed $amount
     * @param string $payment_id
     * @return void
     */
    private function deposit($user_id, $amount, $payment_id)
    {
        try {
            
            // Set amount
            $amount                  = convertToNumber($amount);
            
            // Calculate fee from this amount
            $fee                     = convertToNumber($this->fee('deposit', $amount)); 

            // Make transaction
            $deposit                 = new DepositTransaction();
            $deposit->user_id        = $user_id;
            $deposit->transaction_id = $payment_id;
            $deposit->payment_method = $this->gateway;
            $deposit->amount_total   = $amount;
            $deposit->amount_fee     = $fee;
            $deposit->amount_net     = $amount - $fee;
            $deposit->currency       = $this->settings->currency;
            $deposit->exchange_rate  = $this->settings->exchange_rate;
            $deposit->status         = $this->status;
            $deposit->ip_address     = request()->ip();
            $deposit->save();

            // Get user
            $user                    = User::where('id', $user_id)->firstOrFail();

            // Add funds
            $user->balance_available = convertToNumber($user->balance_available) + convertToNumber($deposit->amount_net);
            $user->save();

            // Send  a notification
            $this->notification('deposit', $user);

        } catch (\Throwable $th) {

            // Error
            throw $th;

        }
    }


    /**
     * Checkout
     *
     * @param array $cart
     * @param object $user
     * @param string $payment_id
     * @return void
     */
    private function checkout($cart, $user, $payment_id)
    {
        try {

            // Set empty variables
            $subtotal = 0;
            $total    = 0;
            $tax      = 0;
            $fee      = 0;

            // Loop through items in cart
            foreach ($cart as $key => $item) {
                    
                // Add gig price to subtotal
                $subtotal += convertToNumber($item['gig']['price']) * convertToNumber($item['quantity']);

                // Check if item has upgrades
                $upgrades  = $item['upgrades'];

                // Loop through upgrades
                if ( isset($upgrades) && is_array($upgrades) && count($upgrades) ) {
                    
                    // Loop through upgrades
                    foreach ($upgrades as $j => $upgrade) {
                        
                        // Check if upgrade checked
                        if ( isset($upgrade['checked']) && $upgrade['checked'] == 1 ) {
                            
                            // Add upgrade price to subtotal
                            $subtotal += convertToNumber($upgrade['price']) * convertToNumber($item['quantity']);

                        }

                    }

                }

            }

            // Get commission settings
            $commission_settings = settings('commission');

            // Check if taxes enabled
            if ($commission_settings->enable_taxes) {
                
                // Check if type of taxes percentage
                if ($commission_settings->tax_type === 'percentage') {
                    
                    // Set tax amount
                    $tax       = convertToNumber(bcmul($subtotal, $commission_settings->tax_value) / 100);

                } else {
                    
                    // Set tax amount
                    $tax       = convertToNumber($commission_settings->tax_value);

                }

            }

            // Calculate payment gateway fee
            $fee                   = convertToNumber($this->fee( 'gigs', $subtotal ));
            
            // Calculate total price
            $total                 = $subtotal + $tax + $fee;
        
            // Get user billing address
            $billing_info          = $user->billing;

            // Set unique id for this order
            $uid                   = uid();

            // Get buyer id
            $buyer_id              = $user->id;

            // Save order
            $order                 = new Order();
            $order->uid            = $uid;
            $order->buyer_id       = $buyer_id;
            $order->total_value    = $total;
            $order->subtotal_value = $subtotal;
            $order->taxes_value    = $tax;
            $order->save();

            // Loop through items in cart
            foreach ($cart as $key => $item) {
                    
                // Get gig
                $gig = Gig::where('uid', $item['id'])->with('owner')->active()->first();

                // Check if gig exists
                if ($gig) {
                    
                    // Set quantity
                    $quantity        = isset($item['quantity']) ? convertToNumber($item['quantity']) : 1;

                    // Set gig upgrades
                    $upgrades        = isset($item['upgrades']) && is_array($item['upgrades']) && count($item['upgrades']) ? $item['upgrades'] : [];

                    // Set empty variable
                    $upgrades_amount = 0;

                    // Loop through upgrades
                    foreach ($upgrades as $index => $upgrade) {
                        
                        // Check if upgrade is selected
                        if ( isset($upgrade['checked']) && $upgrade['checked'] == 1 ) {
                            
                            $upgrades_amount += convertToNumber($upgrade['price']) * $quantity;

                        }

                    }

                    // Set item total price
                    $item_total = $upgrades_amount + ( convertToNumber($item['gig']['price']) * $quantity );

                    // Calculate commission first
                    if ($commission_settings->commission_from === 'orders') {
                        
                        // Check commission type
                        if ($commission_settings->commission_type === 'percentage') {
                            
                            // Calculate commission
                            $commission = convertToNumber($commission_settings->commission_value) * $item_total / 100;
    
                        } else {
    
                            // Fixed amount
                            $commission = convertToNumber($commission_settings->commission_value);
    
                        }

                    } else {
                        
                        // No commission
                        $commission = 0;

                    }

                    // Save order item
                    $order_item                         = new OrderItem();
                    $order_item->uid                    = uid();
                    $order_item->order_id               = $order->id;
                    $order_item->gig_id                 = $gig->id;
                    $order_item->owner_id               = $gig->user_id;
                    $order_item->quantity               = $quantity;
                    $order_item->has_upgrades           = count($upgrades) ? true : false;
                    $order_item->total_value            = $item_total;
                    $order_item->profit_value           = $item_total - $commission;
                    $order_item->commission_value       = $commission;
                    $order_item->save();

                    // Loop through upgrades again
                    foreach ($upgrades as $index => $value) {
                        
                        // Check if upgrade is selected
                        if ( isset($upgrade['checked']) && $upgrade['checked'] == 1 ) {
                        
                            // Get upgrade
                            $upgrade = GigUpgrade::where('uid', $value['id'])->where('gig_id', $gig->id)->first();
    
                            // Check if upgrade exists
                            if ($upgrade) {
                                
                                // Save item upgrade
                                $order_item_upgrade             = new OrderItemUpgrade();
                                $order_item_upgrade->item_id    = $order_item->id;
                                $order_item_upgrade->title      = $upgrade->title;
                                $order_item_upgrade->price      = $upgrade->price;
                                $order_item_upgrade->extra_days = $upgrade->extra_days;
                                $order_item_upgrade->save();
    
                            }

                        }
                        
                    }

                    // Update seller pending balance
                    $gig->owner()->update([
                        'balance_pending' => convertToNumber($gig->owner->balance_pending) + convertToNumber($order_item->profit_value)
                    ]);

                    // Increment orders in queue
                    $gig->increment('orders_in_queue');

                    // Order item placed successfully
                    // Let's notify the seller about new order
                    $gig->owner->notify( (new PendingOrder($order_item))->locale(config('app.locale')) );

                    // Check user's level
                    check_user_level($buyer_id);

                    // Send notification
                    notification([
                        'text'    => 't_u_received_new_order_seller',
                        'action'  => url('seller/orders/details', $order_item->uid),
                        'user_id' => $order_item->owner_id
                    ]);

                }

            }

            // Save invoice
            $invoice                 = new OrderInvoice();
            $invoice->order_id       = $order->id;
            $invoice->payment_method = $this->gateway;
            $invoice->payment_id     = $payment_id;
            $invoice->firstname      = $billing_info->firstname ?? $user->username;
            $invoice->lastname       = $billing_info->lastname ?? $user->username;
            $invoice->email          = $user->email;
            $invoice->company        = !empty($billing_info->company) ? clean($billing_info->company) : null;
            $invoice->address        = !empty($billing_info->address) ? clean($billing_info->address) : "NA";
            $invoice->status         = 'paid';
            $invoice->save();

            // Update balance
            $user->update([
                'balance_purchases' => convertToNumber($user->balance_purchases) + convertToNumber($total)
            ]);

            // Now everything succeeded
            // Let's empty the cart
            session()->forget('cart');

            // Now let's notify the buyer that his order has been placed
            $user->notify( (new OrderPlaced($order, $total))->locale(config('app.locale')) );

            //check for affiliate registeration and check if expired 
            if(settings('affiliate')->is_enabled)
            {
            $affiliate_register =AffiliateRegisteration::where('user_id', $buyer_id)
                                                        ->where('expires_at','>',now())
                                                        ->first() ;
            if($affiliate_register){
                
                // get referral user
                $referral_user = User::where('id', $affiliate_register->referral_id)->first();
                
                // calculate referral earning
                $referral_earning =(convertToNumber(settings('affiliate')->profit_percentage)/100)*convertToNumber($total);
                   
                // add credit to referral wallet
                $referral_balance = convertToNumber($referral_user->balance_available) + $referral_earning;
                $referral_user->update(['balance_available'=>$referral_balance]);

                // create new affiliate transaction
                $affiliate_transaction = new AffiliateTransaction();
                $affiliate_transaction->user_id = $buyer_id ;
                $affiliate_transaction->referral_id = $referral_user->id ;
                $affiliate_transaction->order_id = $order->id ;
                $affiliate_transaction->referral_earning = $referral_earning ;
                $affiliate_transaction->save();
            }
            }


        } catch (\Throwable $th) {
            
            // Error
            throw $th;

        }
    }


    /**
     * Calculate fee value
     *
     * @param string $type
     * @param mixed $amount
     * @return mixed
     */
    private function fee($type, $amount = null)
    {
        try {
            
            // Set amount for deposit
            $amount = convertToNumber($amount) * $this->settings?->exchange_rate / settings('currency')->exchange_rate;

            // Remove long decimal
            $amount = convertToNumber( number_format($amount, 2, '.', '') );

            // Check fee type
            switch ($type) {
    
                // Deposit
                case 'deposit':
    
                    // Get deposit fixed fee
                    if (isset($this->settings->fixed_fee['deposit'])) {
                        
                        // Set fixed fee
                        $fee_fixed = convertToNumber($this->settings->fixed_fee['deposit']);
    
                    } else {
    
                        // No fixed fee
                        $fee_fixed = 0;
    
                    }
    
                    // Get deposit percentage fee
                    if (isset($this->settings->percentage_fee['deposit'])) {
                        
                        // Set percentage fee
                        $fee_percentage = convertToNumber($this->settings->percentage_fee['deposit']);
    
                    } else {
    
                        // No percentage fee
                        $fee_percentage = 0;
    
                    }
    
                    // Calculate percentage of this amount 
                    $fee_percentage_amount = $this->exchange( $fee_percentage * $amount / 100, $this->settings->exchange_rate );

                    // Calculate exchange rate of this fixed fee
                    $fee_fixed_exchange    = $this->exchange( $fee_fixed,  $this->settings->exchange_rate);
                    
                    // Calculate fee value and visible text
                    if ($fee_fixed > 0 && $fee_percentage > 0) {
                        
                        // Calculate fee value
                        $fee_value = convertToNumber($fee_percentage_amount) + convertToNumber($fee_fixed_exchange);
    
                    } else if (!$fee_fixed && $fee_percentage > 0) {
                        
                        // Calculate fee value
                        $fee_value = convertToNumber($fee_percentage_amount);
    
                    } else if ($fee_fixed > 0 && !$fee_percentage) {
    
                        // Calculate fee value
                        $fee_value = convertToNumber($fee_fixed_exchange);
                        
                    } else if (!$fee_percentage && !$fee_fixed) {
                        
                        // Calculate fee value
                        $fee_value = 0;
    
                    }
                    
                    // Return fee value
                    return number_format($fee_value, 2, '.', '');
    
                break;

                // Gigs
                case 'gigs':

                    // Get gigs fixed fee
                    if (isset($this->settings->fixed_fee['gigs'])) {
                        
                        // Set fixed fee
                        $fee_fixed = convertToNumber($this->settings->fixed_fee['gigs']);
    
                    } else {
    
                        // No fixed fee
                        $fee_fixed = 0;
    
                    }
    
                    // Get gigs percentage fee
                    if (isset($this->settings->percentage_fee['gigs'])) {
                        
                        // Set percentage fee
                        $fee_percentage = convertToNumber($this->settings->percentage_fee['gigs']);
    
                    } else {
    
                        // No percentage fee
                        $fee_percentage = 0;
    
                    }
    
                    // Calculate percentage of this amount 
                    $fee_percentage_amount = $this->exchange( $fee_percentage * $amount / 100, $this->settings->exchange_rate );

                    // Calculate exchange rate of this fixed fee
                    $fee_fixed_exchange    = $this->exchange( $fee_fixed,  $this->settings->exchange_rate);
    
                    // Calculate fee value and visible text
                    if ($fee_fixed > 0 && $fee_percentage > 0) {
                        
                        // Calculate fee value
                        $fee_value = convertToNumber($fee_percentage_amount) + convertToNumber($fee_fixed_exchange);
    
                    } else if (!$fee_fixed && $fee_percentage > 0) {
                        
                        // Calculate fee value
                        $fee_value = convertToNumber($fee_percentage_amount);
    
                    } else if ($fee_fixed > 0 && !$fee_percentage) {
    
                        // Calculate fee value
                        $fee_value = convertToNumber($fee_fixed_exchange);
                        
                    } else if (!$fee_percentage && !$fee_fixed) {
                        
                        // Calculate fee value
                        $fee_value = 0;
    
                    }
    
                    // Return fee value
                    return $fee_value;

                break;
    
            }

        } catch (\Throwable $th) {
            
            // Something went wrong
            return 0;

        }
    }


    /**
     * Calculate exchange rate
     *
     * @param mixed $amount
     * @param mixed $exchange_rate
     * @param boolean $formatted
     * @param string $currency
     * @return mixed
     */
    private function exchange($amount, $exchange_rate, $formatted = false, $currency = null)
    {
        try {

            // Convert amount to number
            $amount                = convertToNumber($amount);

            // Get currency settings
            $currency_settings     = settings('currency');

            // Get default currency exchange rate
            $default_exchange_rate = convertToNumber($currency_settings->exchange_rate);

            // Get exchanged amount
            $exchanged_amount      = convertToNumber( $amount *  $default_exchange_rate / $exchange_rate );

            // Check if we have to return a formatted value
            if ($formatted) {
                
                return money( $exchanged_amount, $currency, true )->format();

            }

            // Return max deposit
            return convertToNumber(number_format( $exchanged_amount, 2, '.', '' ));

        } catch (\Throwable $th) {

            // Something went wrong
            return $amount;

        }
    }


    /**
     * Send a notification to user
     *
     * @param string $type
     * @param object $user
     * @return void
     */
    private function notification($type, $user)
    {
        try {
            
            // Check notification type
            switch ($type) {

                // Deposit funds
                case 'deposit':
                    


                break;

                // Gig checkout
                case 'gig':
                    
                    

                break;

                // Project payment
                case 'project':
                    
                    

                break;

                // Bid payment
                case 'bid':
                    
                    

                break;

            }

        } catch (\Throwable $th) {
            
            // Something went wrong
            return;

        }
    }


    /**
     * Redirecting
     *
     * @param string $type
     * @param string $status
     * @return void
     */
    private function redirect($type, $status = 'success')
    {
        // Check where to redirect
        switch ($type) {

            // Deposit history
            case 'deposit':
                
                // Check if payment succeeded
                if ($status === 'success') {
                    
                    // Redirect to deposit history page
                    return redirect('account/deposit/history')->with('success', __('messages.t_ur_transaction_has_completed'));

                } else if ($status === 'pending') {
                    
                    // Redirect to deposit history page
                    return redirect('account/deposit/history')->with('success', __('messages.t_mollie_payment_pending'));

                }
                

            break;

            // Gigs order
            case 'gigs':
                
                // Check if payment succeeded
                if ($status === 'success') {
                    
                    // Redirect to deposit history page
                    return redirect('account/orders')->with('success', __('messages.t_submit_ur_info_now_seller_start_order'));

                } else if ($status === 'pending') {
                    
                    // Redirect to deposit history page
                    return redirect('account/orders')->with('success', __('messages.t_mollie_payment_pending'));

                }

            break;

        }
    }
}
import 'package:flutter/material.dart';
import 'package:shalestin/Screens/home.dart';
  
  void main() => runApp(const MyApp());
  
  class MyApp extends StatelessWidget {
    const MyApp({super.key});
  
    @override
    Widget build(BuildContext context) {
      return MaterialApp(
 routes: {
        'Home': (context) => const Home(),
      },
        initialRoute: 'Home',
        debugShowCheckedModeBanner: false,

      );
    }
  }
import 'dart:convert';
import 'package:http/http.dart' as http;

class ApiService<T> {
  final String _baseUrl;

  ApiService(this._baseUrl);

  Future<List<T>> getAll(T Function(Map<String, dynamic>) fromJson) async {
    final response = await http.get(Uri.parse(_baseUrl));
    if (response.statusCode == 200) {
      final jsonData = json.decode(response.body) as List;
      return jsonData.map((data) => fromJson(data)).toList();
    } else {
      throw Exception('Failed to load data');
    }
  }

  Future<List<T>> search(String query, T Function(Map<String, dynamic>) fromJson) async {
    final response = await http.get(Uri.parse('$_baseUrl?search=$query'));
    if (response.statusCode == 200) {
      final jsonData = json.decode(response.body) as List;
      return jsonData.map((data) => fromJson(data)).toList();
    } else {
      throw Exception('Failed to search data');
    }
  }

  Future<T> create(Map<String, dynamic> data, T Function(Map<String, dynamic>) fromJson) async {
    final response = await http.post(
      Uri.parse(_baseUrl),
      headers: {'Content-Type': 'application/json'},
      body: json.encode(data),
    );
    if (response.statusCode == 201) {
      return fromJson(json.decode(response.body));
    } else {
      throw Exception('Failed to create data');
    }
  }

  Future<T> update(int id, Map<String, dynamic> data, T Function(Map<String, dynamic>) fromJson) async {
    final response = await http.put(
      Uri.parse('$_baseUrl/$id'),
      headers: {'Content-Type': 'application/json'},
      body: json.encode(data),
    );
    if (response.statusCode == 200) {
      return fromJson(json.decode(response.body));
    } else {
      throw Exception('Failed to update data');
    }
  }

  Future<void> delete(int id) async {
    final response = await http.delete(Uri.parse('$_baseUrl/$id'));
    if (response.statusCode != 204) {
      throw Exception('Failed to delete data');
    }
  }
}
//=============================================
class Note {
  final int id;
  final String title;
  final String content;

  Note({required this.id, required this.title, required this.content});

  factory Note.fromJson(Map<String, dynamic> json) {
    return Note(
      id: json['id'],
      title: json['title'],
      content: json['content'],
    );
  }

  Map<String, dynamic> toJson() {
    return {
      'id': id,
      'title': title,
      'content': content,
    };
  }
}

final notesService = ApiService<Note>('http://10.0.2.2:8000/api/notes');

// Get all notes
final notes = await notesService.getAll(Note.fromJson);

// Search for notes
final searchResults = await notesService.search('keyword', Note.fromJson);

// Create a new note
final newNote = await notesService.create(
  {
    'title': 'New Note',
    'content': 'This is a new note',
  },
  Note.fromJson,
);

// Update a note
final updatedNote = await notesService.update(
  newNote.id,
  {
    'title': 'Updated Note',
    'content': 'This is an updated note',
  },
  Note.fromJson,
);

// Delete a note
await notesService.delete(updatedNote.id);
if (config('app.debug')) {
  dump('');
  $this->info('');
}

config('app.debug') ? info('One liner') : null;
<input                       
    type="text" 
    placeholder="Start date" 
    class="px-2 py-1 text-sm rounded text-gray-800" 
    x-init="new Pikaday({ field: $el })"
    x-on:change="$wire.startDate = formatDateToYYYYMMDD(new Date($el.value))"
/>
public function index(Travel $travel, ToursListRequest $request)
    {
        $tours = $travel->tours()
            ->when($request->priceFrom, function ($query) use ($request) {
                $query->where('price', '>=', $request->priceFrom * 100);
            })
            ->when($request->priceTo, function ($query) use ($request) {
                $query->where('price', '<=', $request->priceTo * 100);
            })
            ->when($request->dateFrom, function ($query) use ($request) {
                $query->where('starting_date', '>=', $request->dateFrom);
            })
            ->when($request->dateTo, function ($query) use ($request) {
                $query->where('starting_date', '<=', $request->dateTo);
            })
            ->when($request->sortBy, function ($query) use ($request) {
                if (! in_array($request->sortBy, ['price'])
                    || (! in_array($request->sortOrder, ['asc', 'desc']))) {
                    return;
                }

                $query->orderBy($request->sortBy, $request->sortOrder);
            })
            ->orderBy('starting_date')
            ->paginate();

        return TourResource::collection($tours);
    }
//in controller datatable
->addColumn('mass_delete', function ($row) {
  $selected = '';

  return  '<input type="checkbox" class="row-select test" value="'.$row->id.'">' ;
})


//in view table
 <th>_<input type="checkbox" value="1" id="select-all-row" data-table-id="incoming-messages-table"></th>

//in view datatable (to disable orderable on first column)
'columnDefs': [ {
  'targets': [0], /* column index */
  'orderable': false, /* true or false */
}]

//in view (action button and)
<button type="submit" class="btn btn-xs btn-primary" id="delete-selected">{{__('admin.delete selected')}}</button>
<form action="{{route('admin.incoming-messages.deleteArray')}}" method="post" id="delete_form">
  @csrf
<div class="inputs">

  </div>
</form>


//in view js
<script>
  $(document).on('click', '#select-all-row', function(e) {
    var table_id = $(this).data('table-id');
    if (this.checked) {
      $('#' + table_id)
        .find('tbody')
        .find('input.row-select')
        .each(function() {
        if (!this.checked) {
          $(this)
            .prop('checked', true)
            .change();
        }
      });
    } else {
      $('#' + table_id)
        .find('tbody')
        .find('input.row-select')
        .each(function() {
        if (this.checked) {
          $(this)
            .prop('checked', false)
            .change();
        }
      });
    }
  });


$(document).on('click', '#delete-selected', function(e){
  e.preventDefault();

  $ids = '';
  $html = '';
  $("input:checkbox:checked").each(function(){
    $ids += $(this).val() + ',';
    $html += '<input type="hidden" id="message_deleted" name="message[]" value="'+$(this).val()+'">';
  })
  $('.inputs').html($html);
  $('form#delete_form').submit() 
})
</script>

*** For laravel versions < 10 put this line
    $app->bind('path.public', function() {
        return __DIR__;
    });
just after this line

    $app = require_once __DIR__.'/../../{applicationname}/bootstrap/app.php';

****For laravel version >= 10 add this line
    $app->usePublicPath(__DIR__);
just after this line

    $app = require_once __DIR__.'/../../{applicationname}/bootstrap/app.php';
    Route::get('/notification', function () {
        $documentManagerFiles = DocumentManagerFile::where('ocr_project_id', 1)->where('revision', '>', 0 )->take(5)->get();
        // dd($documentManagerFiles);
        return (new DocumentManagerFileCreatedNotification($documentManagerFiles))
                    ->toMail(Auth::user());
    });
\DB::enableQueryLog(); // Enable query log

// Your Eloquent query executed by using get()

dd(\DB::getQueryLog()); // Show results of log
$tournament = app('App\Http\Controllers\TournamentController')->read_tournament_details($request, $tournament_id)->getData(true);
        
defineProps({
    leaves: {
        type: [],
    },
    fields: {
        type: ["Name", "Date From ", "Date To", "Status"],
    },
});
$areasexperiencia = $areasexperiencia;
function unique_key($array,$keyname){
$new_array = array();
foreach($array as $key=>$value){

if(!isset($new_array[$value[$keyname]])){
$new_array[$value[$keyname]] = $value;
}

}
$new_array = array_values($new_array);
return $new_array;
}
$unique_arr = unique_key($areasexperiencia,'nombre');
<?php

use App\Http\Controllers\admin\SiswaController;
use App\Http\Controllers\DspController;
use App\Http\Controllers\KelasController;
use App\Http\Controllers\PembayaranController;
use App\Http\Controllers\HomeController;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Route;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

// Route::get('/test', [SiswaController::class, 'store']);

// Route::get('/', function () {
//     return view('dashboard');
// });

// Route::get('/index-siswa', function () {
//     return view('petugas/index');
// });

// Route::get('/create-siswa', function () {
//     return view('../create-siswa');
// });

Auth::routes();

// Route::get('/', function () {
//     return view('auth.login');
// })->middleware(['guest']);

Route::middleware(['auth'])->group(function () {
    Route::get('index', [HomeController::class, 'index'])->middleware(['auth']);
    Route::get('/', function () {
        return view('dashboard');
    });
    Route::resource('pembayaran', PembayaranController::class);
    Route::get('pembayaran', [PembayaranController::class, 'index'])->name('pembayaran.index');
    Route::get('pembayaran-detail', [PembayaranController::class, 'detail'])->name('pembayaran.detail');
    Route::get('pembayaran/detail/{id}', [PembayaranController::class, 'detail_pembayaran'])->name('pembayaran.detail-pembayaran');

    Route::resource('siswa', SiswaController::class);
    Route::post('siswa/buat', [SiswaController::class, 'store'])->name('siswa.add');
    Route::get('siswa/ubah/{id}', [SiswaController::class, 'edit'])->name('siswa.ubah');

    Route::resource('kelas', KelasController::class);
    Route::get('kelas', [KelasController::class, 'index'])->name('kelas.index');
    Route::post('kelas/buat', [KelasController::class, 'store'])->name('kelas.add');
    Route::get('kelas/edit/{id}', [KelasController::class, 'edit'])->name('kelas.edits');

    Route::resource('dsp', DspController::class);
    // Route::get('dsp', [DspController::class, 'index'])->name('dsp.index');
    Route::post('dsp/buat', [DspController::class, 'store'])->name('dsp.add');
    Route::get('pembayaran-buat/{id}', [PembayaranController::class, 'proses_pembayaran'])->name('pembayaran.add');
});

// Route::get('/', function () {
//             return view('dashboard');
//         });
namespace App\Http\Controllers;

use App\Models\Dsp;
use App\Models\Kelas;
use App\Models\Siswa;
use App\Models\Pembayaran;
use Carbon\Carbon;
use Illuminate\Http\Request;

class PembayaranController extends Controller
{
    public function index(){
        $siswa = Siswa::orderBy('nama_siswa','asc')->get();
        $kelas = Kelas::all();
        $dsps = Dsp::all();
        // $kelas = Kelas::orderBy('nama_kelas')->get();


        return view('pembayaran.index', ['siswa' => $siswa, 'kelas' => $kelas, 'dsps'=>$dsps]);
    }

    public function detail(){
        $siswa = Siswa::orderBy('nama_siswa','asc')->get();
        // $kelas = Kelas::orderBy('nama_kelas')->get();
        $kelas = Kelas::all();
        return view('pembayaran.detail',['siswa' => $siswa, 'kelas' => $kelas]);
    }

    public function detail_pembayaran($id){
        $pembayaran = Siswa::find($id);
        return view('pembayaran.detail-pembayaran');

    }



    public function proses_pembayaran(Request $request, $id){
        $siswa = Siswa::findOrFail($id);
        // $dsps = Dsp::where('dsp_id',$siswa->dsp_id);

        // $pembayaran = Pembayaran::where("siswa_id", $siswa->id)->get();
        // $pembayaran = Pembayaran::where("siswa_id", $siswa->id)->get();

        // $request->validate([
        //     'tahun'=>'required',
        //     'jumlah_bayar'=>'required'
        // ]);

        // $totalPembayaran = Dsp::where("nominal", $siswa->id)->get();
        $tanggal = Carbon::now();

        $pembayaran = new Pembayaran();
        $pembayaran->petugas_id = 1;
        $pembayaran->siswa_id = $siswa->id;
        $pembayaran->nisn = $siswa->nisn;
        $pembayaran->tanggal_bayar = $tanggal;
        $pembayaran->bulan_bayar = $tanggal->format('m');
        $pembayaran->tahun_bayar = $tanggal->format('y');

        $pembayaran->jumlah_bayar = $siswa->dsp->nominal;

        $validasi['nominal'] = $siswa->dsp->nominal - $pembayaran->jumlah_bayar;
        $siswa->update($validasi);

        if ($siswa->nominal == 0) {
            $siswa->update(['status' => 'lunas']);
        }

        return redirect()->back();


    }
<div class="preview-item-content">
                                    <p class="preview-subject ellipsis mb-1 text-small">Change Password</p>
                                </div>
                            </a>
                            <div class="dropdown-divider"></div>
                            <a href="#" class="dropdown-item preview-item">
                                <div class="preview-thumbnail">
                                    <div class="preview-icon bg-dark rounded-circle">
                                        <i class="mdi mdi-calendar-today text-success"></i>
                                    </div>
                                </div>
                                <div class="preview-item-content">
                                    <p class="preview-subject ellipsis mb-1 text-small">To-do list</p>
                                </div>
                            </a>
                        </div>
                    </div>
                </li>
                <li class="nav-item menu-items">
                    <a class="nav-link" href="/">
                        <span class="menu-icon">
                            <i class="mdi mdi-home"></i>
                        </span>
                        <span class="menu-title">Dashboard</span>
                    </a>
                </li>
                <li class="nav-item menu-items">
                    <a class="nav-link" href="{{ route('siswa.index') }}">
                        <span class="menu-icon">
                            <i class="mdi mdi-account"></i>
                        </span>
                        <span class="menu-title">siswa</span>
                    </a>
                </li>
                <li class="nav-item menu-items">
                    <a class="nav-link" data-toggle="collapse" href="#ui-basic" aria-expanded="false"
                        aria-controls="ui-basic">
                        <span class="menu-icon">
                            <i class="mdi mdi-cart"></i>
                        </span>
                        <span class="menu-title">Pembayaran</span>
                        <i class="menu-arrow"></i>
                    </a>
                    <div class="collapse" id="ui-basic">
                        <ul class="nav flex-column sub-menu">
                            <li class="nav-item"> <a class="nav-link" href="{{ route('pembayaran.index') }}">Siswa</a></li>
                            <li class="nav-item"> <a class="nav-link" href="{{ route('pembayaran.detail') }}">Detail</a></li>
                        </ul>
                    </div>
                </li>
                <li class="nav-item menu-items">
                    <a class="nav-link" href="{{ route('kelas.index') }}">
                        <span class="menu-icon">
                            <i class="mdi mdi-table-large"></i>
                        </span>
                        <span class="menu-title">Kelas</span>
                    </a>
                </li>
                <li class="nav-item menu-items">
                    <a class="nav-link" href="{{route('dsp.index')}}">
                        <span class="menu-icon">
                            <i class="mdi mdi-chart-bar"></i>
                        </span>
                        <span class="menu-title">Harga DSP</span>
                    </a>
                </li>
                <li class="nav-item menu-items">
                    <a class="nav-link" href="pages/icons/mdi.html">
                        <span class="menu-icon">
                            <i class="mdi mdi-contacts"></i>
                        </span>
                        <span class="menu-title">Icons</span>
                    </a>
                </li>
            </ul>
        </nav>
<head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <title>DSPAID | SMKN4BDG</title>
    <!-- plugins:css -->
    <link rel="stylesheet" href="assets/vendors/mdi/css/materialdesignicons.min.css">
    <link rel="stylesheet" href="assets/vendors/css/vendor.bundle.base.css">
    <!-- endinject -->
    <!-- Plugin css for this page -->
    <link rel="stylesheet" href="assets/vendors/jvectormap/jquery-jvectormap.css">
    <link rel="stylesheet" href="assets/vendors/flag-icon-css/css/flag-icon.min.css">
    <link rel="stylesheet" href="assets/vendors/owl-carousel-2/owl.carousel.min.css">
    <link rel="stylesheet" href="assets/vendors/owl-carousel-2/owl.theme.default.min.css">
    <!-- End plugin css for this page -->
    <!-- inject:css -->
    <!-- endinject -->
    <!-- Layout styles -->
    <link rel="stylesheet" href="{{ asset('assets/css/style.css') }}">
    <!-- End layout styles -->
    <link rel="shortcut icon" href="{{ asset('assets/images/favicon.png') }}" />
    <link rel="shortcut icon" href="assets/fontawesome-free-6.3.0-web/css" />
    <link rel="stylesheet" href="path/to/fontawesome/css/all.min.css">
</head>

<body>
    <div class="container-scroller">
        <!-- partial:partials/_sidebar.html -->
        <nav class="sidebar sidebar-offcanvas" id="sidebar">
            <div class="sidebar-brand-wrapper d-none d-lg-flex align-items-center justify-content-center fixed-top">
                <a class="sidebar-brand brand-logo" href="/index">
                    <h1>DSPAID</h1>
                </a>
                <a class="sidebar-brand brand-logo-mini" href="index.html"><img src="assets/images/logo-mini.svg"
                        alt="logo" /></a>
            </div>
            <ul class="nav">
                <li class="nav-item profile">
                    <div class="profile-desc">
                        <div class="profile-pic">
                            <div class="count-indicator">
                                <img class="img-xs rounded-circle " src="assets/images/faces/face15.jpg" alt="">
                                <span class="count bg-success"></span>
                            </div>
                            <div class="profile-name">
                                <h5 class="mb-0 font-weight-normal">Henry Klein</h5>
                                <span>Gold Member</span>
                            </div>
                        </div>
                        <a href="#" id="profile-dropdown" data-toggle="dropdown"><i
                                class="mdi mdi-dots-vertical"></i></a>
                        <div class="dropdown-menu dropdown-menu-right sidebar-dropdown preview-list"
                            aria-labelledby="profile-dropdown">
                            <a href="#" class="dropdown-item preview-item">
                                <div class="preview-thumbnail">
                                    <div class="preview-icon bg-dark rounded-circle">
                                        <i class="mdi mdi-settings text-primary"></i>
                                    </div>
                                </div>
                                <div class="preview-item-content">
                                    <p class="preview-subject ellipsis mb-1 text-small">Account settings</p>
                                </div>
                            </a>
                            <div class="dropdown-divider"></div>
                            <a href="#" class="dropdown-item preview-item">
                                <div class="preview-thumbnail">
                                    <div class="preview-icon bg-dark rounded-circle">
                                        <i class="mdi mdi-onepassword  text-info"></i>
                                    </div>
<head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <title>DSPAID | SMKN4BDG</title>
    <!-- plugins:css -->
    <link rel="stylesheet" href="assets/vendors/mdi/css/materialdesignicons.min.css">
    <link rel="stylesheet" href="assets/vendors/css/vendor.bundle.base.css">
    <!-- endinject -->
    <!-- Plugin css for this page -->
    <link rel="stylesheet" href="assets/vendors/jvectormap/jquery-jvectormap.css">
    <link rel="stylesheet" href="assets/vendors/flag-icon-css/css/flag-icon.min.css">
    <link rel="stylesheet" href="assets/vendors/owl-carousel-2/owl.carousel.min.css">
    <link rel="stylesheet" href="assets/vendors/owl-carousel-2/owl.theme.default.min.css">
    <!-- End plugin css for this page -->
    <!-- inject:css -->
    <!-- endinject -->
    <!-- Layout styles -->
    <link rel="stylesheet" href="{{ asset('assets/css/style.css') }}">
    <!-- End layout styles -->
    <link rel="shortcut icon" href="{{ asset('assets/images/favicon.png') }}" />
    <link rel="shortcut icon" href="assets/fontawesome-free-6.3.0-web/css" />
    <link rel="stylesheet" href="path/to/fontawesome/css/all.min.css">
</head>

<body>
    <div class="container-scroller">
        <!-- partial:partials/_sidebar.html -->
        <nav class="sidebar sidebar-offcanvas" id="sidebar">
            <div class="sidebar-brand-wrapper d-none d-lg-flex align-items-center justify-content-center fixed-top">
                <a class="sidebar-brand brand-logo" href="/index">
                    <h1>DSPAID</h1>
                </a>
                <a class="sidebar-brand brand-logo-mini" href="index.html"><img src="assets/images/logo-mini.svg"
                        alt="logo" /></a>
            </div>
            <ul class="nav">
                <li class="nav-item profile">
                    <div class="profile-desc">
                        <div class="profile-pic">
                            <div class="count-indicator">
                                <img class="img-xs rounded-circle " src="assets/images/faces/face15.jpg" alt="">
                                <span class="count bg-success"></span>
                            </div>
                            <div class="profile-name">
                                <h5 class="mb-0 font-weight-normal">Henry Klein</h5>
                                <span>Gold Member</span>
                            </div>
                        </div>
                        <a href="#" id="profile-dropdown" data-toggle="dropdown"><i
                                class="mdi mdi-dots-vertical"></i></a>
                        <div class="dropdown-menu dropdown-menu-right sidebar-dropdown preview-list"
                            aria-labelledby="profile-dropdown">
                            <a href="#" class="dropdown-item preview-item">
                                <div class="preview-thumbnail">
                                    <div class="preview-icon bg-dark rounded-circle">
                                        <i class="mdi mdi-settings text-primary"></i>
                                    </div>
                                </div>
                                <div class="preview-item-content">
                                    <p class="preview-subject ellipsis mb-1 text-small">Account settings</p>
                                </div>
                            </a>
                            <div class="dropdown-divider"></div>
                            <a href="#" class="dropdown-item preview-item">
                                <div class="preview-thumbnail">
                                    <div class="preview-icon bg-dark rounded-circle">
                                        <i class="mdi mdi-onepassword  text-info"></i>
                                    </div>
                                </div>
                                <div class="preview-item-content">
                                    <p class="preview-subject ellipsis mb-1 text-small">Change Password</p>
                                </div>
                            </a>
                            <div class="dropdown-divider"></div>
                            <a href="#" class="dropdown-item preview-item">
                                <div class="preview-thumbnail">
                                    <div class="preview-icon bg-dark rounded-circle">
                                        <i class="mdi mdi-calendar-today text-success"></i>
                                    </div>
                                </div>
                                <div class="preview-item-content">
                                    <p class="preview-subject ellipsis mb-1 text-small">To-do list</p>
                                </div>
                            </a>
                        </div>
                    </div>
                </li>
                <li class="nav-item menu-items">
                    <a class="nav-link" href="/">
                        <span class="menu-icon">
                            <i class="mdi mdi-home"></i>
                        </span>
                        <span class="menu-title">Dashboard</span>
                    </a>
                </li>
                <li class="nav-item menu-items">
                    <a class="nav-link" href="{{ route('siswa.index') }}">
                        <span class="menu-icon">
                            <i class="mdi mdi-account"></i>
                        </span>
                        <span class="menu-title">siswa</span>
                    </a>
                </li>
<head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <title>DSPAID | SMKN4BDG</title>
    <!-- plugins:css -->
    <link rel="stylesheet" href="assets/vendors/mdi/css/materialdesignicons.min.css">
    <link rel="stylesheet" href="assets/vendors/css/vendor.bundle.base.css">
    <!-- endinject -->
    <!-- Plugin css for this page -->
    <link rel="stylesheet" href="assets/vendors/jvectormap/jquery-jvectormap.css">
    <link rel="stylesheet" href="assets/vendors/flag-icon-css/css/flag-icon.min.css">
    <link rel="stylesheet" href="assets/vendors/owl-carousel-2/owl.carousel.min.css">
    <link rel="stylesheet" href="assets/vendors/owl-carousel-2/owl.theme.default.min.css">
    <!-- End plugin css for this page -->
    <!-- inject:css -->
    <!-- endinject -->
    <!-- Layout styles -->
    <link rel="stylesheet" href="{{ asset('assets/css/style.css') }}">
    <!-- End layout styles -->
    <link rel="shortcut icon" href="{{ asset('assets/images/favicon.png') }}" />
    <link rel="shortcut icon" href="assets/fontawesome-free-6.3.0-web/css" />
    <link rel="stylesheet" href="path/to/fontawesome/css/all.min.css">
</head>

<body>
    <div class="container-scroller">
        <!-- partial:partials/_sidebar.html -->
        <nav class="sidebar sidebar-offcanvas" id="sidebar">
            <div class="sidebar-brand-wrapper d-none d-lg-flex align-items-center justify-content-center fixed-top">
                <a class="sidebar-brand brand-logo" href="/index">
                    <h1>DSPAID</h1>
                </a>
                <a class="sidebar-brand brand-logo-mini" href="index.html"><img src="assets/images/logo-mini.svg"
                        alt="logo" /></a>
            </div>
            <ul class="nav">
                <li class="nav-item profile">
                    <div class="profile-desc">
                        <div class="profile-pic">
                            <div class="count-indicator">
                                <img class="img-xs rounded-circle " src="assets/images/faces/face15.jpg" alt="">
                                <span class="count bg-success"></span>
                            </div>
                            <div class="profile-name">
                                <h5 class="mb-0 font-weight-normal">Henry Klein</h5>
                                <span>Gold Member</span>
                            </div>
                        </div>
                        <a href="#" id="profile-dropdown" data-toggle="dropdown"><i
                                class="mdi mdi-dots-vertical"></i></a>
                        <div class="dropdown-menu dropdown-menu-right sidebar-dropdown preview-list"
                            aria-labelledby="profile-dropdown">
                            <a href="#" class="dropdown-item preview-item">
                                <div class="preview-thumbnail">
                                    <div class="preview-icon bg-dark rounded-circle">
                                        <i class="mdi mdi-settings text-primary"></i>
                                    </div>
                                </div>
                                <div class="preview-item-content">
                                    <p class="preview-subject ellipsis mb-1 text-small">Account settings</p>
                                </div>
                            </a>
                            <div class="dropdown-divider"></div>
                            <a href="#" class="dropdown-item preview-item">
                                <div class="preview-thumbnail">
                                    <div class="preview-icon bg-dark rounded-circle">
                                        <i class="mdi mdi-onepassword  text-info"></i>
                                    </div>
                                </div>
                                <div class="preview-item-content">
                                    <p class="preview-subject ellipsis mb-1 text-small">Change Password</p>
                                </div>
                            </a>
                            <div class="dropdown-divider"></div>
                            <a href="#" class="dropdown-item preview-item">
                                <div class="preview-thumbnail">
                                    <div class="preview-icon bg-dark rounded-circle">
                                        <i class="mdi mdi-calendar-today text-success"></i>
                                    </div>
                                </div>
                                <div class="preview-item-content">
                                    <p class="preview-subject ellipsis mb-1 text-small">To-do list</p>
                                </div>
                            </a>
                        </div>
                    </div>
                </li>
                <li class="nav-item menu-items">
                    <a class="nav-link" href="/">
                        <span class="menu-icon">
                            <i class="mdi mdi-home"></i>
                        </span>
                        <span class="menu-title">Dashboard</span>
                    </a>
                </li>
                <li class="nav-item menu-items">
                    <a class="nav-link" href="{{ route('siswa.index') }}">
                        <span class="menu-icon">
                            <i class="mdi mdi-account"></i>
                        </span>
                        <span class="menu-title">siswa</span>
                    </a>
                </li>
                <li class="nav-item menu-items">
                    <a class="nav-link" data-toggle="collapse" href="#ui-basic" aria-expanded="false"
                        aria-controls="ui-basic">
                        <span class="menu-icon">
                            <i class="mdi mdi-cart"></i>
                        </span>
                        <span class="menu-title">Pembayaran</span>
                        <i class="menu-arrow"></i>
                    </a>
                    <div class="collapse" id="ui-basic">
                        <ul class="nav flex-column sub-menu">
                            <li class="nav-item"> <a class="nav-link" href="{{ route('pembayaran.index') }}">Siswa</a></li>
                            <li class="nav-item"> <a class="nav-link" href="{{ route('pembayaran.detail') }}">Detail</a></li>
                        </ul>
                    </div>
                </li>
                <li class="nav-item menu-items">
                    <a class="nav-link" href="{{ route('kelas.index') }}">
                        <span class="menu-icon">
                            <i class="mdi mdi-table-large"></i>
                        </span>
                        <span class="menu-title">Kelas</span>
                    </a>
                </li>
                <li class="nav-item menu-items">
                    <a class="nav-link" href="{{route('dsp.index')}}">
                        <span class="menu-icon">
                            <i class="mdi mdi-chart-bar"></i>
                        </span>
                        <span class="menu-title">Harga DSP</span>
                    </a>
                </li>
                <li class="nav-item menu-items">
                    <a class="nav-link" href="pages/icons/mdi.html">
                        <span class="menu-icon">
                            <i class="mdi mdi-contacts"></i>
                        </span>
                        <span class="menu-title">Icons</span>
                    </a>
                </li>
            </ul>
        </nav>
<head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <title>DSPAID | SMKN4BDG</title>
    <!-- plugins:css -->
    <link rel="stylesheet" href="assets/vendors/mdi/css/materialdesignicons.min.css">
    <link rel="stylesheet" href="assets/vendors/css/vendor.bundle.base.css">
    <!-- endinject -->
    <!-- Plugin css for this page -->
    <link rel="stylesheet" href="assets/vendors/jvectormap/jquery-jvectormap.css">
    <link rel="stylesheet" href="assets/vendors/flag-icon-css/css/flag-icon.min.css">
    <link rel="stylesheet" href="assets/vendors/owl-carousel-2/owl.carousel.min.css">
    <link rel="stylesheet" href="assets/vendors/owl-carousel-2/owl.theme.default.min.css">
    <!-- End plugin css for this page -->
    <!-- inject:css -->
    <!-- endinject -->
    <!-- Layout styles -->
    <link rel="stylesheet" href="{{ asset('assets/css/style.css') }}">
    <!-- End layout styles -->
    <link rel="shortcut icon" href="{{ asset('assets/images/favicon.png') }}" />
    <link rel="shortcut icon" href="assets/fontawesome-free-6.3.0-web/css" />
    <link rel="stylesheet" href="path/to/fontawesome/css/all.min.css">
</head>

<body>
    <div class="container-scroller">
        <!-- partial:partials/_sidebar.html -->
        <nav class="sidebar sidebar-offcanvas" id="sidebar">
            <div class="sidebar-brand-wrapper d-none d-lg-flex align-items-center justify-content-center fixed-top">
                <a class="sidebar-brand brand-logo" href="/index">
                    <h1>DSPAID</h1>
                </a>
                <a class="sidebar-brand brand-logo-mini" href="index.html"><img src="assets/images/logo-mini.svg"
                        alt="logo" /></a>
            </div>
            <ul class="nav">
                <li class="nav-item profile">
                    <div class="profile-desc">
                        <div class="profile-pic">
                            <div class="count-indicator">
                                <img class="img-xs rounded-circle " src="assets/images/faces/face15.jpg" alt="">
                                <span class="count bg-success"></span>
                            </div>
                            <div class="profile-name">
                                <h5 class="mb-0 font-weight-normal">Henry Klein</h5>
                                <span>Gold Member</span>
                            </div>
                        </div>
                        <a href="#" id="profile-dropdown" data-toggle="dropdown"><i
                                class="mdi mdi-dots-vertical"></i></a>
                        <div class="dropdown-menu dropdown-menu-right sidebar-dropdown preview-list"
                            aria-labelledby="profile-dropdown">
                            <a href="#" class="dropdown-item preview-item">
                                <div class="preview-thumbnail">
                                    <div class="preview-icon bg-dark rounded-circle">
                                        <i class="mdi mdi-settings text-primary"></i>
                                    </div>
                                </div>
                                <div class="preview-item-content">
                                    <p class="preview-subject ellipsis mb-1 text-small">Account settings</p>
                                </div>
                            </a>
                            <div class="dropdown-divider"></div>
                            <a href="#" class="dropdown-item preview-item">
                                <div class="preview-thumbnail">
                                    <div class="preview-icon bg-dark rounded-circle">
                                        <i class="mdi mdi-onepassword  text-info"></i>
                                    </div>
                                </div>
                                <div class="preview-item-content">
                                    <p class="preview-subject ellipsis mb-1 text-small">Change Password</p>
                                </div>
                            </a>
                            <div class="dropdown-divider"></div>
                            <a href="#" class="dropdown-item preview-item">
                                <div class="preview-thumbnail">
                                    <div class="preview-icon bg-dark rounded-circle">
                                        <i class="mdi mdi-calendar-today text-success"></i>
                                    </div>
                                </div>
                                <div class="preview-item-content">
                                    <p class="preview-subject ellipsis mb-1 text-small">To-do list</p>
                                </div>
                            </a>
                        </div>
                    </div>
                </li>
                <li class="nav-item menu-items">
                    <a class="nav-link" href="/">
                        <span class="menu-icon">
                            <i class="mdi mdi-home"></i>
                        </span>
                        <span class="menu-title">Dashboard</span>
                    </a>
                </li>
                <li class="nav-item menu-items">
                    <a class="nav-link" href="{{ route('siswa.index') }}">
                        <span class="menu-icon">
                            <i class="mdi mdi-account"></i>
                        </span>
                        <span class="menu-title">siswa</span>
                    </a>
                </li>
                <li class="nav-item menu-items">
                    <a class="nav-link" data-toggle="collapse" href="#ui-basic" aria-expanded="false"
                        aria-controls="ui-basic">
                        <span class="menu-icon">
                            <i class="mdi mdi-cart"></i>
                        </span>
                        <span class="menu-title">Pembayaran</span>
                        <i class="menu-arrow"></i>
                    </a>
                    <div class="collapse" id="ui-basic">
                        <ul class="nav flex-column sub-menu">
                            <li class="nav-item"> <a class="nav-link" href="{{ route('pembayaran.index') }}">Siswa</a></li>
                            <li class="nav-item"> <a class="nav-link" href="{{ route('pembayaran.detail') }}">Detail</a></li>
                        </ul>
                    </div>
                </li>
                <li class="nav-item menu-items">
                    <a class="nav-link" href="{{ route('kelas.index') }}">
                        <span class="menu-icon">
                            <i class="mdi mdi-table-large"></i>
                        </span>
                        <span class="menu-title">Kelas</span>
                    </a>
                </li>
                <li class="nav-item menu-items">
                    <a class="nav-link" href="{{route('dsp.index')}}">
                        <span class="menu-icon">
                            <i class="mdi mdi-chart-bar"></i>
                        </span>
                        <span class="menu-title">Harga DSP</span>
                    </a>
                </li>
                <li class="nav-item menu-items">
                    <a class="nav-link" href="pages/icons/mdi.html">
                        <span class="menu-icon">
                            <i class="mdi mdi-contacts"></i>
                        </span>
                        <span class="menu-title">Icons</span>
                    </a>
                </li>
            </ul>
        </nav>
        <!-- partial -->
        <div class="container-fluid page-body-wrapper">
            <!-- partial:partials/_navbar.html -->
            <nav class="navbar p-0 fixed-top d-flex flex-row">
                <div class="navbar-brand-wrapper d-flex d-lg-none align-items-center justify-content-center">
                    <a class="navbar-brand brand-logo-mini" href="index.html"><img src="assets/images/logo-mini.svg"
                            alt="logo" /></a>
                </div>
                <div class="navbar-menu-wrapper flex-grow d-flex align-items-stretch">
                    <button class="navbar-toggler navbar-toggler align-self-center" type="button"
                        data-toggle="minimize">
                        <span class="mdi mdi-menu"></span>
                    </button>
                    <ul class="navbar-nav w-100">
                        <li class="nav-item w-100">
                            <form class="nav-link mt-2 mt-md-0 d-none d-lg-flex search">
                                <input type="text" class="form-control" placeholder="Search products">
                            </form>
                        </li>
                    </ul>
                    <ul class="navbar-nav navbar-nav-right">
                        <li class="nav-item dropdown d-none d-lg-block">
                            <div class="dropdown-menu dropdown-menu-right navbar-dropdown preview-list"
                                aria-labelledby="createbuttonDropdown">
                                <h6 class="p-3 mb-0">Projects</h6>
                                <div class="dropdown-divider"></div>
                                <a class="dropdown-item preview-item">
                                    <div class="preview-thumbnail">
                                        <div class="preview-icon bg-dark rounded-circle">
                                            <i class="mdi mdi-file-outline text-primary"></i>
                                        </div>
                                    </div>
                                    <div class="preview-item-content">
                                        <p class="preview-subject ellipsis mb-1">Software Development</p>
                                    </div>
                                </a>
                                <div class="dropdown-divider"></div>
                                <a class="dropdown-item preview-item">
                                    <div class="preview-thumbnail">
                                        <div class="preview-icon bg-dark rounded-circle">
                                            <i class="mdi mdi-web text-info"></i>
                                        </div>
                                    </div>
                                    <div class="preview-item-content">
                                        <p class="preview-subject ellipsis mb-1">UI Development</p>
                                    </div>
                                </a>
                                <div class="dropdown-divider"></div>
                                <a class="dropdown-item preview-item">
                                    <div class="preview-thumbnail">
                                        <div class="preview-icon bg-dark rounded-circle">
                                            <i class="mdi mdi-layers text-danger"></i>
                                        </div>
                                    </div>
                                    <div class="preview-item-content">
                                        <p class="preview-subject ellipsis mb-1">Software Testing</p>
                                    </div>
                                </a>
                                <div class="dropdown-divider"></div>
                                <p class="p-3 mb-0 text-center">See all projects</p>
                            </div>
                        </li>
                        <li class="nav-item nav-settings d-none d-lg-block">
                            <a class="nav-link" href="#">
                                <i class="mdi mdi-view-grid"></i>
                            </a>
                        </li>
                        <li class="nav-item dropdown border-left">
                            <a class="nav-link count-indicator dropdown-toggle" id="messageDropdown" href="#"
                                data-toggle="dropdown" aria-expanded="false">
                                <i class="mdi mdi-email"></i>
                                <span class="count bg-success"></span>
                            </a>
                            <div class="dropdown-menu dropdown-menu-right navbar-dropdown preview-list"
                                aria-labelledby="messageDropdown">
                                <h6 class="p-3 mb-0">Messages</h6>
                                <div class="dropdown-divider"></div>
                                <a class="dropdown-item preview-item">
                                    <div class="preview-thumbnail">
                                        <img src="assets/images/faces/face4.jpg" alt="image"
                                            class="rounded-circle profile-pic">
                                    </div>
                                    <div class="preview-item-content">
                                        <p class="preview-subject ellipsis mb-1">Mark send you a message</p>
                                        <p class="text-muted mb-0"> 1 Minutes ago </p>
                                    </div>
                                </a>
                                <div class="dropdown-divider"></div>
                                <a class="dropdown-item preview-item">
                                    <div class="preview-thumbnail">
                                        <img src="assets/images/faces/face2.jpg" alt="image"
                                            class="rounded-circle profile-pic">
                                    </div>
                                    <div class="preview-item-content">
                                        <p class="preview-subject ellipsis mb-1">Cregh send you a message</p>
                                        <p class="text-muted mb-0"> 15 Minutes ago </p>
                                    </div>
                                </a>
                                <div class="dropdown-divider"></div>
                                <a class="dropdown-item preview-item">
                                    <div class="preview-thumbnail">
                                        <img src="assets/images/faces/face3.jpg" alt="image"
                                            class="rounded-circle profile-pic">
                                    </div>
                                    <div class="preview-item-content">
                                        <p class="preview-subject ellipsis mb-1">Profile picture updated</p>
                                        <p class="text-muted mb-0"> 18 Minutes ago </p>
                                    </div>
                                </a>
                                <div class="dropdown-divider"></div>
                                <p class="p-3 mb-0 text-center">4 new messages</p>
                            </div>
                        </li>
                        <li class="nav-item dropdown border-left">
                            <a class="nav-link count-indicator dropdown-toggle" id="notificationDropdown"
                                href="#" data-toggle="dropdown">
                                <i class="mdi mdi-bell"></i>
                                <span class="count bg-danger"></span>
                            </a>
                            <div class="dropdown-menu dropdown-menu-right navbar-dropdown preview-list"
                                aria-labelledby="notificationDropdown">
                                <h6 class="p-3 mb-0">Notifications</h6>
                                <div class="dropdown-divider"></div>
                                <a class="dropdown-item preview-item">
                                    <div class="preview-thumbnail">
                                        <div class="preview-icon bg-dark rounded-circle">
                                            <i class="mdi mdi-calendar text-success"></i>
                                        </div>
                                    </div>
                                    <div class="preview-item-content">
                                        <p class="preview-subject mb-1">Event today</p>
                                        <p class="text-muted ellipsis mb-0"> Just a reminder that you have an event
                                            today </p>
                                    </div>
                                </a>
                                <div class="dropdown-divider"></div>
                                <a class="dropdown-item preview-item">
                                    <div class="preview-thumbnail">
                                        <div class="preview-icon bg-dark rounded-circle">
                                            <i class="mdi mdi-settings text-danger"></i>
                                        </div>
                                    </div>
                                    <div class="preview-item-content">
                                        <p class="preview-subject mb-1">Settings</p>
                                        <p class="text-muted ellipsis mb-0"> Update dashboard </p>
                                    </div>
                                </a>
                                <div class="dropdown-divider"></div>
                                <a class="dropdown-item preview-item">
                                    <div class="preview-thumbnail">
                                        <div class="preview-icon bg-dark rounded-circle">
                                            <i class="mdi mdi-link-variant text-warning"></i>
                                        </div>
                                    </div>
                                    <div class="preview-item-content">
                                        <p class="preview-subject mb-1">Launch Admin</p>
                                        <p class="text-muted ellipsis mb-0"> New admin wow! </p>
                                    </div>
                                </a>
                                <div class="dropdown-divider"></div>
                                <p class="p-3 mb-0 text-center">See all notifications</p>
                            </div>
                        </li>
                        <li class="nav-item dropdown">
                            <a class="nav-link" id="profileDropdown" href="#" data-toggle="dropdown">
                                <div class="navbar-profile">
                                    <img class="img-xs rounded-circle" src="../../assets/images/faces/face15.jpg"
                                        alt="">
                                    <p class="mb-0 d-none d-sm-block navbar-profile-name">Henry Klein</p>
                                    <i class="mdi mdi-menu-down d-none d-sm-block"></i>
                                </div>
                            </a>
                            <div class="dropdown-menu dropdown-menu-right navbar-dropdown preview-list"
                                aria-labelledby="profileDropdown">
                                <h6 class="p-3 mb-0">Profile</h6>
                                <div class="dropdown-divider"></div>
                                <a class="dropdown-item preview-item">
                                    <div class="preview-thumbnail">
                                        <div class="preview-icon bg-dark rounded-circle">
                                            <i class="mdi mdi-settings text-success"></i>
                                        </div>
                                    </div>
                                    <div class="preview-item-content">
                                        <p class="preview-subject mb-1">Settings</p>
                                    </div>
                                </a>
                                <div class="dropdown-divider"></div>
                                <a href="{{ route('logout') }}"
                                    onclick="event.preventDefault();
                              document.getElementById('logout-form').submit();"
                                    class="dropdown-item preview-item">
                                    <div class="preview-thumbnail">
                                        <div class="preview-icon bg-dark rounded-circle">
                                            <i class="mdi mdi-logout text-danger"></i>
                                        </div>
                                    </div>
                                    <div class="preview-item-content">
                                        <p class="preview-subject mb-1">Log out</p>
                                    </div>
                                </a>
                                <form id="logout-form" action="{{ route('logout') }}" method="POST" class="d-none">
                                    @csrf
                                </form>
                                <div class="dropdown-divider"></div>
                                <p class="p-3 mb-0 text-center">Advanced settings</p>
                            </div>
                        </li>
                    </ul>
                    <button class="navbar-toggler navbar-toggler-right d-lg-none align-self-center" type="button"
                        data-toggle="offcanvas">
                        <span class="mdi mdi-format-line-spacing"></span>
                    </button>
                </div>
            </nav>
            <div class="main-panel">
                <div class="content-wrapper">
                    @yield('content')
                </div>
            </div>
            <!-- partial -->
        </div>
        <!-- content-wrapper ends -->

    </div>
    <!-- main-panel ends -->
    </div>

    <!-- page-body-wrapper ends -->
    </div>
    <!-- container-scroller -->
    <!-- plugins:js -->
    <script src="assets/vendors/js/vendor.bundle.base.js"></script>
    <!-- endinject -->
    <!-- Plugin js for this page -->
    <script src="assets/vendors/chart.js/Chart.min.js"></script>
    <script src="assets/vendors/progressbar.js/progressbar.min.js"></script>
    <script src="assets/vendors/jvectormap/jquery-jvectormap.min.js"></script>
    <script src="assets/vendors/jvectormap/jquery-jvectormap-world-mill-en.js"></script>
    <script src="assets/vendors/owl-carousel-2/owl.carousel.min.js"></script>
    <!-- End plugin js for this page -->
    <!-- inject:js -->
    <script src="assets/js/off-canvas.js"></script>
    <script src="assets/js/hoverable-collapse.js"></script>
    <script src="assets/js/misc.js"></script>
    <script src="assets/js/settings.js"></script>
    <script src="assets/js/todolist.js"></script>
    <!-- endinject -->
    <!-- Custom js for this page -->
    <script src="assets/js/dashboard.js"></script>
    <!-- End custom js for this page -->
</body>

</html>
	
<a href="{{ request()->url() }}">Clear Parameters</a>
public function handle()
{
    $first_name = $this->ask('What is the first name?');
    $last_name = $this->ask('What is the last name?');
    $email = $this->ask('What is the email address?');
    $password = $this->secret('What is the password?');

    AdminUser::create([
        'first_name' => $first_name,
        'last_name' => $last_name,
        'email' => $email,
        'password' => bcrypt($password)
    ]);

    $this->info("User $first_name $last_name was created");
}
// Display Object or Array
public function oa($model)
{
    if (gettype($model) === 'object') {
        dump(get_class($model));
        dump($model->toArray());
    } else {
        dump(gettype($model));
        dump($model);
    }
}
// Display string
public function s($model)
{
    dump($model);
}
In terminal excute the following command
1. composer require hardevine/shoppingcart
Then in app.php in config folder write the following code in providers array
Gloudemans\Shoppingcart\ShoppingcartServiceProvider::class,
 and in aliases array
 'Cart' => Gloudemans\Shoppingcart\Facades\Cart::class,
2. Now in terminal execute the following command
php artisan vendor:publish --provider="Gloudemans\Shoppingcart\ShoppingcartServiceProvider" --tag="config"
3. Now in ShopComponent class file at head write the following
use Cart;
then in ShopComponent write the following function
 public function store($product_id, $product_name, $product_price)
    {
        Cart::add($product_id, $product_name, 1, $product_price)->associate('\App\Models\Product');
        session()->flash('success_message', 'Items added in Cart');
        return redirect()->route('cart.index');
    }
4. Now in shopcomponent blade file, in Add To Cart a link add the following code wire code
 
<a aria-label="Add To Cart" class="action-btn hover-up" href="#" wire:click.prevent="store('{{$product->id}}', '{{$product->name}}', '{{$product->regular_price}}')"><i class="fi-rs-shopping-bag-add"></i></a>
5. Now in cart-component blade file 
in the table after <tbody> start write the following code
 @if (Cart::count()>0)
    <tr>
     <td class="image product-thumbnail"><img src="{{asset('assets/imgs/shop/product-1-2.jpg')}}" alt="#">
       </td>
     <td class="product-des product-name">
       <h5 class="product-name"><a href="product-details.html">J.Crew Mercantile Women's Short-Sleeve</a></h5>
       <p class="font-xs">Maboriosam in a tonto nesciung eget<br> distingy magndapibus </p>
      </td>
        <td class="price" data-title="Price"><span>$65.00 </span>
      </td>
      <td class="text-center" data-title="Stock">
        <div class="detail-qty border radius  m-auto">
         <a href="#" class="qty-down"><i class="fi-rs-angle-small-down"></i></a>
          <span class="qty-val">1</span>
         <a href="#" class="qty-up"><i class="fi-rs-angle-small-up"></i></a>
        </div>
      </td>
        
	  <td class="text-right" data-title="Cart">
         <span>$65.00 </span>
           </td>
           <td class="action" data-title="Remove"><a href="#" class="text-muted"><i class="fi-rs-trash"></i></a></td>
           </tr>
          @else
           <p>No Item In Cart</p>
         @endif

6. Now use following items to show cart items
  @foreach (Cart::content() as $item)
	<tr>
     <td class="image product-thumbnail"><img src="{{asset('assets/imgs/shop/product-')}}{{$item->model->id}}-1.jpg" alt="#"></td>
      <td class="product-des product-name">
       <h5 class="product-name"><a href="product-details.html">{{$item->model->name}}</a></h5>
      </td>
       <td class="price" data-title="Price"><span>${{$item->model->regular_price}} </span></td>
         <td class="text-center" data-title="Stock">
           <div class="detail-qty border radius  m-auto">
            <a href="#" class="qty-down"><i class="fi-rs-angle-small-down"></i></a>
            <span class="qty-val">1</span>
           <a href="#" class="qty-up"><i class="fi-rs-angle-small-up"></i></a>
         </div>
         </td>
        <td class="text-right" data-title="Cart">
         <span>${{$item->subtotal}} </span>
        </td>
         <td class="action" data-title="Remove"><a href="#" class="text-muted"><i class="fi-rs-trash"></i></a></td>
          </tr>
@endforeach
7. Now in cart totals
 <div class="table-responsive">
   <table class="table">
   <tbody>
      <tr>
       <td class="cart_total_label">Cart Subtotal</td>
       <td class="cart_total_amount"><span class="font-lg fw-900 text-brand">${{Cart::subtotal()}}</span></td>
      </tr>
      <tr>
       <td class="cart_total_label">Tax</td>
        <td class="cart_total_amount"><span class="font-lg fw-900 text-brand">${{Cart::tax()}}</span></td>
       </tr>
        <tr>
       <td class="cart_total_label">Shipping</td>
       <td class="cart_total_amount"> <i class="ti-gift mr-5"></i> Free Shipping</td>
       </tr>
        <tr>
 <td class="cart_total_label">Total</td>
 <td class="cart_total_amount"><strong><span class="font-xl fw-900 text-brand">${{Cart::total()}}</span></strong></td>
  </tr>
 </tbody>
 </table>
 </div>
after  @foreach ($products as $product)
	@endforeach
use:

{{$products->onEachSide(1)->links('pagination::bootstrap-4')}}
use Livewire\withPagination;
then in component main function write
 use withPagination;
    public function render()
    {
        $products = Product::paginate(12);
        return view('livewire.shop-component', compact('products'));
    }
3. You can pic images from asset folders in blade file by using the following code
<img class="default-img" src="{{asset('assets/imgs/shop/product-')}}{{$product->id}}-1.jpg" alt="">
<img class="hover-img" src="{{asset('assets/imgs/shop/product-')}}{{$product->id}}-2.jpg" alt="">
1. First make a factory by using the following code 
php artisan make:factory CategoryFactory -model=Category
2. Go to the CategogyFatory file in factories folder and write the following code
 $category_name = $this->faker->unique()->words($nb=2, $asText = true);
        $slug = Str::slug($category_name, '-');
        return [
            'name' => $category_name,
            'slug' => $slug
        ];
3. You can use Str class as on top
  use Illuminate\Support\Str;
4. Now go to the DatabaseSeeder and write the following code in the run function
 \App\Models\Category::factory(6)->create();
5. use the following command
php artisan db:seed
6. You can make as many factories and call in the databaseseeder file and use the factories
Thanks!
1. git reset HEAD --hard
2. git clean -fdx
3. git status
4. git pull
rename the app.blade.php file if exists for temporary
1. composer require laravel/breeze --dev
2. php artisan breeze:install
Delete the new built app.blade.php file and change the name of the file file in step 1 to again app.blade.php
Now add the following code in users file migration after password
  $table->string('utype')->default('USR')->comment('ADM for admin and USR for User');
3. now run php artisan migrate
4. npm install
5. npm run build
6. Now we can change or use login/logout/Register routes routes available 

 @auth
    <ul>                                
      <li><i class="fi-rs-key"></i>  {{Auth::user()->name}}  / 
        <form method="POST" action="{{route('logout')}}">
          @csrf
          <a href="{{route('logout')}}" onclick="event.preventDefault(); 			    					this.closest('form').submit();">Logout</a>
        </form>
       </li>
    </ul>
 @else
     <ul>                                
       <li><i class="fi-rs-key"></i>
		  <a href="{{route('login')}}">Log In </a>  / <a href="{{route('register')}}">Sign Up</a>		</li>
     </ul>
 @endif

7. the make middleware for that
php artisan make:middleware AdminMiddleware
8. then open the the middle file in http/middleware
9. now add the following code inhandle function

if (Auth::user()->utype === 'ADM') {
   return $next($request);
 }
 else{
 session()->flush();
 return redirect()->route('login');
 }
10. Use the following code in the header of middleware file to use auth
use Illuminate\Support\Facades\Auth;
11. Now open kernel.php file in http folder and add the following code in routemiddleware
'authadmin' => \App\Http\Middleware\AdminMiddleware::class,
  12. Now open the file routeservice provider in providers folder and delete the dashboard word in the line no 20 HOME
13. Now make two componnts use the following commands
php artisan make:livewire Admin/AdminDashboardComponent
php artisan make:livewire User/UserDashboardComponent
14. Now use the following code in web.php to use middleware in your project
Route::middleware(['auth'])->group(function(){
    Route::get('/user/dashboard', UserDashboardComponent::class)->name('user.dashboard');
});

Route::middleware(['auth', 'authadmin'])->group(function(){
    Route::get('/admin/dashboard', AdminDashboardComponent::class)->name('admin.dashboard');
});
1. first of all install livewire
composer require livewire/livewire
2. make livewire component
php artisan make:livewire HomeComponent
3. Make a folder in views named with layouts
4. then make file app.blade.php
5. Then write {{$slot}} where you want to render your livewire component
6. then write this code right before closing of head tag
  @livewireStyles
6. then write this code right before closing of head tag
  @livewireStyles
7. then write this code right before closing of body tag
  @livewireScripts
In laravel 9:
Command No 1 in controller:
return redirect()->route('category.index')->with('success', 'Record Entered Successfully');

then in blade
 @if (Session::has('success'))
      <div class="alert alert-success">
        {{Session::get('success')}}
      </div>
@endif
//Custom Validation 

$validated = Validator::make($data, [
                    'username' => 'required|unique:wbx_pos_merchant_terminals', // note the email field
                    'email' => 'required|unique:wbx_pos_merchant_terminals', // note the email field
                ]);
                return json_encode(
                    [
                        'error' => true,
                        'messages'=>$validated->errors()->all()
                    ]
                );
1. add the following code in laravel migrations to set foreign key
$table->unsignedBigInteger('customer_id');
$table->foreign('customer_id')->references('id')->on('customers');
or if you want to delete the foreign id data also
$table->foreign('customer_id')->references('id')->on('customers')->onDelete('cascade');
here 'customers' is the table of id here we are considering as foreign id
2. Now in the customer model as the following function
public function orders(){
        return $this->hasMany(Order::class, 'customer_id');
    }
3. In the order model add the following function
public function customer(){
        return $this->belongsTo(Customer::class, 'customer_id', 'id');
    }
1. Go to official link
https://spatie.be/docs/laravel-backup/v8/installation-and-setup
of spatie-backup and copy and run the following command [composer require spatie/laravel-backup]
2. Then copy and run the following command from the same link
[php artisan vendor:publish --provider="Spatie\Backup\BackupServiceProvider"]
3. Now you can include or exclude any file from backup in the config/backup.php file
4. Now in database.php file go to 'mysql' code group and add the following line of code after 'engine' => null,
  the code to add::
   'dump' => [
                'dump_binary_path' => 'C:/xampp/mysql/bin/',
            ],
5. Now in terminal run the following command [php artisan backup:run]
6. Now check the storage folder for your backup zipped file
7. Enjoy backup thanks
1. First install laravel as usual
2. the cd/enter to your project
3. now run the command [npm i vue@next vue-loader@next] to install vue into your project
4. now install vue plugin run the command [npm i @vitejs/plugin-vue]
5. if it came npm errors the youcan install specified version of vitreplugin by typing
e.g[npm i @vitejs/plugin-vue@3.0.x]
6. now open vite.config.js file and add some code as follows
add this line at headings import vue from "@vitejs/plugin-vue";
7. then put a coma after laravel code and add the following code 
vue({
            template: {
                transformAssetUrls: {
                    base: null,
                    includeAbsolute: false,
                }
            }
        })
8. open the blade main or welcome file and make a div in the body with id 'app'
9. now go to the resources/js folder and make a file named welcome.vue and type the follwing code in it and save 
  <template>
    <h1>welcome page frm vue js</h1>
</template>
10. now open app.js file in resources/js folder and remove the existing code. Then type the following code
import {createApp} from "vue";
import welcome from './welcome.vue';

createApp(welcome).mount('#app');
11. No open welcome.blade file and add the following code in head section
@vite(['resources/js/app.js','resources/css/app.css'])
12. Hurrah!! now enjoy laravel with vue..
1. open your laravel application as normal routine in chrome browser
2. Now click on three dots at top right of browser 
3. Then click on more tools option
4. Then click on create shortcut
5. Tick the option here that is open as window.
6. Now change the shortcut image with your own image
7. convert png/jpg etc image to .ico image
8. enjoy the laravel app as your desktop application. Thanks!
1. Make a file named index.php in the parent application folder
2. Point this file to the index.php file exits in the public folder by writing this code in that file 
  <?php
 	require_once __DIR__.'/public/index.php';
3. copy .htaccess file from public folder to parent application folder
4. Now change all links and script libraries in layoutfiles with public at start of the href link and also with script src.
5. Now enjoy you have no need to use php artisan serve
1. Right click on xampp control and click run as administrator
2. click on config button at top right corner of xampp and tick on Apache and mysql then tick on start control panel minimized
3. Then create a short cut of xampp-control exe file in c drive
4. Then type run at task bar the in RUN type shell:startup then paste the short to that startup folder
5. and thats it now you can restart your computer to check the auto ON functionality.
Thanks!
 ->columns([
                Tables\Columns\TextColumn::make('name'),
                Tables\Columns\TextColumn::make('urls')
                    ->label('No. URLs')
                    ->getStateUsing(function (Site $record) {
                        return count($record->urls);
                    }),
            ])
Forms\Components\TextInput::make('url')
  ->label('URL')
  ->url()
  ->required(),
  ])
    ->createItemButtonLabel('Add URL'
$posts = Post::whereDate('created_at', Carbon::today())->get();
// show
return Responder::respondValid(
    [
        'Model' => Model::with($relationships)->find($consultTopicId)
    ]
);

// index
return Responder::respondValid(
  	[
      	'MemberProviderConsults' => ConsultLogResource::collection(
        	MemberProviderConsult::with(
            	$this->relations
            )->where('columns', $filter)->orderBy('id', 'desc')->get()
      )
  ]
);

// Store
 $models = Model::create(
    [
        'name' => $request->input('name')
        'description' => $request->input('description', null)
    ]
);

$model->BelongsToManyRelation()->sync($request->input('relatedModelIds'));

return Responder::respondValid(
    [
        'model' => $model
    ]
);

// Update
$model = Model::find($modelId);

if ($request->input('name')) {
    $model->update(
        [
            'name' => $request->input('name')
            'description' => $request->input('description', null)
        ]
    );
}
$model->belongsToManyRelation()->sync($request->input('relatedModelIds'));
$model->questions()->sync($request->input('otherRelatedModelIds'));

$this->updateRequiredQuestions($request, $model->id);

return Responder::respondValid(
    [
        'model' => $model->refresh()->load($this->relations)
    ]
);
After the Ethereum Merge Event, Ethereum has become more admired in the crypto industry. Meantime, the price of ethereum has skyrocketed. Do you wanna create an ethereum standard token? https://bit.ly/3TlCuwx 

Being the trusted Ethereum Token Development Company that rendering excellent Token Development Services on multiple ethereum standards such as ERC20, ERC1155, ERC223, ERC721, ERC777, ERC827, ERC 998, and ERC1400 to enhance your tokenomics business and platform.

For Instant Connect, 
Whatsapp +91 9384587998 || Telegram @maticzofficial

1.go to htdocs folder and open git bash
2. git clone "url taken from remote github link"
3. cd projectName
4. composer update / composer install
5. make database name it with projectname or other
6. you can do npm install if required
7. then make a copy of .env file by using this command
8. cp .env.example .env
9. php artisan key:generate
10. php artisan migrate --seed
--------Include this in seeder file-------
use Illuminate\Support\Facades\Hash;
$user->password = Hash::make('12345');
----------Terminal Command------------------------
php artisan make:seeder BookSeeder
----------BookSeeder Code---------------------------
  use Faker\Factory as Faker;
----------Public function run() code------------------
 $faker = Faker::create();
       for ($i=0; $i < 100; $i++) { 
            $book = new Book;
            $book->book_name = $faker->name;
            $book->book_author = $faker->city;
            $book->save();
        }
----------Database Seeder code public function run()---------------
   $this->call([
            BookSeeder::class
        ]);
------------------php artisan code--------------------------------
php artisan db:seed
---------write it in head section in blade template-----------------
<meta name="csrf-token" content="{{csrf_token()}}"> 
  ----------do not use slim version of J Query---------------
    --------Use this before document ready in script tag--------
    <script>
          $.ajaxSetup({
                    headers: {
                        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                    }
                });
    </script>
------------------then------------------------------------
 <script>
        $(document).ready(function(){
            $('#country').change(function(){
                var country_id = $(this).val();
                $('#city').html('<option value="">Select City</option>');
                
                $.ajax({
                    url: '/getState/'+country_id,
                    type:'post',
                    success: function(result){
                        $('#state').html(result);
                    }
                });
            });

            $('#state').change(function(){
                var state_id = $(this).val();

              
                
                $.ajax({
                    url: '/getCity/'+state_id,
                    type:'post',
                    success: function(result){
                        $('#city').html(result);
                    }
                });
            });
        });
    </script>
--------------------------web.php code--------------------------
Route::post('/getState/{id}', [PlaceController::class, 'getState']);
Route::post('/getCity/{id}', [PlaceController::class, 'getCity']);
-------------------------Controller Code -----------------------------
  public function getState($country_id){
        $states = State::where('country_id', $country_id)->get();
        $html = '';
        foreach($states as $state){
            $html .='<option value="'.$state->id.'">'.$state->state_name.'</option>';
        }
        echo $html;
    }

    public function getCity($state_id){
        $cities = City::where('state_id', $state_id)->get();
        $html = '';
        foreach($cities as $city){
            $html .='<option value="'.$city->id.'">'.$city->city_name.'</option>';
        }
        echo $html;
    }
<?php

namespace App\Traits;

trait ResponseApi
{
    public function coreResponse($message, $data = null, $statusCode, $isSuccess = true)
    {
        if (!$message) {
            return response()->json(['message' => 'Message is required'], 500);
        }

        if ($isSuccess) {
            return response()->json([
                'message' => $message,
                'error' => false,
                'code' => $statusCode,
                'results' => $data
            ], $statusCode);
        } else {
            return response()->json([
                'message' => $message,
                'error' => true,
                'code' => $statusCode,
            ], $statusCode);
        }
    }

    public function success($message, $data, $statusCode = 200)
    {
        return $this->coreResponse($message, $data, $statusCode);
    }

    public function error($message, $statusCode = 500)
    {
        return $this->coreResponse($message, null, $statusCode, false);
    }
}
// In the controller
throw Illuminate\Validation\ValidationException::withMessages([
    "one_thing" => ["Validation Message #1"], 
    "another_thing" => ['Validation Message #2']
]);
$promises = Http::pool(function (Pool $pool) use ($schoolId, $filter, $batch, $studentGroupId) {
            $pool->as('schoolStaff')->withToken(Auth::user()->token())
                ->get(Api::schoolStaff()->index($schoolId, [], true), $filter);
            $pool->as('schoolBatchStudentGroup')->withToken(Auth::user()->token())
                ->get(Api::schoolBatchStudentGroup()->detail($schoolId, $batch, $studentGroupId, true));
        });

        $staffDatas = json_decode($promises['schoolStaff']->getBody(), true)['data'] ?? [];
        $studentGroup = json_decode($promises['schoolBatchStudentGroup']->getBody(), true)['data'] ?? [];
#!/bin/sh
set -e
 
echo "Deploying application ..."
 
# Enter maintenance mode
(php artisan down --message 'The app is being (quickly!) updated. Please try again in a minute.') || true
    # Update codebase
    git fetch origin deploy
    git reset --hard origin/deploy
 
    # Install dependencies based on lock file
    composer install --no-interaction --prefer-dist --optimize-autoloader
 
    # Migrate database
    php artisan migrate --force
 
    # Note: If you're using queue workers, this is the place to restart them.
    # ...
 
    # Clear cache
    php artisan optimize
 
    # Reload PHP to update opcache
    echo "" | sudo -S service php7.4-fpm reload
# Exit maintenance mode
php artisan up
 
echo "Application deployed!"
server {
    listen 80;
    listen [::]:80;
    server_name example.com;
    root /srv/example.com/public;
 
    add_header X-Frame-Options "SAMEORIGIN";
    add_header X-Content-Type-Options "nosniff";
 
    index index.php;
 
    charset utf-8;
 
    location / {
        try_files $uri $uri/ /index.php?$query_string;
    }
 
    location = /favicon.ico { access_log off; log_not_found off; }
    location = /robots.txt  { access_log off; log_not_found off; }
 
    error_page 404 /index.php;
 
    location ~ \.php$ {
        fastcgi_pass unix:/var/run/php/php8.0-fpm.sock;
        fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
        include fastcgi_params;
    }
 
    location ~ /\.(?!well-known).* {
        deny all;
    }
}
Go to directory laravel/bootstrap/cache and delete config.php file.


How did I solve this issue? After running those commands and not getting the solution.


composer dump-autoload
composer install
php artisan cache:clear
php artisan config:clear
php artisan optimize
php artisan clear-compiled
composer create-project laravel/laravel test_laravel
public function handle()
{
     $datas = Model::all();

     $bar = $this->output->createProgressBar($datas->count());

     $datas->each(function ($data) use ($bar) {
         try {
             // do something
         } catch (Exception $e) {
             $this->error('Error');
         }

         $bar->advance();
     });
}
// will add this code in web.php page 
Route::get("/mail",function(){
    Mail::raw("thank you", function($messsage){
        $messsage->to("name@gmail.com")->subject("contact with me");
    });
});

// will add this code at env file 
MAIL_MAILER=log

// to see the result you should go to www.myapp.com/mail then go to laravel.log file you will find the result there 
public function boot()
{
    User::observe(UserObserver::class);
}
Next, add an Observer class like so:

class UserObserver
{
    public function deleting(User $user)
    {
         $user->photos()->delete();
    }
}
composer require itsgoingd/clockwork
- in terminal: brew services start mysql
- alternatively, use DBngin

- open database front-end to create MySQL DB
    - Name: dbName
    - Host: 127.0.0.1
    - Username: root
    - Password is empty
    
- rename wp-config-sample.php to wp-config.php and update db variables
    
Use this info to complete Wordpress setup
in .env change APP_URL to 

APP_URL=http://localhost:port 
$this->assertSame('FooBar', Str::reverse('raBooF'));
$this->assertSame('Teniszütő', Str::reverse('őtüzsineT'));
$this->assertSame('❤MultiByte☆', Str::reverse('☆etyBitluM❤'));
//original
$dotted = [
    'user.name' => 'foo',
    'user.occupation' => 'bar',
];
 
// Converts it back to the original form
Arr::undot($dotted);

// Results in...
$resultArray = [
    'user' => [
        'name' => 'foo',
        'occupation' => 'bar',
    ]
];
$original = [
    'user' => [
        'name' => 'foo',
        'occupation' => 'bar',
    ]
];
 
$dotted = Arr::dot($original);
 
// Results in...
$dotted = [
    'user.name' => 'foo',
    'user.occupation' => 'bar',
];
Event::fakeExcept([
    NonImportantEvent::class,
    'non-fake-event',
]);
$schedule->command('model:prune', [
    '--exclude' => [Test::class, Example::class],
])->daily();
export $(sudo cat /opt/elasticbeanstalk/deployment/env) && sudo -E -u webapp php artisan tinker
php artisan cache:clear
php artisan route:clear
php artisan config:clear 
php artisan view:clear 
Update your /app/Providers/AppServiceProvider.php to contain:

use Illuminate\Support\Facades\Schema;

/**
 * Bootstrap any application services.
 *
 * @return void
 */
public function boot()
{
    Schema::defaultStringLength(191);
}
// in terminal, php artisan to create middleware
php artisan make:middleware VerifyIsAdmin

// in VerifyIsAdmin middleware file
public function handle(Request $request, Closure $next)
{
  if (!auth()->user()->isAdmin()) {
    return redirect()->back();
  }
  return $next($request);
}

// must register in kernel.php
protected $routeMiddleware = [
  'auth' => \App\Http\Middleware\Authenticate::class,
  'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
  'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
  'can' => \Illuminate\Auth\Middleware\Authorize::class,
  'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
  'password.confirm' => \Illuminate\Auth\Middleware\RequirePassword::class,
  'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
  'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
  'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
  'verifyCategoryCount' => VerifyCategoriesCount::class,
  'admin' => VerifyIsAdmin::class,
];

// use in Route to ensure user is authenticated and admin
Route::middleware(['auth', 'admin'])->group(function () {
    Route::get('users', [UsersController::class, 'index'])->name('users.index');
});
// class ExampleRequest 
public function response(array $errors): RedirectResponse
{
  return Redirect::back()->withErrors($errors)->withInput();
}
<!-- form.blade.php -->
<div class="form-group col-md-6 mb-3">
   <label for="contact_lastname">Nom <span class="text-danger">*</span></label>
   <input type="text"
          class="form-control @if($errors->has('contact_lastname')) is-invalid @endif"
          id="contact_lastname" name="contact_lastname"
          aria-describedby="validation_contact_lastname">
   @if($errors->has('contact_lastname'))
   <div id="validation_contact_lastname" class="invalid-feedback">
     {{$errors->first('contact_lastname') }}
   </div>
   @endif
</div>

<!-- ContactsController.php -->
$request->validate([
   'contact_lastname' => 'required'
]);
composer require laravel/sail --dev
php artisan sail:install
./vendor/bin/sail up
// Create 5 documents
$documents = Document::factory()->count(5)->make();

// Create contact
$contact->documents()->saveMany($documents);
/**
     * Query Public schema and return any req'd settings.
     */
    public static function getSettingsFromPublic()
    {
        if (Schema::connection('public')->hasTable('pubs')) {
            DB::table('public.pubs_settings')->select('ps.id, LOWER(ps.name) AS name, ps.description, ps.value, ps.resolve_include_path, ps.set_as_null, psc.name AS category, cst.name AS type, cse.name AS element')->join('components_settings_types_elements cste', 'cste.id', 'ps.components_settings_types_elements_id')->where('psc.name', 'css')->orderBy('ps.name', 'ASC')->get();
            $statement = "SELECT ps.id, LOWER(ps.name) AS name, ps.description, ps.value, ps.resolve_include_path, ps.set_as_null, psc.name AS category, cst.name AS type, cse.name AS element FROM pubs_settings ps JOIN pubs_settings_categories psc ON (psc.id = ps.pubs_settings_categories_id) JOIN components_settings_types_elements cste ON (cste.id = ps.components_settings_types_elements_id) JOIN components_settings_types cst ON (cst.id = cste.components_settings_types_id) JOIN components_settings_elements cse ON (cse.id = cste.components_settings_elements_id) WHERE psc.name = 'css' ORDER BY ps.name ASC";
            $data = DB::connection('public')->statement($statement);
        }
    }
$response = $response->withHeader('x-joey-test', 'myvalue');

return $response->withStatus(404)->getBody()->write('not found');
return $response->getBody()->write('hello world');
// convention is to make table name singular and in alphabetical order
php artisan make:migration create_post_tag_table

// create_post_tag_table.php
// if 1 post has 5 tags, then 5 records will exist with same post_id and different tag_ids
public function up()
{
  Schema::create('post_tag', function (Blueprint $table) {
    $table->bigIncrements('id');
    $table->integer('post_id');
    $table->integer('tag_id');
    $table->timestamps();
  });
}

// Post.php
// define relationship in Post model
public function tags()
{
  return $this->belongsToMany(Tag::class);
}
// php artisan make:seeder NameOfTheSeeder

<?php

namespace Database\Seeders;

use App\Models\ModelName;
use Illuminate\Database\Seeder;

class ModelNameSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        ModelName::factory()->count(50)->create();
    }
}
/**
 * Carbon example for january 2021 
 */

// first day of month (2021-01-01 00:00:00)
Carbon::now()->firstOfMonth()->startOfDay()

// first day of month in timestamp (1609459200)
Carbon::now()->firstOfMonth()->startOfDay()->timestamp

// last day of month (2021-01-31 23:59:59)
Carbon::now()->lastOfMonth()->endOfDay()

// last day of month in timestamp (1640995199)
Carbon::now()->lastOfMonth()->endOfDay()->timestamp

/**
 * Carbon example for january 1, 2021 
 */

// start of day in date (2021-01-01 00:00:00)
Carbon::now()->startOfDay()
 
// start of day in timestamp (1609459200)
Carbon::now()->startOfDay()->timestamp
 
// end of day in date (2021-01-01 23:59:59)
Carbon::now()->endOfDay()
 
// end of day in timestamp (1609545599)
Carbon::now()->endOfDay()->timestamp
Route::middelware(['auth'])->group(function (){

    Route::get('/', function () {
        return view('welcome');
    });

    Route::get('/dashboard', function (){
        return view('dashboard');
    })->name('dashboard');

});
Route::patch('aluminio/{id}', 'AluminioController@update')->name('aluminio.update');
$tasks = Tasks::find(1);
$newTask = $tasks->replicate();
$newTask->save();
//Multiple relationships:
$books = Book::with('author', 'publisher')->get();

//Nested relationships:
$books = Book::with('author.contacts')->get();
<!-- use enctype -->
<form  action="/route" method="POST" enctype="multipart/form-data">
class="{{ Request::is('products.index') ? 'active' : '' }}"
// url : https://www.example.com/param1/param2/param3
$request()->segment(3); // param3
// config/app.php
'locale' => 'fr',
'fallback_locale' => 'fr',
// replace get()
$products = Product::where('active', 1)->get();

// by paginate()
$products = Product::where('active', 1)->paginate(10);
// config\database.php
'connections' => [
    'mysql' => [
      (...)
      'strict' => true,
    ],
],
$this->validate($request, [
	"field_nullable" => "nullable"
]
/**
* Artisan Command
*/

php artisan make:request RequestName

/**
* Controller Code
*/
// inject filepath to custom request
use App\Http\Requests\RequestName;

// inject custom request as $request
// $request knows about validation and will automatically validate
public function store(RequestName $request)
    {
        Category::create([
            'name' => $request->name
        ]);

        session()->flash('success', 'Category Successfully Created');

        return redirect(route('categories.index'));
    }
    
/**
* Request File
*/
class CreateCategoryRequest 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()
    {
    // this is where validation rules are set
        return [
            'name' => 'required|unique:categories'
        ];
    }
}
if (str_contains(url()->current(), '/api')) {

            $finalProperty = [];
            $properties = PropertyListing::orderBy('id', 'DESC')->get(["id","user_id","listing_for","images","address","price","property_type","furnishing_status","facilities"]);
            foreach ($properties as $key => $property){
                // $finalImage['id'] = $property->id;
                // $finalImage['user_id'] = $property->user_id;
                // $finalImage['listing_for'] = $property->listing_for;
                $img_array = explode(',',$property->images);

                $properties[$key]->images = $img_array;

            }
         
            return response()->json(['properties' => $properties, 'success' => 200]);
            
        } else {
            $sliderImages = PropertyListing::all();
            return view('admin.imageslider.index', compact('sliderImages'));
        }
\Log::info(print_r($siteImageUrl, true));
php artisan migrate:refresh --path=/database/migrations/my_migration.php
NotificationFactory::new()->create();



use App\Models\User;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Notifications\DatabaseNotification;
use Illuminate\Support\Str;

class NotificationFactory extends Factory
{
    protected $model = DatabaseNotification::class;

    public function definition()
    {
        return [
            'id' => Str::uuid()->toString(),
            'type' => 'App\Notifications\ThreadSubscription',
            'notifiable_id' => function() {
                return auth()->id() ?? User::factory()->create();
            },
            'notifiable_type' => 'App\Models\User',
            'data' => ['message' => 'text']
        ];
    }
}
* Start the VM
	- vagrant up
	- vagrant ssh
* Shutdown and remove everything in memory
	- vagrant halt
* Close the VM for later use
	- vagrant suspend
	- vagrant resume
* Changed the homestead.yaml file?
	- vagrant provision
composer create-project "laravel/laravel=5.1.*" sampleproject
// sending a massage to blade from controller
return redirect()->route('add_item')->with('message', "Category Created Successfully");


//Checking for a message from the blade 
  @if(session()->has('message'))
    <div class="alert alert-success">
        {{ session()->get('message') }}
    </div>
@endif
$entities = $user->entities;
$entityIds = $entities->map( function($entity) {
    return [$entity['id']];
});
Entity::whereIn('id', $entityIds)->deleted();
php artisan cache:clear
chmod -R 777 storage/
composer dump-autoload
Route::group(['prefix' => '/user'], function () {
    Route::get('/profile', function(){
        return 'Profile';
    });

    Route::get('/password', function(){
        return 'Password';
    });
});
$validatedData = $request->validate([
    'name' => 'required',
    'gender' => 'required',
    'country' => 'required',
    'bod'=>'required',
    'description'=>'required',
]);

Profile::where('user_id',$user_id)->fill([
        'name'=>'name',
        'gender'=>'gender',
        'country'=>'country',
        'bod'=>'bod',
        'description'=>'description',
    ])->save();
Hello, As I read in your description that your company has many php- laravel, javascript projects, I am very interested in working with you. As you can see my profile, I have worked in core PHP, php and wordpress and javascript many times. I can work in this domain.
I know MVCs very well and have experience with them. I have worked with MVC CRUD, routing, integrating frontend technologies like vue.js and angular.js with the MVCs.
I have spent time in Integrating payment gateways in php and laravel.
I am also quiet good in architecturing databases like MySQL.
So overall I feel I will be a great fit t your system if selected once for a project.
If any thing is new for me that has to be implemented in the project then I find it to be a great opportunity of learning and implementation. So you can trust me and keep me as your working partner. You wil find me as a basic need of your development team after I have spent some time working with youl.
I will be waiting for your response.
Thank you.
Kind Regards.
public function update(Request $request, $id)
    {
        $this->validate($request, [
            'name' => 'required|unique:categories',
        ]);

        $category = Table::findOrFail($id);
        $category->name = $request->name;
        $category->save();
        return redirect()->route('management.table.home')->with('message', "Table Edited Successfully");
    }
   User::create([
           'name' => $request->name,
           'username' => $request->username,
           'email' => $request->email,
           'password' => Hash::make($request->password),

        ]);
<form action="{{ route('posts.likes', $post->id) }}" type="submit" method='post' >
                  @csrf
                  @method('delete')
                <button  type="submit" class="btn btn-primary btn-sm">Dislike</button>
              </form>

//route
Route::delete('/posts/{id}/likes', [PostLikeController::class, 'destroy'])->name('posts.likes');
// In post model are we are checking whether user has liked it:
// contains is a collection method which allows to look at the inside of the collection
// with collectiong you are looking at a particular key (user_id), and checking if the $user->id is within the collection
// then it will return a true or false
 
// POST MODEL: 
public function likedBy(User $user){
      return $this->likes->contains('user_id', $user->id);
    }

//POSTLIKECONTROLLER
 public function store($id, Request $request){
// this is activating when you press the submit button for like

        $this->middleware(['auth']);


        $post = Post::find($id);

        if ($post->likedBy($request->user())){
            return back(); 
        }
        
        $post->likes()->create([
            'user_id' => $request->user()->id,
        ]);
        return back();




 {{ Str::plural('like', $post->likes->count()) }}
public function store(Request $request)
    {
        $this->validate($request, [
            'name' => 'required|unique:categories',
        ]);

        Category::create([
            'name' => $request->name,
        ]);
Route::get('/',closure)
<button type="submit" id="customers_filter" onclick="checkWhetherTheTableContainsSearchResults()"
                                class="btn filter-button d-inline-block ml-3">
                                Filter
                            </button>
                            
<input id="search-hidden-input" hidden name="searchValue">

<script>
function checkWhetherTheTableContainsSearchResults() {
        let search = location.search.substring(1)
            searchInputElement = document.getElementById('search-hidden-input');
        
        if(search != '') {
            searchInputElement.setAttribute('value', search);
        }
    }
</script>
    
// If the filter is to work on search results, the original search parameter has to be passed into the request array.
        // Thus, the request array will return more than one parameter 
        // AND
        // one of the parameters will be searchValue
        // WHICH
        // will contain the entire search parameter (key + value)

        if ((count($request->all()) > 1) && (isset($request->searchValue))) {
            if (strpos($request->searchValue, '=')) {
                $string = $request->searchValue;
                $array = explode('=', $string);
                $request->searchValue = $array[1];
            }
        }
"repositories": {
        "webdevmatics/jetstream" : {
            "type": "path",
            "url": "C:\\laragon\\www\\codegenerator\\packages/webdevmatics/jetstream"
        }
    }
star

Thu Aug 14 2025 13:10:31 GMT+0000 (Coordinated Universal Time)

#php #laravel #docker #compose
star

Wed Aug 13 2025 18:16:02 GMT+0000 (Coordinated Universal Time)

#php #laravel
star

Wed Aug 13 2025 18:14:42 GMT+0000 (Coordinated Universal Time)

#php #laravel
star

Wed Aug 13 2025 18:10:53 GMT+0000 (Coordinated Universal Time)

#php #laravel
star

Wed Aug 13 2025 13:46:57 GMT+0000 (Coordinated Universal Time)

#php #laravel
star

Tue Aug 12 2025 16:28:03 GMT+0000 (Coordinated Universal Time)

#php #laravel
star

Tue Aug 12 2025 16:02:18 GMT+0000 (Coordinated Universal Time)

#php #laravel
star

Tue Aug 12 2025 16:01:08 GMT+0000 (Coordinated Universal Time)

#php #laravel
star

Tue Aug 12 2025 16:00:41 GMT+0000 (Coordinated Universal Time)

#php #laravel
star

Tue Aug 12 2025 16:00:13 GMT+0000 (Coordinated Universal Time)

#php #laravel
star

Tue Aug 12 2025 15:54:47 GMT+0000 (Coordinated Universal Time)

#php #laravel
star

Tue Aug 12 2025 15:19:23 GMT+0000 (Coordinated Universal Time)

#php #laravel
star

Tue Aug 12 2025 15:15:46 GMT+0000 (Coordinated Universal Time)

#php #laravel
star

Fri Aug 08 2025 15:13:30 GMT+0000 (Coordinated Universal Time)

#php #laravel
star

Fri Aug 08 2025 13:50:25 GMT+0000 (Coordinated Universal Time)

#php #laravel
star

Wed Aug 06 2025 13:35:49 GMT+0000 (Coordinated Universal Time)

#php #laravel
star

Sat Jul 12 2025 01:33:31 GMT+0000 (Coordinated Universal Time)

#php #laravel
star

Fri Jul 11 2025 00:57:16 GMT+0000 (Coordinated Universal Time)

#php #laravel
star

Fri Jul 11 2025 00:55:42 GMT+0000 (Coordinated Universal Time)

#php #laravel
star

Fri Jul 11 2025 00:54:01 GMT+0000 (Coordinated Universal Time)

#php #laravel
star

Fri Jul 11 2025 00:51:09 GMT+0000 (Coordinated Universal Time)

#php #laravel
star

Fri Jul 11 2025 00:49:09 GMT+0000 (Coordinated Universal Time)

#php #laravel
star

Mon Jun 23 2025 17:28:16 GMT+0000 (Coordinated Universal Time)

#php #laravel
star

Wed Mar 19 2025 14:53:47 GMT+0000 (Coordinated Universal Time)

#php #laravel
star

Tue Jan 21 2025 20:52:03 GMT+0000 (Coordinated Universal Time)

#php #laravel
star

Fri Jan 10 2025 15:10:54 GMT+0000 (Coordinated Universal Time)

#php #laravel
star

Thu Dec 26 2024 15:50:27 GMT+0000 (Coordinated Universal Time) https://www.meta.ai/c/19e08a2a-db68-4c85-b68c-9f44bef211b3

#laravel
star

Mon Oct 28 2024 20:54:02 GMT+0000 (Coordinated Universal Time)

#laravel #api #test #route #api.php
star

Thu Oct 24 2024 07:10:49 GMT+0000 (Coordinated Universal Time) https://www.bestwebsite.com

#laravel
star

Thu Sep 19 2024 20:16:29 GMT+0000 (Coordinated Universal Time)

#flutter #laravel #api #http #2lancer
star

Sat Aug 17 2024 01:20:17 GMT+0000 (Coordinated Universal Time)

#flutter #laravel #api #http #2lancer
star

Sat Aug 17 2024 00:58:14 GMT+0000 (Coordinated Universal Time)

#flutter #laravel #api #http #2lancer
star

Sat Aug 17 2024 00:56:17 GMT+0000 (Coordinated Universal Time)

#flutter #laravel #api #http #2lancer
star

Sat Aug 17 2024 00:55:54 GMT+0000 (Coordinated Universal Time)

#flutter #laravel #api #http #2lancer
star

Sat Aug 17 2024 00:54:26 GMT+0000 (Coordinated Universal Time) https://2lancer.ma/page/terms

#flutter #laravel #api #http #2lancer
star

Fri Aug 02 2024 13:14:57 GMT+0000 (Coordinated Universal Time) https://bobbyiliev.com/post/10-simple-tips-for-optimizing-your-laravel-application/

#laravel
star

Fri Aug 02 2024 13:14:48 GMT+0000 (Coordinated Universal Time) https://bobbyiliev.com/post/10-simple-tips-for-optimizing-your-laravel-application/

#laravel
star

Sat Jul 13 2024 11:08:00 GMT+0000 (Coordinated Universal Time)

#flutter #laravel #api #http
star

Wed Jun 19 2024 08:07:51 GMT+0000 (Coordinated Universal Time)

#flutter #laravel #api #http
star

Mon Mar 25 2024 14:05:14 GMT+0000 (Coordinated Universal Time)

#php #laravel
star

Wed Feb 21 2024 07:55:51 GMT+0000 (Coordinated Universal Time)

#blade #php #laravel #html #livewire #alpinejs
star

Sat Jan 20 2024 02:17:33 GMT+0000 (Coordinated Universal Time) https://github.com/LaravelDaily/laravel-tips/blob/master/other.md

#laravel #other #topics
star

Sat Jan 20 2024 02:14:11 GMT+0000 (Coordinated Universal Time) https://github.com/LaravelDaily/laravel-tips/blob/master/mail.md

#laravel #mail
star

Sat Jan 20 2024 02:12:05 GMT+0000 (Coordinated Universal Time) https://github.com/LaravelDaily/laravel-tips/blob/master/factories.md

#laravel #factory #factories
star

Sat Jan 20 2024 02:11:01 GMT+0000 (Coordinated Universal Time) https://github.com/LaravelDaily/laravel-tips/blob/master/db-models-and-eloquent.md

#laravel #database #eloquent #model
star

Sat Jan 20 2024 02:08:49 GMT+0000 (Coordinated Universal Time) https://github.com/LaravelDaily/laravel-tips/blob/master/collections.md

#laravel #eloquent #collection
star

Sat Jan 20 2024 02:06:58 GMT+0000 (Coordinated Universal Time) https://github.com/LaravelDaily/laravel-tips/blob/master/auth.md

#laravel #auth #tips
star

Sat Jan 20 2024 02:05:07 GMT+0000 (Coordinated Universal Time) https://github.com/LaravelDaily/laravel-tips/blob/master/artisan.md

#laravel #php #artisan #tips
star

Sat Jan 20 2024 02:03:22 GMT+0000 (Coordinated Universal Time) https://github.com/LaravelDaily/laravel-tips/blob/master/api.md

#php #laravel #api #api_tips #tips
star

Sat Jan 20 2024 01:44:36 GMT+0000 (Coordinated Universal Time) https://github.com/LaravelDaily/Laravel-Travel-API-Course/blob/main/app/Http/Controllers/Api/V1/TourController.php

#laravel #php #filtering #search #eloquent
star

Fri Jan 19 2024 15:14:52 GMT+0000 (Coordinated Universal Time)

#php #laravel #selectall
star

Wed Sep 20 2023 06:46:44 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/30198669/how-to-change-public-folder-to-public-html-in-laravel

#laravel
star

Wed Aug 30 2023 09:33:30 GMT+0000 (Coordinated Universal Time)

#laravel #php
star

Tue May 09 2023 14:05:07 GMT+0000 (Coordinated Universal Time)

#php #laravel
star

Sat May 06 2023 15:07:28 GMT+0000 (Coordinated Universal Time)

#php #laravel
star

Tue Apr 11 2023 04:11:37 GMT+0000 (Coordinated Universal Time)

#laravel #inertia #vue
star

Fri Mar 31 2023 17:20:50 GMT+0000 (Coordinated Universal Time) https://makitweb.com/remove-duplicate-values-from-an-array-in-php/

#laravel #php
star

Sun Mar 26 2023 12:35:19 GMT+0000 (Coordinated Universal Time)

#laravel
star

Sun Mar 26 2023 12:33:56 GMT+0000 (Coordinated Universal Time)

#laravel
star

Sun Mar 26 2023 12:32:14 GMT+0000 (Coordinated Universal Time)

#laravel
star

Sun Mar 26 2023 12:31:01 GMT+0000 (Coordinated Universal Time)

#laravel
star

Sun Mar 26 2023 12:28:27 GMT+0000 (Coordinated Universal Time)

#laravel
star

Sun Mar 26 2023 12:25:34 GMT+0000 (Coordinated Universal Time)

#laravel
star

Sun Mar 26 2023 12:22:49 GMT+0000 (Coordinated Universal Time)

#laravel
star

Thu Feb 23 2023 02:36:10 GMT+0000 (Coordinated Universal Time) https://refindustries.com/community/12632/how-to-sort-a-laravel-query-builder-result-by-multiple-columns

#laravel #php
star

Wed Feb 15 2023 16:36:22 GMT+0000 (Coordinated Universal Time) https://manashcse.medium.com/laravel-notify-remind-user-for-upcoming-event-9a45ca95b19c

#laravel #cron
star

Wed Feb 15 2023 12:47:23 GMT+0000 (Coordinated Universal Time)

#laravel
star

Sun Feb 12 2023 16:03:58 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/34382043/laravel-how-do-i-insert-the-first-user-in-the-database

#laravel
star

Thu Feb 02 2023 15:11:21 GMT+0000 (Coordinated Universal Time)

#php #laravel #command
star

Fri Jan 06 2023 04:29:42 GMT+0000 (Coordinated Universal Time)

#laravel #ajax
star

Wed Jan 04 2023 07:11:52 GMT+0000 (Coordinated Universal Time)

#laravel #ajax
star

Wed Jan 04 2023 06:57:31 GMT+0000 (Coordinated Universal Time)

#laravel #ajax
star

Wed Jan 04 2023 06:51:38 GMT+0000 (Coordinated Universal Time)

#laravel #ajax
star

Tue Jan 03 2023 17:20:28 GMT+0000 (Coordinated Universal Time)

#laravel #ajax
star

Tue Jan 03 2023 07:18:36 GMT+0000 (Coordinated Universal Time)

#laravel #ajax
star

Mon Jan 02 2023 10:15:44 GMT+0000 (Coordinated Universal Time)

#laravel #ajax
star

Fri Dec 30 2022 06:57:11 GMT+0000 (Coordinated Universal Time)

#laravel #ajax
star

Wed Dec 28 2022 04:15:12 GMT+0000 (Coordinated Universal Time)

#php #laravel
star

Thu Dec 22 2022 12:27:38 GMT+0000 (Coordinated Universal Time)

#laravel #ajax
star

Thu Dec 22 2022 11:15:52 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/48533921/validation-rule-unique-requires-at-least-1-parameters

#php #laravel
star

Thu Dec 15 2022 02:43:24 GMT+0000 (Coordinated Universal Time)

#laravel #ajax
star

Tue Dec 13 2022 07:23:56 GMT+0000 (Coordinated Universal Time) Install Vue 3 In Laravel 9 With Vite | Laravel Vite With Vue 3 | Vite Laravel Vue 3 | #1 HINDI

#laravel #ajax
star

Sun Dec 11 2022 16:08:23 GMT+0000 (Coordinated Universal Time)

#laravel #ajax
star

Sun Dec 11 2022 15:59:59 GMT+0000 (Coordinated Universal Time)

#laravel #ajax
star

Sun Dec 11 2022 15:50:54 GMT+0000 (Coordinated Universal Time)

#laravel #ajax
star

Fri Nov 25 2022 21:07:59 GMT+0000 (Coordinated Universal Time) https://github.dev/ryangjchandler/uptime-checker

#laravel
star

Fri Nov 25 2022 21:04:19 GMT+0000 (Coordinated Universal Time) https://github.dev/ryangjchandler/uptime-checker

#laravel
star

Mon Nov 21 2022 20:24:51 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/33247908/get-only-records-created-today-in-laravel

#laravel
star

Fri Oct 28 2022 12:53:53 GMT+0000 (Coordinated Universal Time) controller-logic

#php #controller #laravel
star

Wed Oct 19 2022 10:25:51 GMT+0000 (Coordinated Universal Time) https://maticz.com/how-to-create-nft-marketplace

#javascript #java #laravel #angular
star

Wed Oct 19 2022 10:19:52 GMT+0000 (Coordinated Universal Time) https://bit.ly/3GLa8p1

#javascript #java #php #laravel #angular #nodejs
star

Wed Oct 19 2022 10:16:04 GMT+0000 (Coordinated Universal Time) https://maticz.com/ethereum-token-development

#java #javascript #php #laravel
star

Wed Oct 19 2022 10:11:54 GMT+0000 (Coordinated Universal Time) https://bit.ly/3RN2YXJ

#java #javascript #php #laravel
star

Tue Oct 18 2022 10:28:17 GMT+0000 (Coordinated Universal Time)

#laravel #ajax
star

Tue Oct 11 2022 07:41:46 GMT+0000 (Coordinated Universal Time)

#laravel #ajax
star

Sat Oct 08 2022 16:05:01 GMT+0000 (Coordinated Universal Time)

#laravel #ajax
star

Sat Oct 08 2022 10:20:04 GMT+0000 (Coordinated Universal Time)

#laravel #ajax
star

Fri Sep 30 2022 05:06:47 GMT+0000 (Coordinated Universal Time) https://larainfo.com/blogs/laravel-8-authentication-with-laravel-ui

#laravel
star

Fri Sep 30 2022 02:56:21 GMT+0000 (Coordinated Universal Time) https://www.educba.com/laravel-commands/

#laravel
star

Thu Sep 29 2022 18:35:24 GMT+0000 (Coordinated Universal Time) https://codesource.io/complete-laravel-8-image-upload-tutorial-with-example/

#laravel
star

Thu Sep 15 2022 05:44:35 GMT+0000 (Coordinated Universal Time) https://www.hivelance.com/binance-clone-script

#javascript #php #nodejs #laravel
star

Tue Aug 30 2022 12:30:23 GMT+0000 (Coordinated Universal Time)

#laravel
star

Thu Aug 18 2022 13:21:26 GMT+0000 (Coordinated Universal Time)

#laravel
star

Fri Jul 22 2022 03:40:39 GMT+0000 (Coordinated Universal Time)

#php #laravel
star

Sun Jun 26 2022 08:40:16 GMT+0000 (Coordinated Universal Time)

#php #laravel #bash #apache #server
star

Tue Jun 21 2022 05:01:33 GMT+0000 (Coordinated Universal Time) https://laravel.com/docs/9.x/deployment

#php #laravel #nginx
star

Sat Jun 18 2022 06:21:50 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/59595863/file-put-contentsc-xampp-htdocs-instant-storage-framework-sessions-ff-failed

#php #laravel
star

Thu Jun 16 2022 12:24:06 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/18862160/composer-laravel-create-project

#php #laravel
star

Sat May 28 2022 09:49:21 GMT+0000 (Coordinated Universal Time)

#laravel
star

Sun Apr 24 2022 03:22:34 GMT+0000 (Coordinated Universal Time) Home

#php #laravel
star

Wed Mar 23 2022 12:27:31 GMT+0000 (Coordinated Universal Time) undefined

#laravel #migrate
star

Wed Mar 23 2022 03:02:28 GMT+0000 (Coordinated Universal Time) https://gist.github.com/dev-jaskaranSingh/e209225626d7b1b18a89d41d4a6ecfed

#laravel #php
star

Tue Mar 08 2022 07:57:30 GMT+0000 (Coordinated Universal Time) https://github.com/itsgoingd/clockwork

#laravel
star

Tue Mar 01 2022 15:42:38 GMT+0000 (Coordinated Universal Time)

#php #laravel
star

Tue Feb 01 2022 08:49:51 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/59697588/laravel-voyager-not-showing-images

#laravel
star

Thu Dec 02 2021 08:07:22 GMT+0000 (Coordinated Universal Time) https://laravel-news.com/laravel-8-74-0

#php #laravel
star

Thu Dec 02 2021 08:04:47 GMT+0000 (Coordinated Universal Time) https://laravel-news.com/laravel-8-74-0

#php #laravel
star

Thu Dec 02 2021 08:00:24 GMT+0000 (Coordinated Universal Time) https://laravel-news.com/laravel-8-74-0

#php #laravel
star

Thu Dec 02 2021 07:54:36 GMT+0000 (Coordinated Universal Time) https://laravel-news.com/laravel-8-74-0

#php #laravel
star

Thu Dec 02 2021 07:50:26 GMT+0000 (Coordinated Universal Time) https://laravel-news.com/laravel-8-74-0

#php #laravel
star

Thu Dec 02 2021 07:47:42 GMT+0000 (Coordinated Universal Time) https://laravel-news.com/laravel-8-74-0

#php #laravel
star

Wed Nov 24 2021 19:03:48 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/61816556/laravel-artisan-tinker-from-amazon-linux-2-elastic-beanstalk

#php #elasticbeanstalk #laravel
star

Thu Nov 18 2021 20:18:27 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/42244541/laravel-migration-error-syntax-error-or-access-violation-1071-specified-key-wa

#php #laravel
star

Thu Nov 18 2021 02:32:53 GMT+0000 (Coordinated Universal Time)

#php #laravel
star

Thu Nov 18 2021 02:27:34 GMT+0000 (Coordinated Universal Time) https://www.google.com/search?q

#php #laravel
star

Fri Oct 29 2021 04:36:51 GMT+0000 (Coordinated Universal Time) https://laravel.com/docs/8.x/middleware

#php #laravel
star

Tue Oct 19 2021 15:45:06 GMT+0000 (Coordinated Universal Time)

#laravel
star

Tue Oct 19 2021 14:30:52 GMT+0000 (Coordinated Universal Time)

#laravel
star

Wed Oct 13 2021 21:32:30 GMT+0000 (Coordinated Universal Time)

#laravel
star

Tue Oct 05 2021 20:40:04 GMT+0000 (Coordinated Universal Time)

#laravel
star

Thu Sep 30 2021 17:10:31 GMT+0000 (Coordinated Universal Time)

#php #laravel #querybuilder
star

Fri Sep 24 2021 17:36:04 GMT+0000 (Coordinated Universal Time)

#php #laravel
star

Fri Jul 30 2021 00:28:21 GMT+0000 (Coordinated Universal Time) https://laravel.com/docs/8.x/eloquent-relationships#many-to-many

#php #laravel
star

Thu Jun 24 2021 20:46:42 GMT+0000 (Coordinated Universal Time)

#laravel
star

Thu Jun 17 2021 19:33:02 GMT+0000 (Coordinated Universal Time)

#laravel
star

Tue Jun 15 2021 06:17:49 GMT+0000 (Coordinated Universal Time)

#laravel
star

Fri Jun 11 2021 21:12:23 GMT+0000 (Coordinated Universal Time) https://dev.to/jeromew90/how-use-sweetalert2-in-laravel-8-using-composer-jki

#laravel
star

Fri Jun 11 2021 21:12:02 GMT+0000 (Coordinated Universal Time) https://dev.to/jeromew90/how-to-create-a-multilingual-project-in-laravel-internationalization-i18n-11ol

#laravel
star

Fri Jun 11 2021 21:04:05 GMT+0000 (Coordinated Universal Time)

#laravel
star

Fri Jun 11 2021 21:03:44 GMT+0000 (Coordinated Universal Time)

#laravel
star

Fri Jun 11 2021 20:56:52 GMT+0000 (Coordinated Universal Time)

#php #laravel
star

Fri Jun 11 2021 20:56:24 GMT+0000 (Coordinated Universal Time)

#php #laravel
star

Fri Jun 11 2021 20:55:48 GMT+0000 (Coordinated Universal Time)

#php #laravel
star

Fri Jun 11 2021 20:55:16 GMT+0000 (Coordinated Universal Time)

#php #laravel
star

Fri Jun 11 2021 20:54:44 GMT+0000 (Coordinated Universal Time)

#php #laravel
star

Fri Jun 11 2021 20:54:08 GMT+0000 (Coordinated Universal Time)

#php #laravel
star

Fri Jun 11 2021 20:53:36 GMT+0000 (Coordinated Universal Time)

#php #laravel
star

Fri Jun 11 2021 20:36:55 GMT+0000 (Coordinated Universal Time)

#laravel #php
star

Sun May 16 2021 17:42:10 GMT+0000 (Coordinated Universal Time) https://laravel.com/docs/8.x/validation#form-request-validation

#laravel
star

Thu May 13 2021 10:01:16 GMT+0000 (Coordinated Universal Time)

#php #laravel
star

Mon Apr 19 2021 06:15:12 GMT+0000 (Coordinated Universal Time)

#laravel
star

Tue Apr 06 2021 20:22:31 GMT+0000 (Coordinated Universal Time) https://www.google.com/search?q

#php #laravel
star

Tue Apr 06 2021 12:42:54 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/47151886/how-can-i-run-specific-migration-in-laravel

#laravel #php
star

Wed Mar 24 2021 17:00:56 GMT+0000 (Coordinated Universal Time)

#laravel #factory
star

Sat Mar 20 2021 06:03:45 GMT+0000 (Coordinated Universal Time)

#commandline #laravel
star

Wed Mar 17 2021 08:33:26 GMT+0000 (Coordinated Universal Time) https://qiita.com/revenue-hack/items/f90fa5a7d4352d0bbc3f

#laravel #php
star

Fri Mar 12 2021 12:42:08 GMT+0000 (Coordinated Universal Time)

#laravel
star

Thu Mar 11 2021 06:41:43 GMT+0000 (Coordinated Universal Time) https://laracasts.com/discuss/channels/eloquent/how-to-delete-multiple-records-using-laravel-eloquent

#laravel #php
star

Wed Mar 10 2021 19:39:41 GMT+0000 (Coordinated Universal Time) https://es.stackoverflow.com/questions/177114/cómo-redirigir-a-un-usuario-según-su-rol-en-laravel

#rol #laravel
star

Tue Mar 09 2021 14:34:57 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/36460874/laravel-5-errorexception-failed-to-open-stream-permission-denied

#laravel
star

Fri Feb 26 2021 18:22:30 GMT+0000 (Coordinated Universal Time)

#laravel
star

Fri Feb 26 2021 13:51:51 GMT+0000 (Coordinated Universal Time)

#laravel
star

Thu Feb 18 2021 15:22:20 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/57985564/laravel5-8-the-get-method-is-not-supported-for-this-route-supported-methods-p

#php #save #laravel
star

Fri Jan 15 2021 13:28:09 GMT+0000 (Coordinated Universal Time)

#php #laravel
star

Mon Jan 11 2021 19:39:41 GMT+0000 (Coordinated Universal Time)

#laravel
star

Thu Dec 31 2020 11:35:22 GMT+0000 (Coordinated Universal Time)

#laravel
star

Mon Dec 28 2020 13:06:02 GMT+0000 (Coordinated Universal Time)

#laravel
star

Mon Dec 28 2020 10:39:10 GMT+0000 (Coordinated Universal Time)

#laravel
star

Sun Dec 27 2020 11:56:53 GMT+0000 (Coordinated Universal Time)

#laravel
star

Sun Dec 27 2020 08:06:01 GMT+0000 (Coordinated Universal Time)

#laravel
star

Fri Dec 11 2020 14:49:35 GMT+0000 (Coordinated Universal Time) https://www.hoclabs.com/2018/01/14/laravel-roles-y-permisos/

#roles #laravel
star

Tue Dec 01 2020 00:27:14 GMT+0000 (Coordinated Universal Time)

#laravel
star

Thu Nov 26 2020 18:43:15 GMT+0000 (Coordinated Universal Time) https://virtumedia.wordpress.com/2020/02/27/generar-documentos-pdf-en-laravel-que-incluyan-graficos/

#pdf #laravel
star

Tue Nov 10 2020 15:39:18 GMT+0000 (Coordinated Universal Time) https://es.stackoverflow.com/questions/218143/envio-de-mail-con-archivo-adjunto-laravel

#email #laravel
star

Fri Oct 02 2020 03:24:40 GMT+0000 (Coordinated Universal Time)

#php #laravel

Save snippets that work with our extensions

Available in the Chrome Web Store Get Firefox Add-on Get VS Code extension