laravel Archives - ProdSens.live https://prodsens.live/tag/laravel/ News for Project Managers - PMI Sun, 16 Jun 2024 00:20:32 +0000 en-US hourly 1 https://wordpress.org/?v=6.5.5 https://prodsens.live/wp-content/uploads/2022/09/prod.png laravel Archives - ProdSens.live https://prodsens.live/tag/laravel/ 32 32 Introducing Cart: Simplifying Shopping Cart Management for Laravel https://prodsens.live/2024/06/16/introducing-cart-simplifying-shopping-cart-management-for-laravel/?utm_source=rss&utm_medium=rss&utm_campaign=introducing-cart-simplifying-shopping-cart-management-for-laravel https://prodsens.live/2024/06/16/introducing-cart-simplifying-shopping-cart-management-for-laravel/#respond Sun, 16 Jun 2024 00:20:32 +0000 https://prodsens.live/2024/06/16/introducing-cart-simplifying-shopping-cart-management-for-laravel/ introducing-cart:-simplifying-shopping-cart-management-for-laravel

In the fast-paced world of e-commerce, efficient shopping cart management isn’t just essential—it’s a competitive advantage. Today, I’m…

The post Introducing Cart: Simplifying Shopping Cart Management for Laravel appeared first on ProdSens.live.

]]>
introducing-cart:-simplifying-shopping-cart-management-for-laravel

In the fast-paced world of e-commerce, efficient shopping cart management isn’t just essential—it’s a competitive advantage. Today, I’m thrilled to unveil Cart, a powerful Laravel package designed to streamline and elevate your online retail experience.

Why Cart Matters

Effective cart management is crucial for any successful e-commerce venture. Whether you’re running a small boutique shop or a large-scale marketplace, seamless cart operations can significantly impact your customer’s shopping journey. Cart acts as your trusted ally, offering a robust set of features tailored specifically for Laravel applications.

Unveiling Key Features

  1. Flexible Configuration

Cart allows you to customize each cart instance with specific tax rates, configurations, and business rules tailored to your unique needs. Whether managing different tax jurisdictions or implementing promotional discounts, Cart adapts effortlessly to your business requirements.

  1. Multiple Instances Management

With Cart, you can define and manage multiple cart instances within a single Laravel application. This capability is particularly valuable for scenarios requiring separate carts for different user sessions, order types, or temporary storage.

  1. Dynamic Tax Calculation

Tax rules can vary based on location, product type, or customer category. Cart empowers you to enable or disable tax calculations on a per-instance basis, ensuring compliance and flexibility in tax handling across diverse markets.

  1. Intuitive API Integration

Seamlessly integrate Cart into your Laravel application with its intuitive API. Whether adding products, updating quantities, or retrieving cart details, the API simplifies interactions and enhances development efficiency.

  1. Extensive Documentation and Support

Navigating a new package can be daunting, but Cart provides comprehensive documentation that guides you through installation, configuration, and advanced usage scenarios. Additionally, our dedicated support ensures you’re supported throughout your journey with Cart.

Getting Started with Cart

Installation

Getting started with Cart is straightforward. Begin by installing the package via Composer:

composer require realrashid/cart

Next, publish Cart’s configuration and other necessary assets:

php artisan cart:install

Basic Usage

Once installed, using Cart is as simple as including its facade in your Laravel controllers or services. Here’s a quick example of adding an item to the cart:

use RealRashidCartFacadesCart;

// Add a product to the cart
Cart::add(1, 'Sample Product', 2, 25.00, ['size' => 'M', 'color' => 'Blue'], 10);

Advanced Features

Explore Cart’s advanced features like updating item details, calculating taxes, managing multiple cart instances, and more. Dive deeper into our documentation to harness the full potential of Cart for your business.

Support and Contribution

Cart is open-source software licensed under the MIT License. We welcome contributions from the community to enhance Cart’s capabilities and ensure it meets the evolving needs of Laravel developers worldwide.

Show Your Support on ProductHunt!

Cart - Simplifying Cart for Laravel on Product Hunt

Conclusion

In conclusion, Cart is more than just a package—it’s a solution designed to optimize your Laravel-powered e-commerce platform. Whether you’re a developer streamlining cart management or a business owner aiming to enhance customer satisfaction, Cart provides the tools and flexibility you need.

Ready to transform your shopping cart experience? Get started with Cart today and discover a new level of efficiency and control in managing your online store.

If you find Cart helpful and would like to support my work, you can buy me a coffee. Your support keeps this project alive and thriving.

Thank you for being part of this journey.

Warm regards,

Rashid Ali

The post Introducing Cart: Simplifying Shopping Cart Management for Laravel appeared first on ProdSens.live.

]]>
https://prodsens.live/2024/06/16/introducing-cart-simplifying-shopping-cart-management-for-laravel/feed/ 0
Stay Updated with PHP/Laravel: Weekly News Summary (13/05/2024–19/05/2024) https://prodsens.live/2024/05/20/stay-updated-with-php-laravel-weekly-news-summary-13-05-2024-19-05-2024/?utm_source=rss&utm_medium=rss&utm_campaign=stay-updated-with-php-laravel-weekly-news-summary-13-05-2024-19-05-2024 https://prodsens.live/2024/05/20/stay-updated-with-php-laravel-weekly-news-summary-13-05-2024-19-05-2024/#respond Mon, 20 May 2024 16:20:37 +0000 https://prodsens.live/2024/05/20/stay-updated-with-php-laravel-weekly-news-summary-13-05-2024-19-05-2024/ stay-updated-with-php/laravel:-weekly-news-summary-(13/05/2024–19/05/2024)

Dive into the latest tech buzz with this weekly news summary, focusing on PHP and Laravel updates from…

The post Stay Updated with PHP/Laravel: Weekly News Summary (13/05/2024–19/05/2024) appeared first on ProdSens.live.

]]>
stay-updated-with-php/laravel:-weekly-news-summary-(13/05/2024–19/05/2024)

Dive into the latest tech buzz with this weekly news summary, focusing on PHP and Laravel updates from May 13th to May 19th, 2024. Stay ahead in the tech game with insights curated just for you!

This summary offers a concise overview of recent advancements in the PHP/Laravel framework, providing valuable insights for developers and enthusiasts alike. Explore the full post for more in-depth coverage and stay updated on the latest PHP/Laravel development.

Check out the complete article here https://poovarasu.dev/php-laravel-weekly-news-summary-13-05-2024-to-19-05-2024/

The post Stay Updated with PHP/Laravel: Weekly News Summary (13/05/2024–19/05/2024) appeared first on ProdSens.live.

]]>
https://prodsens.live/2024/05/20/stay-updated-with-php-laravel-weekly-news-summary-13-05-2024-19-05-2024/feed/ 0
CRUD Laravel 10 dan Bootstrap 5 #5: Menghapus Data https://prodsens.live/2024/05/07/crud-laravel-10-dan-bootstrap-5-5-menghapus-data/?utm_source=rss&utm_medium=rss&utm_campaign=crud-laravel-10-dan-bootstrap-5-5-menghapus-data https://prodsens.live/2024/05/07/crud-laravel-10-dan-bootstrap-5-5-menghapus-data/#respond Tue, 07 May 2024 00:20:19 +0000 https://prodsens.live/2024/05/07/crud-laravel-10-dan-bootstrap-5-5-menghapus-data/ crud-laravel-10-dan-bootstrap-5-#5:-menghapus-data

Hai, Sobat Risereaders! Setelah menyelesaikan beberapa tutorial, mulai dari cara mempersiapkan projek, menampilkan, menambah dan memperbarui data pada…

The post CRUD Laravel 10 dan Bootstrap 5 #5: Menghapus Data appeared first on ProdSens.live.

]]>
crud-laravel-10-dan-bootstrap-5-#5:-menghapus-data

Hai, Sobat Risereaders!

Setelah menyelesaikan beberapa tutorial, mulai dari cara mempersiapkan projek, menampilkan, menambah dan memperbarui data pada aplikasi CRUD mengelola data buku.

