Invitation

js

Monday, January 6, 2025

Importent softwares to install for Developers after installing UBUNTU

PHP
sudo apt install php libapache2-mod-php

MYSQL
sudo apt install mysql-server


Install .deb file in ubuntu
sudo dpkg -i package-name.deb

Wednesday, January 1, 2025

Printer sharing Windows 11

 

Sharing a printer in Windows 11 involves configuring the printer to be accessible to other users on your network. Here's how you can do it:


Step 1: Enable Printer Sharing

  1. Open Settings:

    • Press Windows + I to open the Settings app.
  2. Go to Network & Sharing Settings:

    • Navigate to Network & Internet > Advanced network settings.
    • Under "More settings," click Advanced sharing settings.
  3. Turn on Network Discovery and File/Printer Sharing:

    • Expand Private network (or your current network profile) and enable Network discovery and File and printer sharing.
    • Repeat the steps for Public network if required, but it’s safer to keep sharing on private networks only.

Step 2: Share the Printer

  1. Access Printer Properties:

    • Press Windows + S, type Control Panel, and open it.
    • Go to Hardware and Sound > Devices and Printers.
    • Right-click the printer you want to share and select Printer properties.
  2. Enable Sharing:

    • Go to the Sharing tab.
    • Check the box Share this printer.
    • Optionally, specify a Share name (keep it simple and unique).
  3. Install Additional Drivers (Optional):

    • If other devices on the network use different operating systems, click Additional Drivers and install the required drivers.

Step 3: Connect the Printer on Another Device

  1. Find the Shared Printer:

    • On another device, press Windows + S, type \[YourComputerName], and hit Enter.
    • Replace [YourComputerName] with the name of the computer sharing the printer. (Find this in Settings > System > About > Device name.)
  2. Add the Printer:

    • The shared printer should appear. Right-click it and choose Connect.
    • If prompted, install the printer driver.

Step 4: Test the Printer

  • Print a test page from another computer to ensure everything is working correctly.

If you encounter any issues, ensure:

  • Both devices are on the same network.
  • The printer is powered on and connected.
  • Firewalls or antivirus software aren’t blocking the connection.

Sunday, December 29, 2024

Laravel as backend and React as frontend

 

Here's an outline for building a project using Laravel as the backend and React as the frontend, with the requested pages: a login page, a register user page, and a dashboard page.

Project Setup

Backend: Laravel

  1. Install Laravel

    composer create-project --prefer-dist laravel/laravel backend
    
  2. Set Up Database

    • Configure .env file with your database credentials.
    • Run migrations:
      php artisan migrate
      
  3. Install Laravel Breeze (API) Laravel Breeze provides authentication scaffolding.

    composer require laravel/breeze --dev
    php artisan breeze:install api
    php artisan migrate
    
  4. Set Up API Routes Modify routes/api.php for login, registration, and dashboard:

    use App\Http\Controllers\AuthController;
    
    Route::post('/register', [AuthController::class, 'register']);
    Route::post('/login', [AuthController::class, 'login']);
    Route::middleware('auth:sanctum')->get('/dashboard', [AuthController::class, 'dashboard']);
    
  5. Create AuthController

    php artisan make:controller AuthController
    

    In AuthController.php:

    namespace App\Http\Controllers;
    
    use Illuminate\Http\Request;
    use App\Models\User;
    use Illuminate\Support\Facades\Auth;
    use Illuminate\Support\Facades\Hash;
    
    class AuthController extends Controller
    {
        public function register(Request $request)
        {
            $request->validate([
                'name' => 'required|string|max:255',
                'email' => 'required|string|email|max:255|unique:users',
                'password' => 'required|string|min:8',
            ]);
    
            $user = User::create([
                'name' => $request->name,
                'email' => $request->email,
                'password' => Hash::make($request->password),
            ]);
    
            return response()->json(['message' => 'User registered successfully'], 201);
        }
    
        public function login(Request $request)
        {
            $request->validate([
                'email' => 'required|email',
                'password' => 'required',
            ]);
    
            if (!Auth::attempt($request->only('email', 'password'))) {
                return response()->json(['message' => 'Invalid credentials'], 401);
            }
    
            $token = $request->user()->createToken('auth_token')->plainTextToken;
    
            return response()->json(['access_token' => $token, 'token_type' => 'Bearer']);
        }
    
        public function dashboard(Request $request)
        {
            return response()->json(['message' => 'Welcome to the dashboard']);
        }
    }
    