Kini kita akhirnya telah mencapai bagian terakhir dari seri CRUD Laravel 10 dan Bootstrap 5 ini, yaitu pada tutorial menghapus data buku dari database aplikasi CRUD.

Cara Menghapus Data dalam Aplikasi CRUD

Berikut langkah-langkah menghapus data dari aplikasi CRUD:

1. Membuat Method Destroy

Langkah pertama yang perlu kita lakukan adalah menambahkan method destroy di dalam BookController.

Method ini akan bertanggung jawab untuk menghapus data buku berdasarkan ID yang diberikan. Tambahkan kode berikut ke BookController:

// app/Http/Controllers/BookController.php

public function destroy(Book $book)
{
    // Menghapus gambar sampul jika ada
    if (!empty($book->cover)) {
        Storage::delete('public/books/' . $book->cover);
    }

    // Menghapus data dari database
    $book->delete();

    // Mengalihkan halaman ke indeks dengan pesan sukses
    return redirect()->route('books.index')->with('success', 'Data buku berhasil dihapus!');
}

Dalam method destroy, kita tidak hanya menghapus data buku dari database, tetapi juga menghapus gambar covernya jika ada.

Ini adalah langkah penting untuk memastikan bahwa gambar cover yang tidak digunakan, tidak memenuhi penyimpanan projek kita.

2. Menjalankan Aplikasi

Setelah menambahkan method destroy, langkah selanjutnya adalah menjalankan aplikasi kita. Pastikan untuk menjalankan server Laravel menggunakan perintah:

php artisan serve

Setelah itu, uji coba fitur penghapusan data di browser Anda untuk memastikan semuanya berfungsi dengan baik.

Pesan konfirmasi ketika ingin menghapus data

Penutup

Dengan demikian, kita telah menyelesaikan seri tutorial CRUD Laravel 10 dan Bootstrap 5 dengan sukses.

Dari awal hingga akhir, kita telah belajar langkah-langkah dasar untuk membuat, menampilkan, menambahkan, memperbarui, dan menghapus data dalam aplikasi Laravel, sambil memanfaatkan kelebihan Bootstrap untuk tampilan yang menarik dan responsif.

Semoga seri tutorial kali ini bisa bermanfaat untuk kamu!

The post CRUD Laravel 10 dan Bootstrap 5 #5: Menghapus Data appeared first on ProdSens.live.

]]>
https://prodsens.live/2024/05/07/crud-laravel-10-dan-bootstrap-5-5-menghapus-data/feed/ 0
CRUD Laravel 10 dan Bootstrap 5 #4: Mengupdate Data https://prodsens.live/2024/05/03/crud-laravel-10-dan-bootstrap-5-4-mengupdate-data/?utm_source=rss&utm_medium=rss&utm_campaign=crud-laravel-10-dan-bootstrap-5-4-mengupdate-data https://prodsens.live/2024/05/03/crud-laravel-10-dan-bootstrap-5-4-mengupdate-data/#respond Fri, 03 May 2024 00:20:47 +0000 https://prodsens.live/2024/05/03/crud-laravel-10-dan-bootstrap-5-4-mengupdate-data/ crud-laravel-10-dan-bootstrap-5-#4:-mengupdate-data

Hai, Sobat Risereaders! Pada artikel sebelumnya, kita telah mempelajari proses menambahkan data baru ke dalam aplikasi kita. Dan…

The post CRUD Laravel 10 dan Bootstrap 5 #4: Mengupdate Data appeared first on ProdSens.live.

]]>
crud-laravel-10-dan-bootstrap-5-#4:-mengupdate-data

Hai, Sobat Risereaders!

Pada artikel sebelumnya, kita telah mempelajari proses menambahkan data baru ke dalam aplikasi kita. Dan juga, cara menyimpan gambar ketika melakukan penambahan data di Laravel.

Sekarang, kita akan melanjutkan pembuatan aplikasi CRUD Laravel dan Bootstrap, yaitu pada tahap mengupdate data aplikasi kita.

Cara Mengupdate Data Aplikasi CRUD

Langkah-langkah cara mengupdate data CRUD yang sudah ada di dalam database:

  1. Membuat Method Edit dan Update

Langkah pertama dalam proses mengupdate data adalah dengan membuat method edit dan update di dalam controller BookController.

Method edit akan bertanggung jawab menampilkan form untuk mengedit data, sementara method update akan digunakan untuk memperbarui data di database.

// app/Http/Controllers/BookController.php

public function edit(Book $book)
{
    // Menampilkan halaman form edit data
    return view('books.edit', compact('book'));
}

public function update(Request $request, Book $book)
{
    // Validasi data input
    $validatedData = $request->validate([
        'cover' => 'nullable|image|mimes:jpg,png,jpeg,gif|max:2048',
        'title' => 'required|string|max:255',
        'description' => 'required|string',
    ]);

    // Jika mengunggah gambar cover baru
    if ($request->hasFile('cover')) {
        // Hapus gambar cover lama
        Storage::delete("public/books/$book->cover");

        // Upload gambar cover baru
        $cover = $request->file('cover');
        $cover->storeAs('public/books', $cover->hashName());

        // Simpan nama file gambar cover baru ke database
        $validatedData['cover'] = $cover->hashName();
    }

    // Update data di database
    $book->update($validatedData);

    // Mengalihkan halaman ke index dengan pesan sukses
    return redirect()->route('books.index')->with('success', 'Data buku berhasil diperbarui!');
}

Dalam method edit, kita menggunakan route model binding untuk langsung mengambil data buku yang akan diedit dari database.

Sedangkan dalam method update, kita melakukan validasi terhadap data input yang diterima sebelum memperbarui data di database.

Ketika kita melakukan update data, jika ada gambar cover baru yang ditambahkan, maka akan menghapus gambar cover yang lama menggunakan Storage::delete. Jangan lupa untuk mengimport Storage.

use IlluminateSupportFacadesStorage;

2. Membuat View Edit Data

Setelah membuat method di controller, langkah berikutnya adalah membuat tampilan untuk form edit data.

Buatlah file edit.blade.php di dalam folder resources/views/books/ dan tambahkan kode berikut:




@extends('layouts.app')


@section('title', 'Edit Buku')

@section('content')
     class="row justify-content-center">
         class="col-md-8">
            
            

@yield('title')

class="card mt-3"> class="card-body"> action="{{ route('books.update', $book->id) }}" method="POST" enctype="multipart/form-data"> @csrf @method('PUT') class="row justify-content-center"> class="col-6 col-sm-4 mb-3 order-sm-last"> src="{{ asset('storage/books/' . $book->cover) }}" alt="" class="img-fluid border rounded">
class="col-sm-8"> class="mb-3"> class="form-label" for="cover">Cover type="file" class="form-control @error('cover') is-invalid @enderror" id="cover" name="cover"> @error('cover') class="invalid-feedback">{{ $message }} @enderror class="mb-3"> class="form-label" for="title">Judul type="text" class="form-control @error('title') is-invalid @enderror" id="title" name="title" value="{{ old('title', $book->title) }}"> @error('title') class="invalid-feedback">{{ $message }} @enderror class="mb-3"> class="form-label" for="description">Deskripsi class="form-control @error('description') is-invalid @enderror" id="description" name="description" rows="3">{{ old('description', $book->description) }} @error('description') class="invalid-feedback">{{ $message }} @enderror href="{{ route('books.index') }}" class="btn btn-outline-primary me-2">Kembali type="submit" class="btn btn-primary">Simpan @endsection

Dalam tampilan ini, kita menggunakan layout layouts.app yang sudah kita buat pada tahap persiapan awal aplikasi CRUD.

Form ini diproteksi dengan CSRF token dan method PUT, sesuai dengan standar RESTful untuk proses update data.

3. Menjalankan Aplikasi

Terakhir, mari kita uji coba aksi update data yang telah kita tambahkan. Jalankan aplikasi Laravel terlebih dahulu:

php artisan serve

Buka browser kamu, dan kunjungi http://localhost:8000/books. Setelah itu, cari data buku yang ingin kamu ubah datanya.

Tampilan halaman books.edit

Penutup

Dalam artikel ini, kita telah mempelajari langkah-langkah untuk mengupdate data di dalam aplikasi CRUD kita. Belajar cara membuat method edit dan update, serta membuat halaman books.edit untuk menampilkan form edit data.

Pada artikel berikutnya dan juga terakhir, kita akan mempelajari cara menghapus data dari aplikasi CRUD kita. Jadi, tetap semangat belajar dan jangan lewatkan artikel selanjutnya!

The post CRUD Laravel 10 dan Bootstrap 5 #4: Mengupdate Data appeared first on ProdSens.live.

]]>
https://prodsens.live/2024/05/03/crud-laravel-10-dan-bootstrap-5-4-mengupdate-data/feed/ 0
CRUD Laravel 10 dan Bootstrap 5 #2: Menampilkan Data https://prodsens.live/2024/04/26/crud-laravel-10-dan-bootstrap-5-2-menampilkan-data/?utm_source=rss&utm_medium=rss&utm_campaign=crud-laravel-10-dan-bootstrap-5-2-menampilkan-data https://prodsens.live/2024/04/26/crud-laravel-10-dan-bootstrap-5-2-menampilkan-data/#respond Fri, 26 Apr 2024 00:20:21 +0000 https://prodsens.live/2024/04/26/crud-laravel-10-dan-bootstrap-5-2-menampilkan-data/ crud-laravel-10-dan-bootstrap-5-#2:-menampilkan-data

Hai, Sobat Risereaders! Pada artikel sebelumnya, kita telah membahas langkah-langkah persiapan awal untuk memulai pembuatan aplikasi CRUD sederhana…

The post CRUD Laravel 10 dan Bootstrap 5 #2: Menampilkan Data appeared first on ProdSens.live.

]]>
crud-laravel-10-dan-bootstrap-5-#2:-menampilkan-data

Hai, Sobat Risereaders!

Pada artikel sebelumnya, kita telah membahas langkah-langkah persiapan awal untuk memulai pembuatan aplikasi CRUD sederhana dengan menggunakan Laravel 10 dan Bootstrap 5.


CRUD Laravel 10 dan Bootstrap 5: Persiapan Awal

Tutorial cara mudah membuat aplikasi CRUD untuk mengelola data buku dengan Laravel 10 dan Bootstrap 5 bagian pertama.

favicon
blog.riseku.com

Kita sudah belajar bagaimana membuat model dan migrasi untuk projek, sekaligus menjalankan migrasi. Sekarang, kita akan beralih ke tahap selanjutnya dalam proses pengembangan, yaitu menampilkan data.

Cara Menampilkan Data Aplikasi CRUD

Langkah-langkah menampilkan data buku aplikasi CRUD dalam bentuk tabel:

1. Membuat Controller dan Method

Langkah pertama adalah membuat controller bernama BookController. Buka terminal kamu, jalankan perintah berikut:

php artisan make:controller BookController

Cari controller BookController di dalam folder app/Http/Controllers. Kemudian, mari kita buat method index untuk menampilkan data buku kita dari database:

// app/Http/Controllers/BookController.php



namespace AppHttpControllers;

// import class Book
use AppModelsBook;
use IlluminateHttpRequest;

class BookController extends Controller
{
    public function index(Request $request)
    {
        // mengambil title dari form pencarian
        $title = $request->input('search');

        // mengambil data buku dari database
        $books = Book::where('title', 'like', "%$title%") // filter data berdasarkan title
            ->orderByDesc('id') // urutkan data berdasarkan id secara descending
            ->paginate(5); // menampilkan 5 data per halaman

        // mengirim data buku ke view index
        return view('books.index', compact('books'));
    }
}

2. Membuat Layout

Selanjutnya, kita akan membuat layout untuk view. Buatlah file baru app.blade.php di dalam folder resources/views/layouts.




 lang="id">


     charset="UTF-8">
     name="viewport" content="width=device-width, initial-scale=1.0">
     http-equiv="X-UA-Compatible" content="ie=edge">

    
    </span>@yield('title')<span class="nt">
     href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" rel="stylesheet"
        integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65" crossorigin="anonymous">
     rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/css/toastr.min.css">


 class="bg-light">
     class="container my-5">

        
        @yield('content')
    

Dengan menggunakan layout, kita dapat memisahkan struktur tampilan dari konten yang dinamis, sehingga memudahkan dalam pengelolaan dan perawatan kode.

3. Membuat View Index

Selanjutnya, kita perlu membuat view books.index. Buatlah file baru index.blade.php di dalam folder resources/views/books.




@extends('layouts.app')


@section('title', 'Daftar Buku')

@section('content')
     class="d-flex justify-content-between align-items-center mb-3">
        
        

@yield('title')

href="{{ route('books.create') }}" class="btn btn-primary">Tambah Buku
action="" method="get"> class="input-group mb-4"> type="text" class="form-control" placeholder="Cari buku..." name="search" value="{{ request('search') }}"> class="btn btn-secondary" type="submit">Cari class="card"> class="card-body table-responsive p-0"> class="table table-striped mb-0"> style="width: 150px">Cover Judul Deskripsi style="width: 150px" class="text-center">Aksi @forelse ($books as $book) src="{{ asset('storage/books/' . $book->cover) }}" class="img-fluid border rounded">
{{ $book->title }}
{{ $book->description }} class="text-center"> href="{{ route('books.edit', $book) }}" class="btn btn-sm btn-warning">Edit action="{{ route('books.destroy', $book) }}" method="post" class="d-inline"> @csrf @method('DELETE') class="btn btn-sm btn-danger" onclick="return confirm('Apakah Anda yakin ingin menghapus data ini?')">Hapus @empty colspan="4" class="text-center">Tidak ada data @endforelse @if ($books->hasPages()) class="m-3 mb-0"> {{ $books->links('vendor.pagination.bootstrap-5') }} @endif @endsection

4. Publish Pagination

Pada halaman books.index, kita menggunakan pagination Bootstrap 5, namun viewnya belum dipublikasikan.

Untuk menggunakan pagination tersebut, perlu untuk mempublikasikan viewnya terlebih dahulu. Jalankan perintah berikut di terminal:

php artisan vendor:publish --tag=laravel-pagination

Setelah proses ini selesai, kita dapat menggunakan pagination Bootstrap 5 dalam aplikasi Laravel kita.

5. Mendefinisikan Route

Langkah terakhir adalah mendefinisikan route untuk menampilkan data. Buka file routes/web.php dan tambahkan route berikut:



// import class BookController
use AppHttpControllersBookController;
use IlluminateSupportFacadesRoute;

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

// menambahkan route resource books
Route::resource('books', BookController::class);

Di sini, kita mendefinisikan route resource books yang akan menghasilkan beberapa route untuk menangani berbagai aksi CRUD.

Route ini akan otomatis menghasilkan routes untuk methods yang diperlukan, seperti index, create, store, edit, update, dan destroy. Dengan demikian, kita tidak perlu mendefinisikan routenya satu per satu secara manual.

Berikut adalah hasil route yang menggunakan resource:

CRUD Laravel 10 dan Bootstrap 5: Route Resource

6. Menjalankan Aplikasi

Sekarang, saatnya untuk menjalankan aplikasi kita dan melihat hasilnya. Gunakan perintah berikut untuk menjalankan aplikasi:

php artisan serve

Setelah itu, kita dapat mengakses localhost:8000/books dan melihat tampilan tabel yang berisi data dari tabel books di database.

CRUD Laravel 10 dan Bootstrap 5: Halaman Index

Penutup

Pada artikel ini, kita telah mempelajari cara menampilkan data dengan menggunakan Laravel 10 dan Bootstrap 5. Langkah-langkah yang kita pelajari meliputi definisi route, pembuatan controller dan method, serta pembuatan tampilan untuk menampilkan data.

Selanjutnya, pada artikel berikutnya, kita akan membahas langkah-langkah untuk menambahkan data baru ke dalam database. Semoga tutorial ini memberikan manfaat!


CRUD Laravel 10 dan Bootstrap 5: Menambahkan Data

Tutorial cara mudah membuat aplikasi CRUD untuk mengelola data buku dengan Laravel 10 dan Bootstrap 5 bagian ketiga.

favicon
blog.riseku.com