Frontend: React

  1. Create React App

    npx create-react-app frontend
    cd frontend
    
  2. Install Axios for API Requests

    npm install axios
    
  3. Set Up Routes Install React Router:

    npm install react-router-dom
    

    Create src/routes.js:

    import React from 'react';
    import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';
    import Login from './pages/Login';
    import Register from './pages/Register';
    import Dashboard from './pages/Dashboard';
    
    const AppRoutes = () => (
        <Router>
            <Routes>
                <Route path="/" element={<Login />} />
                <Route path="/register" element={<Register />} />
                <Route path="/dashboard" element={<Dashboard />} />
            </Routes>
        </Router>
    );
    
    export default AppRoutes;
    
  4. Login Page Create src/pages/Login.jsx:

    import React, { useState } from 'react';
    import axios from 'axios';
    
    const Login = () => {
        const [email, setEmail] = useState('');
        const [password, setPassword] = useState('');
    
        const handleLogin = async (e) => {
            e.preventDefault();
            try {
                const response = await axios.post('http://localhost:8000/api/login', { email, password });
                localStorage.setItem('token', response.data.access_token);
                window.location.href = '/dashboard';
            } catch (error) {
                alert('Login failed');
            }
        };
    
        return (
            <form onSubmit={handleLogin}>
                <input type="email" placeholder="Email" value={email} onChange={(e) => setEmail(e.target.value)} />
                <input type="password" placeholder="Password" value={password} onChange={(e) => setPassword(e.target.value)} />
                <button type="submit">Login</button>
            </form>
        );
    };
    
    export default Login;
    
  5. Register Page Create src/pages/Register.jsx:

    import React, { useState } from 'react';
    import axios from 'axios';
    
    const Register = () => {
        const [name, setName] = useState('');
        const [email, setEmail] = useState('');
        const [password, setPassword] = useState('');
    
        const handleRegister = async (e) => {
            e.preventDefault();
            try {
                await axios.post('http://localhost:8000/api/register', { name, email, password });
                alert('Registration successful');
                window.location.href = '/';
            } catch (error) {
                alert('Registration failed');
            }
        };
    
        return (
            <form onSubmit={handleRegister}>
                <input type="text" placeholder="Name" value={name} onChange={(e) => setName(e.target.value)} />
                <input type="email" placeholder="Email" value={email} onChange={(e) => setEmail(e.target.value)} />
                <input type="password" placeholder="Password" value={password} onChange={(e) => setPassword(e.target.value)} />
                <button type="submit">Register</button>
            </form>
        );
    };
    
    export default Register;
    
  6. Dashboard Page Create src/pages/Dashboard.jsx:

    import React, { useEffect, useState } from 'react';
    import axios from 'axios';
    
    const Dashboard = () => {
        const [message, setMessage] = useState('');
    
        useEffect(() => {
            const fetchDashboard = async () => {
                try {
                    const token = localStorage.getItem('token');
                    const response = await axios.get('http://localhost:8000/api/dashboard', {
                        headers: { Authorization: `Bearer ${token}` },
                    });
                    setMessage(response.data.message);
                } catch (error) {
                    alert('Failed to load dashboard');
                    window.location.href = '/';
                }
            };
    
            fetchDashboard();
        }, []);
    
        return <h1>{message}</h1>;
    };
    
    export default Dashboard;
    
  7. Integrate Routes Update src/index.js:

    import React from 'react';
    import ReactDOM from 'react-dom';
    import AppRoutes from './routes';
    
    ReactDOM.render(<AppRoutes />, document.getElementById('root'));
    

Run the Application

  • Start Laravel server:

    php artisan serve
    
  • Start React development server:

    npm start
    

Now, you have a functional Laravel-React project with a login page, register page, and dashboard!

Monday, December 23, 2024

VS Code: Importent extensions

 angular.ng-template