The post CRUD Laravel 10 dan Bootstrap 5 #2: Menampilkan Data appeared first on ProdSens.live.

]]>
https://prodsens.live/2024/04/26/crud-laravel-10-dan-bootstrap-5-2-menampilkan-data/feed/ 0
Laravel Middleware https://prodsens.live/2024/03/21/laravel-middleware/?utm_source=rss&utm_medium=rss&utm_campaign=laravel-middleware https://prodsens.live/2024/03/21/laravel-middleware/#respond Thu, 21 Mar 2024 23:20:30 +0000 https://prodsens.live/2024/03/21/laravel-middleware/ laravel-middleware

Introduction Middleware stands as a crucial component facilitating seamless communication and interaction between various layers of an application.…

The post Laravel Middleware appeared first on ProdSens.live.

]]>
laravel-middleware

Introduction

Middleware stands as a crucial component facilitating seamless communication and interaction between various layers of an application. It serves as a bridge, intercepting incoming requests, performing operations, and shaping responses before they reach their final destination. In this article, we delve into the realm of middleware within the context of Laravel, one of the most popular PHP frameworks renowned for its elegant syntax and powerful features.

Explanation of Middleware in Web Development
Middleware, in its essence, refers to software components that sit between different layers of an application, facilitating communication and data exchange. In web development, middleware intercepts HTTP requests and responses, allowing developers to perform various tasks such as authentication, authorization, logging, and more, before reaching the intended route handler or controller.

Middleware operates on the principle of the “chain of responsibility” design pattern, wherein each middleware component in the chain has the ability to either modify the request, pass it to the next middleware, or halt the request entirely. This modular approach not only promotes code reusability but also enables developers to compartmentalize concerns, making applications more maintainable and extensible.

Importance of Middleware in Laravel Framework

In Laravel, middleware plays an important role in shaping the flow of incoming HTTP requests and outgoing responses. Laravel’s middleware layer sits between the incoming request and the application’s route handlers, providing developers with a robust mechanism to inject custom logic at various stages of the request lifecycle.

One of the key strengths of Laravel middleware lies in its flexibility and versatility. Whether it’s implementing authentication and authorization mechanisms, handling cross-site request forgery (CSRF) protection, logging requests, or performing custom operations, middleware empowers developers to tailor the request-handling process according to the specific requirements of their applications.

How Middleware Works in Laravel Framework

Here’s a simplified explanation of how middleware functions in Laravel:

1) Request Arrives: An HTTP request enters your Laravel application.
2) Middleware Stack: The request encounters a stack of middleware defined within your application.
3) Middleware Execution: Each middleware in the stack is executed sequentially.
4) A middleware can perform actions like:
Accessing request data (headers, body, etc.)
Checking user authentication status
Modifying the request object
It has the option to:
Terminate the request by returning a response (e.g., redirecting to a login page if unauthenticated).
Pass the request along to the next middleware in the stack.
5) Controller Reached: If no middleware terminates the request, it eventually reaches the intended controller for processing.
6) Response Generated: The controller generates a response based on the request.
7) Middleware on Response: The response may also pass back through the middleware stack, allowing for further modifications if necessary.

Middleware Execution Flow

The order of middleware execution is crucial. You can define two types of middleware in Laravel:

Global Middleware: Registered in the app/Http/Kernel.php file, these middleware apply to every single request hitting your application.
Route Middleware: Assigned to specific routes within your application’s route definitions. This allows you to apply middleware selectively based on the route being accessed.

The middleware stack processes requests in the following order:

  1. Global Middleware: All globally registered middleware execute sequentially.
  2. Route Middleware: Any middleware assigned to the specific route being accessed are processed in the order defined.
  3. Controller: The request reaches the designated controller for handling.
  4. Post-Response Middleware: After the controller generates a response, any middleware defined for the route (in reverse order) or globally can perform final modifications on the response.

Let’s create a custom global middleware that logs each incoming request:

Step 1: Create a new middleware using the artisan command:

php artisan make:middleware LogHttpRequest

Step 2: Open the generated middleware file AppHttpMiddlewareLogHttpRequest.php and implement the logic to log incoming requests:



namespace AppHttpMiddleware;

use Closure;
use IlluminateSupportFacadesLog;

class LogHttpRequest
{
    public function handle($request, Closure $next)
    {
        // Log the incoming request
        Log::info('Incoming Request: ' . $request->fullUrl());

        return $next($request);
    }
}

Step 3: Register the custom middleware in the $middleware array of AppHttpKernel.php:

protected $middleware = [
    // Other middleware...
    AppHttpMiddlewareLogHttpRequest::class,
];

With this setup, the LogHttpRequest middleware will be executed for every incoming request, logging the URL of each request.

Creating Custom Middleware

Creating custom middleware in Laravel is a straightforward process. Below is a step-by-step guide to creating custom middleware:

Step 1: Generate a new middleware using the Artisan command-line tool. Open your terminal and run the following command:

php artisan make:middleware CustomMiddleware

This command will create a new middleware class file named CustomMiddleware.php in the app/Http/Middleware directory.

Step 2: Open the generated middleware file (CustomMiddleware.php) in your text editor. You’ll find a handle method within this file. This method receives an incoming request and a closure. You can add your custom logic inside this method.



namespace AppHttpMiddleware;

use Closure;

class CustomMiddleware
{
    public function handle($request, Closure $next)
    {
        // Add your custom logic here

        return $next($request);
    }
}

Step 3: Implement your custom logic inside the handle method. This could include tasks such as authentication, authorization, logging, modifying the request/response, etc.

Step 4: If your middleware needs additional parameters, you can pass them as constructor arguments. For example:

public function __construct($parameter)
{
    $this->parameter = $parameter;
}

Step 5: If necessary, you can also perform actions before or after the request passes through the middleware by using the before or after methods. These methods are called automatically by Laravel before and after the handle method, respectively.

Step 6: Once your custom middleware is ready, you can register it in the $routeMiddleware array in the AppHttpKernel.php file.

Registering Middleware in Laravel Applications

Middleware in Laravel can be registered in two ways:

Global Middleware: These are registered in the $middleware property of the AppHttpKernel class.

Route Middleware: These are registered in the $routeMiddleware property of the same class.

To register middleware, follow these steps:

Step 1: Open the AppHttpKernel.php file in your Laravel application.

Step 2: Locate the $middleware property for global middleware or the $routeMiddleware property for route middleware.

Step 3: Add your middleware to the corresponding array with a key-value pair. The key will be used to reference the middleware in your routes or controllers.

protected $routeMiddleware = [
    'custom' => AppHttpMiddlewareCustomMiddleware::class,
];

Configuring Middleware Parameters

If your middleware requires parameters, you can pass them when registering middleware in the AppHttpKernel.php file. Here’s how:

protected $routeMiddleware = [
    'custom' => AppHttpMiddlewareCustomMiddleware::class,
];

Then, in your middleware constructor, you can accept these parameters:

public function __construct($parameter)
{
    $this->parameter = $parameter;
}

When applying middleware to routes, you can pass parameters like this:

Route::get('/example', function () {
    //
})->middleware('custom:param1,param2');

When applying middleware to routes, you can pass parameters like this:

Route::get('/example', function () {
    //
})->middleware('custom:param1,param2');

In this example, param1 and param2 will be passed to the middleware’s constructor as separate arguments.

Passing Parameters to Middleware

Passing parameters to middleware in Laravel can be achieved by appending them to the middleware name when applying the middleware to routes. Here’s how you can pass parameters to middleware:

Define Parameters in Middleware Constructor: First, define parameters in the constructor of your middleware class.



namespace AppHttpMiddleware;

use Closure;

class CustomMiddleware
{
    protected $parameter;

    public function __construct($parameter)
    {
        $this->parameter = $parameter;
    }

    public function handle($request, Closure $next)
    {
        // Middleware logic here
        return $next($request);
    }
}

Pass Parameters When Applying Middleware: When applying middleware to routes, pass parameters separated by commas after the middleware name.

Route::get('/example', function () {
    //
})->middleware('custom:param1,param2');

Access Parameters Within Middleware: Parameters passed to middleware can be accessed within the middleware’s handle method.

public function handle($request, Closure $next)
{
    // Access parameters
    $param1 = $this->parameter[0];
    $param2 = $this->parameter[1];

    // Middleware logic here
    return $next($request);
}

Middleware Priority and Execution Order

Middleware priority and execution order determine the sequence in which middleware is executed. In Laravel, middleware can be assigned priority through the $middlewarePriority property in the AppHttpKernel class. The default priority is defined in the $middlewarePriority array, where the keys represent middleware aliases, and the values represent their priority levels.

Best Practices for Managing Middleware Priority

Managing middleware priority is essential for controlling the order of execution and ensuring that middleware functions as expected. Here are some best practices:

Understand Default Priority: Familiarize yourself with the default middleware priority defined in the $middlewarePriority property of the AppHttpKernel class. Laravel executes middleware in the order specified in this array.

Review Middleware Dependencies: Before assigning priority to middleware, consider any dependencies or interactions between middleware. Ensure that middleware required for authentication, authorization, or request handling has higher priority.

Test Middleware Execution Order: Test the execution order of middleware to verify that the desired sequence is followed. Use debugging tools or log statements within middleware to track their execution flow.

Avoid Conflicts: Be cautious when assigning priorities to middleware to avoid conflicts or unintended consequences. Ensure that middleware with conflicting actions or behaviors are executed in the correct sequence.

Document Middleware Priority: Document the priority assigned to middleware in your application. Maintain a record of middleware dependencies and execution order to facilitate maintenance and troubleshooting.

By following these best practices, you can effectively manage middleware priority in your Laravel applications, ensuring seamless execution and consistent behavior.

Let’s create a real-world example of a Laravel middleware for logging HTTP requests.
This middleware will log details such as the request method, URL, request parameters, and timestamp to a log file.

Step 1: Create the Middleware

Generate a new middleware using the Artisan command-line tool:

php artisan make:middleware LogHttpRequests

This will create a new middleware file named LogHttpRequests.php in the app/Http/Middleware directory.

Step 2: Implement the Middleware

Open the LogHttpRequests.php file and implement the logic to log HTTP requests:



namespace AppHttpMiddleware;

use Closure;
use IlluminateSupportFacadesLog;

class LogHttpRequests
{
    public function handle($request, Closure $next)
    {
        // Log the incoming request
        Log::info('HTTP Request Logged:', [
            'method' => $request->method(),
            'url' => $request->fullUrl(),
            'parameters' => $request->all(),
            'timestamp' => now()->toDateTimeString(),
        ]);

        return $next($request);
    }
}

Step 3: Register the Middleware

Add the middleware to the $middleware array in the AppHttpKernel class to make it a global middleware:

protected $middleware = [
    // Other middleware...
    AppHttpMiddlewareLogHttpRequests::class,
];

Step 4: Use the Middleware

The middleware is now registered globally and will log all incoming HTTP requests. You can also apply it selectively to routes by specifying it in the route definition:

Route::get('/example', function () {
    //
})->middleware(AppHttpMiddlewareLogHttpRequests::class);

Step 5: Test the Middleware

Make HTTP requests to your Laravel application, and you should see log entries in the configured log file (usually storage/logs/laravel.log). These log entries will contain details about each incoming HTTP request, including the request method, URL, parameters, and timestamp.

This example demonstrates how to create a Laravel middleware for logging HTTP requests, providing valuable insight into the incoming traffic to your application.

Middleware Groups and Middleware Stacks in Laravel

Laravel provides two powerful mechanisms for organizing and managing middleware: middleware groups and middleware stacks.

1. Creating Middleware Groups for Route Groups
Middleware groups allow you to define a collection of middleware that can be applied to multiple routes with a single reference. This promotes code reuse and simplifies route definitions.

Here’s how to create and use middleware groups:

Define the Group:

In app/Http/Kernel.php, add a new key-value pair to the $middlewareGroups property:

protected $middlewareGroups = [
    'web' => [
        AppHttpMiddlewareEncryptCookies::class,
        IlluminateCookieMiddlewareAddQueuedCookiesToResponse::class,
        IlluminateSessionMiddlewareStartSession::class,
        IlluminateViewMiddlewareShareErrorsFromSession::class,
        IlluminateHttpMiddlewareVerifyCsrfToken::class,
        IlluminateRoutingMiddlewareSubstituteBindings::class,
    ],
    // Define other groups as needed
];

Assign the Group to Routes:

Within your route definitions, use the middleware method with the group name:

Route::get('/', function () {
    // ...
})->middleware('web');

Route::group(['middleware' => 'web'], function () {
    // All routes within this group will use the 'web' middleware group
    Route::get('/profile', function () {
        // ...
    });
    Route::get('/dashboard', function () {
        // ...
    });
});

2.Implementing Middleware Stacks for Complex Applications
For more intricate scenarios, Laravel supports middleware stacks. These allow you to define a temporary middleware stack specifically for a route or controller action. This provides greater flexibility in handling complex request flows.

Here’s how to use middleware stacks:

Define the Stack:

Use the withMiddleware method on the route definition:

Route::get('/admin', function () {
    // ...
})->withMiddleware(function ($middleware) {
    $middleware->push(AppHttpMiddlewareIsAdmin::class); // Add custom middleware
})->middleware('auth'); // Apply existing 'auth' middleware as well

The closure passed to withMiddleware receives the current middleware stack as an argument. You can then use methods like push or prepend to add or insert custom middleware into the stack for that specific route.

Examples of Using Middleware Groups and Stacks Effectively
Here are some practical examples of using middleware groups and stacks:

'web' Group: The default web group in Laravel applies essential middleware for web applications (session, CSRF protection, etc.) to a broad range of routes.
'api' Group: You can create an api group containing middleware specific to API requests, such as rate limiting or authentication checks.
Admin Panel: Use a middleware stack to add an IsAdmin middleware to specific routes within your admin panel, restricting access only to authorized users.

Built-in Middleware in Laravel

Laravel offers a variety of pre-built middleware that handle common tasks within web applications. These middleware streamline development by providing essential functionalities you can leverage directly.

Overview of Commonly Used Built-in Middleware
Here’s a breakdown of some frequently used built-in middleware:

AppHttpMiddlewareEncryptCookies: Encrypts cookies for added security.
IlluminateCookieMiddlewareAddQueuedCookiesToResponse: Adds queued cookies to the outgoing HTTP response.
IlluminateSessionMiddlewareStartSession: Starts a session for the request if one doesn’t already exist.
IlluminateViewMiddlewareShareErrorsFromSession: Shares error messages from the session with the view.
IlluminateHttpMiddlewareVerifyCsrfToken: Protects against Cross-Site Request Forgery (CSRF) attacks.
IlluminateRoutingMiddlewareSubstituteBindings: Binds route model parameters to their corresponding Eloquent models.
These middleware are typically included in the default web group defined in app/Http/Kernel.php, ensuring they apply to most web application routes.

For reference, here’s how you could manually apply some of these middleware to a route:

Route::get('/profile', function () {
    // This route uses the built-in session handling middleware
})->middleware(IlluminateSessionMiddlewareStartSession::class);

Route::post('/form', function () {
    // This route enforces CSRF protection
})->middleware(IlluminateHttpMiddlewareVerifyCsrfToken::class);

Overview of Commonly Used Built-in Middleware

AppHttpMiddlewareEncryptCookies: Encrypts cookies for security.
IlluminateCookieMiddlewareAddQueuedCookiesToResponse: Adds queued cookies to the response.
IlluminateSessionMiddlewareStartSession: Starts a session if one doesn’t exist.
IlluminateViewMiddlewareShareErrorsFromSession: Shares session errors with the view.
IlluminateHttpMiddlewareVerifyCsrfToken: Protects against CSRF attacks in POST requests.
IlluminateRoutingMiddlewareSubstituteBindings: Binds route model parameters to Eloquent models.
These middleware are usually included in the web group (app/Http/Kernel.php), applying to most web routes.

More info

Laravel Middleware
Laravel Middleware: Enhancing Your Application’s Security and Functionality
Working With Controllers and Middleware in Laravel