batisteo.vscode-django
bmewburn.vscode-intelephense-client
bradlc.vscode-tailwindcss
christian-kohler.npm-intellisense
codeium.codeium
dbaeumer.vscode-eslint
dsznajder.es7-react-js-snippets
eamodio.gitlens
esbenp.prettier-vscode
formulahendry.auto-close-tag
formulahendry.code-runner
mikestead.dotenv
ms-python.debugpy
ms-python.python
ms-python.vscode-pylance
ms-vscode-remote.remote-wsl
ms-vscode.powershell
oderwat.indent-rainbow
rangav.vscode-thunder-client
ritwickdey.liveserver
xabikos.javascriptsnippets

Thursday, December 19, 2024

Laravel: Explain Auth::user() in Laravel

 

Auth::user() in Laravel is a method provided by the Authentication Facade (Auth) that retrieves the currently authenticated user for the current request. It is one of the core features of Laravel's authentication system, allowing you to access user details easily.


Key Features of Auth::user()

  1. Fetches the Authenticated User:

    • Returns the instance of the currently logged-in user as an object.
    • If no user is authenticated, it returns null.
  2. User Object:

    • The returned object is an instance of the User model (or the model specified in the auth.php configuration for the guard being used).
    • You can access any property or method defined in the User model, such as:
      $user = Auth::user();
      echo $user->name;  // Access 'name' property
      echo $user->email; // Access 'email' property
      
  3. Works with Guards:

    • Auth::user() works with the default web guard unless a specific guard is used.
    • For example, for API authentication:
      $user = Auth::guard('api')->user();
      
  4. Use Cases:

    • Displaying user-specific information (e.g., profile data).
    • Checking user roles or permissions.
    • Fetching data related to the authenticated user.

Example Usage

1. In a Controller

use Illuminate\Support\Facades\Auth;

class ProfileController extends Controller
{
    public function show()
    {
        $user = Auth::user(); // Get the authenticated user
        return view('profile', ['user' => $user]); // Pass user to the view
    }
}

2. In a Blade View

@if (Auth::check())  <!-- Check if user is logged in -->
    <h1>Welcome, {{ Auth::user()->name }}!</h1>
@else
    <p>Please log in to access your account.</p>
@endif

3. Using Auth::user() with Relationships

If your User model has relationships defined, you can use them:

$posts = Auth::user()->posts; // Assuming the User model has a 'posts' relationship

Common Scenarios

Check if a User is Logged In

Use Auth::check() to determine if a user is logged in:

if (Auth::check()) {
    echo "User is logged in.";
    $user = Auth::user(); // Fetch authenticated user
} else {
    echo "User is not logged in.";
}

Customize the Authenticated User

You can add additional methods or attributes to the User model and access them using Auth::user():

class User extends Authenticatable
{
    public function isAdmin()
    {
        return $this->role === 'admin';
    }
}

Then use it:

if (Auth::user()->isAdmin()) {
    echo "Welcome, Admin!";
}

How it Works

  1. Session-Based Authentication (web Guard):

    • When a user logs in, their ID is stored in the session.
    • Auth::user() fetches the user from the database using the ID stored in the session.
  2. Token-Based Authentication (api Guard):

    • For API requests, the token is included in the request (e.g., in the headers).
    • The api guard verifies the token and retrieves the corresponding user.

Handling Edge Cases

  1. User Not Logged In:

    • If no user is logged in, Auth::user() returns null. Always handle this scenario:
      if (Auth::user()) {
          echo "Hello, " . Auth::user()->name;
      } else {
          echo "Please log in.";
      }
      
  2. Using Guards:

    • When using multiple guards, you must specify the guard explicitly:
      $user = Auth::guard('api')->user();
      

Summary

  • Auth::user() retrieves the currently authenticated user.
  • It returns an instance of the User model or null if no user is logged in.
  • Commonly used to access user details, check authentication, or interact with user-specific data.
  • Works seamlessly with Laravel's authentication guards and can handle both session-based and token-based authentication.

English Phrases, Idioms, and Proverbs

English Phrases, Idioms, and Proverbs 1. A blessing in disguise Meaning: Something that seems bad at first but turns out to be good...