The post Laravel Middleware appeared first on ProdSens.live.

]]>
https://prodsens.live/2024/03/21/laravel-middleware/feed/ 0
O poder do FilamentPHP https://prodsens.live/2024/02/06/o-poder-do-filamentphp/?utm_source=rss&utm_medium=rss&utm_campaign=o-poder-do-filamentphp https://prodsens.live/2024/02/06/o-poder-do-filamentphp/#respond Tue, 06 Feb 2024 23:20:57 +0000 https://prodsens.live/2024/02/06/o-poder-do-filamentphp/ o-poder-do-filamentphp

Neste artigo vou apresentar uma ferramenta poderosa, incrivelmente fácil de usar e como ela pode deixar seu desenvolvimento…

The post O poder do FilamentPHP appeared first on ProdSens.live.

]]>
o-poder-do-filamentphp

Neste artigo vou apresentar uma ferramenta poderosa, incrivelmente fácil de usar e como ela pode deixar seu desenvolvimento web muito mais rápido e eficiente com apenas alguns comandos. Com ela, você consegue montar seu projeto completo, com uma interface linda e intuitiva dentro de pouquíssimo tempo. Vamos lá?
 

Tópicos

  • O que é o FilamentPHP?
  • Quais as vantagens de usar FilamentPHP?
  • O que preciso para usar FilamentPHP?
  • Instalando o Filament
  • Demonstração de uso do FilamentPHP na prática
  • Conclusão
  • Referências

 

O que é o FilamentPHP?

Página principal do FilamentPHP

O FilamentPHP é uma ferramenta para desenvolvimento web full-stack, também chamada de TALLkit, pois reúne os 4 cavaleiros da TALLStack (Tailwind, Alpine.js, Laravel, Livewire).

Com uma documentação rica e clara, usar os recursos do Filament não tem nenhum segredo, você consegue implementar cada um deles no seu projeto sem muito esforço, sendo assim, um grande aliado da produtividade, tudo isso com uma interface bonita e intuitiva que você pode moldar da forma como preferir.

O Filament na versão atual (v3.2) conta com 8 módulos pra você usar, são eles: Panel Builder, Form Builder, Table Builder, Notifications, Actions, Widgets, Infolist Builder e Core Concepts, cada um deles com suas respectivas funcionalidades.
 

Quais as vantagens de usar FilamentPHP?

Página inicial da documentação do FilamentPHP

Facilidade: Usando o FilamentPHP você vê várias linhas de código se tornarem uma só. Você consegue implementar facilmente recursos como filtros e campos de buscas em segundos. Basta um comando e o Filament consegue montar seu formulário prontinho só pra você moldar como quiser.

Desacoplamento: O módulos do Filament também podem ser utilizados de forma independente, sem a necessidade da instalação de todo seu ecossistema. Então, se você quiser usar só o Form Builder ou o Table Builder, você pode instalá-los sem precisar instalar todo o restante.

Produtividade: Com as várias facilidades que essa ferramenta oferece, o seu desenvolvimento fica muito mais rápido, uma função que você normalmente demoraria umas horas pra fazer pode durar apenas minutos.

Customizável: Afinal, quem tem limite é estado, não é mesmo? Apesar de o foco do Filament ser em painéis administrativos, você pode utilizá-lo também para criar sites por exemplo, com ele você é livre pra usar sua imaginação.

Open-source: Isso mesmo, lá no Github você pode clonar o repositório do Filament e adicionar sua contribuição. No próprio readme do projeto você encontra orientações de como rodar o projeto na sua máquina.

Gratuito: Não podemos esquecer o melhor de tudo né? O FilamentPHP é totalmente gratuito.
 

O que preciso para usar FilamentPHP?

Para usar FilamentPHP você precisa ter os seguintes requisitos :

  • PHP 8.1+
  • Laravel v10.0+
  • Livewire v3.0+

Esses requisitos valem para o FilamentPHP v3.2, você pode ver os requisitos para as outras versões visitando a aba de Instalação lá dentro da documentação. É recomendado o uso da versão mais atual, pois ela veio com muito mais recursos que as anteriores e de forma ainda mais simplificada, porém, se você optar por uma versão mais baixa, saiba que alguns recursos podem não estar presentes ou mudaram a forma de implementação.

Para o desenvolvimento em Filament, é muito importante que você tenha uma boa noção de PHP + Laravel, pois assim além de a ferramenta ser melhor aproveitada, entendendo isso, você pode desacoplar as funcionalidades com mais facilidade, assim usufruindo de todas as vantagens de utilizá-lo.
 

Instalando o Filament

Para instalar o FilamentPHP, dentro do seu projeto Laravel rode o seguinte comando:

composer require filament/filament:"^3.2" -W 

Depois disso, rode o comando a seguir. Este vai instalar o Painel:

php artisan filament:install --panels

E por último, para criar seu usuário do painel, utilize o comando:

php artisan make:filament-user

E pronto, agora você já pode acessar seu painel Filament, basta rodar um php artisan serve e acessar a URL localhost:8000/admin e logar com o e-mail e senha do usuário que você criou.
 

Demonstração de uso do FilamentPHP na prática

No vídeo acima, eu demonstro a criação de uma resource utilizando Filament. A resource já vem com o CRUD completo e funcional, com seu formulário e sua tabela já montados.

Para criar essa resource eu sigo os seguintes passos:

Primeiro, antes de criar a resource você precisará somente de 3 coisas

  • A sua tabela no banco de dados do seu projeto Laravel deve estar criada.
  • No seu Model, a sua variavel $fillable deve conter todos os campos existentes na sua tabela.
  • E obviamente, ter o FilamentPHP instalado no seu projeto. (Passo a passo no tópico anterior).

Você pode facilmente fazer isso da seguinte forma:

Use o comando abaixo com o nome do Model que você desejar (no caso o nome do meu Model é Product) com a flag -m para que a migration já seja criada junto:

php artisan make:model Product -m

Na Migration que você acabou de criar, coloque os campos que você desejar adicionar na sua tabela, ela deve ficar mais ou menos assim:



use IlluminateDatabaseMigrationsMigration;
use IlluminateDatabaseSchemaBlueprint;
use IlluminateSupportFacadesSchema;

return new class extends Migration
{
    /**
    * Run the migrations.
    */
    public function up(): void 
    {
        Schema::create('products', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->longText('description');
            $table->decimal('price', 8, 2);
            $table->timestamps();
        });
    }

    /**
    * Reverse the migrations.
    */
    public function down(): void 
    {
        Schema::dropIfExists('products');
    }
};

Depois de adicionar seus campos, rode um php artisan migrate para que seja criada a tabela no seu banco de dados.

Após criada a tabela, declare os campos da sua tabela na variável $fillable dentro do seu Model como no exemplo abaixo:



namespace AppModels;

use IlluminateDatabaseEloquentFactoriesHasFactory;
use IlluminateDatabaseEloquentModel;

class Product extends Model
{
    use HasFactory;

    protected $fillable = [
        'name',
        'description',
        'price',

    ];
}

E pronto, agora é só correr pro abraço! Para criar sua resource, você só vai precisar do seguinte comando (onde Product é o nome do seu Model):

php artisan make:filament-resource Product --generate --view

// A flag --generate vai gerar seu formulário
// A flag --view vai criar a página de visualização
// Você pode ainda utilizar a flag --simple para que sua 
// resource seja baseada em modais, isso tudo ta explicado 
// direitinho na documentação

 

Conclusão

Você pode ter um gostinho das funcionalidades do FilamentPHP visitando a demo, lá mostra de forma prática um exemplo de como os componentes podem ser utilizados e organizados em tela no seu projeto. O Filament também tem uma comunidade no Discord que está sempre pronta pra te ajudar e tirar suas dúvidas.

Além disso, reza a lenda que a versão 4 vem ainda esse ano com ainda mais novidades.

“Ah mas você ta fazendo propaganda do negócio”, acho que o que é bom tem ser mostrado né pessoal.
Eai, vamos pro Filament?

 

Referências

 

Meus agradecimentos a @cherryramatis,@clintonrocha98 e @redrodrigoc pelas dicas e sugestões para este artigo, vocês são demais 💜

The post O poder do FilamentPHP appeared first on ProdSens.live.

]]>
https://prodsens.live/2024/02/06/o-poder-do-filamentphp/feed/ 0
Securing Sensitive Data with Encryption Algorithms https://prodsens.live/2024/01/28/securing-sensitive-data-with-encryption-algorithms/?utm_source=rss&utm_medium=rss&utm_campaign=securing-sensitive-data-with-encryption-algorithms https://prodsens.live/2024/01/28/securing-sensitive-data-with-encryption-algorithms/#respond Sun, 28 Jan 2024 05:20:10 +0000 https://prodsens.live/2024/01/28/securing-sensitive-data-with-encryption-algorithms/ securing-sensitive-data-with-encryption-algorithms

Encryption is the process of converting plain text into an unreadable form(ciphertext) to protect from unauthorized access. There…

The post Securing Sensitive Data with Encryption Algorithms appeared first on ProdSens.live.

]]>
securing-sensitive-data-with-encryption-algorithms

Encryption is the process of converting plain text into an unreadable form(ciphertext) to protect from unauthorized access.

There are 2 types of Encryptions:

  1. Symmetric-Key encryption
  2. Asymmetric encryption (public-key encryption)

How encryption algorithms work:

Encryption:
Plain text is input into the algorithm.
The algorithm uses a key to perform a series of complex mathematical operations on the plain text. The output is ciphertext, which is unreadable without the key.

Decryption:
Ciphertext is input into the algorithm.
The algorithm uses the correct key to reverse the mathematical operations.The output is the original plain text.

Symmetric-Key encryption:
It uses the same key for both encryption and decryption. It is fast and efficient for large amounts of data. Secure keys are exchanged between parties.

There are two main types: block ciphers and stream ciphers.

Block Ciphers:

  1. Block ciphers encrypt data in fixed-size blocks (e.g., 64 or 128 bits) using a key.
  2. A widely used block cipher is the Advanced Encryption Standard (AES), which supports key lengths of 128, 192, or 256 bits.
  3. The data is divided into blocks, and each block is encrypted independently.

Stream Ciphers:
Stream ciphers encrypt data bit by bit or byte by byte, typically in a continuous stream.
One common stream cipher is the Rivest Cipher (RC4).

Example: AES (Advanced Encryption Standard)

function encrypt($data="", $key="") {
    $iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length("aes-256-cbc")); // dynamic iv (we can also set static iv)
    $encrypted = openssl_encrypt($data, "aes-256-cbc", $key, 0, $iv);
    return base64_encode($iv . '!!' . $encrypted);
}
function decrypt( $data="", $key="") {
    list($iv, $encryptedData) = explode('!!', base64_decode($data), 2);
    return openssl_decrypt($encryptedData, "aes-256-cbc", $key, 0, $iv);
}

$plainData = [
    'email' => 'codewithrubab@gmail.com',
    'password' => 'codeOn@Vscode2024';
];
$saltKey = "asdckd44dbc228e16c2888436d17a";

$encryptedData = encrypt(json_encode($plainData), $saltKey);
echo $encryptedData;
$decryptedData = decrypt($encryptedData, $saltKey);
print_r($decryptedData);

Note: If we need to re-generate same encrypted data on same plain text then we need to always use same Salt Key and IV. Otherwise, the output will be different.

Asymmetric encryption (public-key encryption):
It uses two different keys: a public key for encryption and a private key for decryption.

we don’t need secure key exchange for encryption. It’s slower than symmetric encryption and useful for digital signatures and authentication,

Common public-key encryption techniques: RSA, ECC (Elliptic Curve Cryptography), Diffie-Hellman.

Let’s see an Example with RSA Algorithm.

If we don’t have the public and private keys then we can generate from the command line interface.

For private key file generation in a directory:

openssl genrsa -out privateKey.pem 2048
For public key:
openssl rsa -in privateKey.pem -pubout

Here, privateKey.pem and privateKey.pem are the generated file names.

The generated public key is a RSA result.

The private Key is not a RSA result. To make it a RSA result we need to write some code.

First, install this package in your Laravel Project.

Composer require "phpseclib/phpseclib": "~2.0"

use phpseclibCryptRSA;


// private key: pem to rsa code
$privateKey = 'set pem file data';
$rsa = new RSA();
$rsa->loadKey($privateKey);
$rsaPrivateKey = $rsa->getPrivateKey();
dd($rsaPrivateKey);

Additionally, if we need to convert a public key from pem to RSA then we can convert using this code.

// for public key: pem to rsa.
$publicKey = 'set pem file data';
$rsa = new RSA();
$rsa->loadKey($publicKey);
$rsa->setPublicKey($publicKey);
$rsaPublicKey = $rsa->getPublicKey();
dd($rsaPublicKey);

Let’s see a real life implementation of Asymmetric Encryption:

Let’s assume we are making a transaction with a bank as a merchant. Bank provided us a public key and we have shared our public key to the bank. From our end, we will encrypt our transaction request data using our private key and send it to the bank. Bank will decrypt the data using our provided public key. Bank then process the data and send us an encrypted response using their private key. After receiving the bank’s response we will decrypt using their public key to get the plain response.

In addition to that, Bank has asked us to send a signature with every transaction request. They also told us that we need to decrypt the decoded Sensitive Data using Merchant Private Key with PKCS1Padding Algorithm. The signature will be generated using SHA256withRSA signature algorithm.

Now, We will make an api call to initiate a transaction to the bank’s end.

public  function signatureGenerate($data){
   $private_key = "-----YOUR RSA PRIVATE KEY-----";
   openssl_sign(json_encode($data), $signature, $private_key, OPENSSL_ALGO_SHA256);
   return base64_encode($signature);
}   


public function encryptDataWithPublicKey($data){
   $public_key = "-----YOUR PUBLIC KEY-----";
   openssl_public_encrypt(json_encode($data), $encryptedData, $public_key, OPENSSL_PKCS1_PADDING);
   return base64_encode($encryptedData);
}


public function decryptDataWithPrivateKey($cryptText){
   $private_key = "-----YOUR RSA PRIVATE KEY-----";
   openssl_private_decrypt(base64_decode($cryptText), $plainText, $private_key, OPENSSL_PKCS1_PADDING);
   return json_decode($plainText, true);
}


public function HttpPostMethod($postURL, $postData, $authToken = null)
{
   try {
       $curl = curl_init($postURL);
       $postData = json_encode($postData);
       $header = array(
           'Content-Type:application/json'
       );

       if($authToken){
           $header[] = 'token:' . $authToken;
       }


       curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
       curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
       curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
       curl_setopt($curl, CURLOPT_POSTFIELDS, $postData);
       curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
       curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
       curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);


       $resultdata = curl_exec($curl);


       $err = curl_error($curl);
       $code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
       $curlErrorNo = curl_errno($curl);


       $ResultArray = json_decode($resultdata, true);
       curl_close($curl);
       return $ResultArray;
   } catch (Exception $exception) {
       echo 'Failed to Connect with Bank. Please try again later';
       exit;
   }


}


initTransaction($merchantId, $merchantAccountNumber, $orderId){
   $postUrl = 'api.your-bank.com/api/payment/initialize';
   $plainData = array(
       'merchant_id' => $merchantId,
       'order_id' => $orderId
   );
   $postData = array(
       'account_number' => $merchantAccountNumber,
       'sensitiveData' => $this->encryptDataWithPublicKey($sensitiveData),
       'signature' => $this->signatureGenerate($sensitiveData)
   );


   return $this->HttpPostMethod($postUrl, $postData);
}
$encryptedResponse = $this->initTransaction('MER1234', 'ACC12345', 'ORD123456');
$plainResponse = $this->decryptDataWithPrivateKey($encryptedResponse['sensitiveData']);
dd($plainResponse);

Bonus:
Here is a useful link to RSA Signature/Generation & Validation

Things to consider when choosing an Encryption Algorithm:

  1. Level of security required.
  2. Speed of encryption/decryption.
  3. Key management complexity.
  4. Resource constraints.

Where encryption algorithms are used

  1. Secure communication (e.g., emails, VPNs)
  2. Data storage (e.g., databases, file systems)
  3. Financial transactions (e.g., online banking)
  4. Password protection
  5. Digital signatures

The post Securing Sensitive Data with Encryption Algorithms appeared first on ProdSens.live.

]]>
https://prodsens.live/2024/01/28/securing-sensitive-data-with-encryption-algorithms/feed/ 0
How to make resources more reusable in Laravel https://prodsens.live/2023/12/26/how-to-make-resources-more-reusable-in-laravel/?utm_source=rss&utm_medium=rss&utm_campaign=how-to-make-resources-more-reusable-in-laravel https://prodsens.live/2023/12/26/how-to-make-resources-more-reusable-in-laravel/#respond Tue, 26 Dec 2023 22:25:24 +0000 https://prodsens.live/2023/12/26/how-to-make-resources-more-reusable-in-laravel/ how-to-make-resources-more-reusable-in-laravel

When working with Laravel API, we utilize resources to manage the process of returning collections in each response.…

The post How to make resources more reusable in Laravel appeared first on ProdSens.live.

]]>
how-to-make-resources-more-reusable-in-laravel

When working with Laravel API, we utilize resources to manage the process of returning collections in each response.

But, How can we do this with a single resource file to avoid messy file structures?

And how can we make our resources more reusable for each operation, especially in something like ( index & show ),

We can differentiate between inside responses using this route name,

So If we don’t want to show all attributes in the index, we can hide them from the index resource.

Here’s our example:

  • We defined our route in the api.php code:
Route::apiResource('/posts', ApiPostController::class, ['only' => ['index', 'show']]);
  • Now in our resource, We put a condition when the request coming from a route named posts.show:
        $routeShowPost = $request->routeIs('posts.show');

And here’s our PostResource, with the power of mergeWhen(), we can show or hide the attributes from the resource:



namespace AppHttpResources;

use IlluminateHttpResourcesJsonJsonResource;
use IlluminateSupportFacadesRoute;

class PostResource extends JsonResource
{
    public function toArray($request)
    {
        $routeShowPost = $request->routeIs('posts.show');

        return [
            'id' => $this->id,
            'title' => $this->title,
            'image' => $this->image,
            'created_at' => $this->created_at,
            $this->mergeWhen($routeShowPost, [
                'content' => $this->content,
                'comments' => CommentResource::collection($this->whenLoaded('comments'))
            ]),
            'user' => UserResource::make($this->whenLoaded('user')),
            'category' => GeneralResource::make($this->whenLoaded('category')),
            'tags' => GeneralResource::collection($this->whenLoaded('tags')),
        ];
    }
}

In our example, we show the post’s content and comments only when the route is posts.show.

Thanks for reading,

The post How to make resources more reusable in Laravel appeared first on ProdSens.live.

]]>
https://prodsens.live/2023/12/26/how-to-make-resources-more-reusable-in-laravel/feed/ 0
How to Serve Laravel Apps With Valet on MacOS https://prodsens.live/2023/12/11/how-to-serve-laravel-apps-with-valet-on-macos/?utm_source=rss&utm_medium=rss&utm_campaign=how-to-serve-laravel-apps-with-valet-on-macos https://prodsens.live/2023/12/11/how-to-serve-laravel-apps-with-valet-on-macos/#respond Mon, 11 Dec 2023 01:24:37 +0000 https://prodsens.live/2023/12/11/how-to-serve-laravel-apps-with-valet-on-macos/ how-to-serve-laravel-apps-with-valet-on-macos

If you’re here, you probably already have Laravel installed on your machine (and you run macOS). If you…

The post How to Serve Laravel Apps With Valet on MacOS appeared first on ProdSens.live.

]]>
how-to-serve-laravel-apps-with-valet-on-macos

If you’re here, you probably already have Laravel installed on your machine (and you run macOS). If you don’t have Laravel set up properly and you use a different operating system, I’ve written a guide to help you set up Laravel.


The Hitchhiker’s Guide to Laravel Setup | DevjavuThe Hitchhiker’s Guide to Laravel Setup | Devjavu

A step by step guide to setting up Laravel on your machine.

favicon
devjavu.space

This is specifically for macOS users who:

  • Have Laravel installed.

  • Would like to run and manage Laravel applications on a single domain (e.g., mylaravelapp.awesome, myapp.app).

  • Would like to run Laravel sites over encrypted TLS (HTTP/2).

  • Would like to share their local sites with the world.

  • Just want to tinker.

Understanding How Valet Works

Valet is a PHP development environment for PHP frameworks, including Laravel, WordPress, etc. Valet configures your Mac to always run Nginx Server in the background when your machine starts.

Using dnsmasq, Valet proxies all requests on the *.test (this can be changed to a custom domain) domain to point to sites installed on your local machine. Valet also allows you to share your sites publicly using local tunnels.

Out of the box, Valet support includes, but is not limited to:

Installation

Valet requires macOS and Homebrew. Before installation, you should make sure that no other programs, such as Apache or Nginx, are binding to your local machine’s port 80.

/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
  • Update brew
brew update
  • Install PHP7.3.
brew install php
  • Install Composer.

  • Download the installer to the current directory.

php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');"
  php -r "if (hash_file('sha384', 'composer-setup.php') === 'a5c698ffe4b8e849a443b120cd5ba38043260d5c4023dbf93e1558871f1f07f58274fc6f4c93bcfd858c6bd0775cd8d1') { echo 'Installer verified'; } else { echo 'Installer corrupt'; unlink('composer-setup.php'); } echo PHP_EOL;"
  • Run the installer.
php composer-setup.php
  • Remove the installer.
php -r "unlink('composer-setup.php');"
  • Install Valet with Composer.
composer global require laravel/valet

To have the Valet command available globally on your system, make sure you have the ~/.composer/vendor/bin directory in your system’s “PATH”.

You can also see how to add the bin folder to your path here.

Configure and install Valet and Dnsmasq to always run when you start your machine:

valet install

Once Valet is installed, try pinging any *.test domain on your terminal using a command such as ping foobar.test. If Valet is installed correctly, you should see this domain responding on 127.0.0.1.

Using a Custom Domain

If you would like to use a different domain other than the default (.test), you can simply tell Valet to use a new domain name:

valet tld new-name

e.g

valet tld app

You should see an output on your terminal verifying that your new domain has been updated:

Restarting dnsmasq...
Valet is configured to serve for TLD [.app]
Restarting php...
Restarting nginx...
Your Valet TLD has been updated to [app].

Valet will automatically start serving your projects at *.app.

Serving Laravel Sites

Once Valet is installed, you’re ready to start serving sites. First, you’ll need to configure a folder where Valet should search for your sites. Think of this as your htdocs folder (if you ever used Xampp or a similar tool).

Create a folder where you’ll have your Laravel sites:

mkdir ~/Laravel_Sites/

Navigate into that directory:

cd ~/Laravel_Sites/

Now run:

valet park

The park command will register your current directory as a path that Valet should search for your sites.

You can proceed to create a new Laravel application in the same folder.

laravel new sleek_site

Your new site should now be accessible at http://sleek_site.app.

Securing Local Sites With TLS

You can serve your Laravel sites locally over HTTPS, thanks to Valet. Simply change into your site directory (~/Laravel_Sites) and run:

valet secure site_name # e.g valet secure sleek_site

You should now be able to access your Laravel application at https://sleek_site.app.

Sharing Local Sites

Valet comes coupled with ngrok for sharing your local sites on a public URL. No additional software installation is required. To share your local site, navigate into your project directory and run

cd sleek_site

valet serve

You should see a server running in your terminal.

Terminal

You can publicly access your Laravel site by opening the URL http://5e44d238.ngrok.io/ in your browser or from a secure source via http://5e44d238.ngrok.io/.

At this point, you’ve successfully set up Valet to serve Laravel applications locally.

Cheers ☕

The post How to Serve Laravel Apps With Valet on MacOS appeared first on ProdSens.live.

]]>
https://prodsens.live/2023/12/11/how-to-serve-laravel-apps-with-valet-on-macos/feed/ 0