Showing posts with label php. Show all posts
Showing posts with label php. Show all posts

Laravel create a api with sactum

To create a Laravel API with Sanctum, you can follow these steps:

Install Laravel Sanctum: 


composer require laravel/sanctum

Publish the Sanctum configuration and migration files:


php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider"

Run the Sanctum migrations:


php artisan migrate

Add the HasApiTokens trait to your User model:

use Laravel\Sanctum\HasApiTokens;

class User extends Authenticatable
{
    use HasApiTokens, Notifiable;
   
    // ...
}


Register the Sanctum middleware in your Kernel class:


protected $middlewareGroups = [
    // ...
    'api' => [
        EnsureFrontendRequestsAreStateful::class,
        'throttle:60,1',
        \Illuminate\Routing\Middleware\SubstituteBindings::class,
        \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreAuthorized::class,
    ],
];


Generate a new API token for your authenticated user:


$token = $user->createToken('API Token')->plainTextToken;

Use the generated API token to authenticate your API requests:


Authorization: Bearer {api_token}

You can now create your API routes and controllers as usual. To protect a route with Sanctum, you can use the auth:sanctum middleware:


Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
    return $request->user();
});


CRUD EXAMPLE

Next, let's create a Product model and migration file to store our product data. Run the following commands to create them:


php artisan make:model Product -m

This will create a Product.php model file and a migration file for the products table.

In the migration file, add the following code to define the columns for the products table:

public function up()
{
    Schema::create('products', function (Blueprint $table) {
        $table->id();
        $table->string('name');
        $table->text('description');
        $table->decimal('price', 8, 2);
        $table->timestamps();
    });
}

Next, run the migration to create the products table:


php artisan migrate


Now, let's create a ProductController to handle the CRUD operations. Run the following command to generate a new controller:

php artisan make:controller ProductController --api

This will create a new ProductController.php file in the app/Http/Controllers folder with boilerplate code for a RESTful API.

Add the following code to the ProductController to define the CRUD methods:

use App\Models\Product;
use Illuminate\Http\Request;

class ProductController extends Controller
{
    public function index()
    {
        $products = Product::all();
        return response()->json($products);
    }

    public function store(Request $request)
    {
        $product = Product::create($request->all());
        return response()->json($product);
    }

    public function show(Product $product)
    {
        return response()->json($product);
    }

    public function update(Request $request, Product $product)
    {
        $product->update($request->all());
        return response()->json($product);
    }

    public function destroy(Product $product)
    {
        $product->delete();
        return response()->json(null, 204);
    }
}


Next, let's protect our API routes with Sanctum. In the routes/api.php file, add the following code to define the routes and apply the auth:sanctum middleware:

use App\Http\Controllers\ProductController;
use Illuminate\Support\Facades\Route;

Route::middleware('auth:sanctum')->group(function () {
    Route::apiResource('products', ProductController::class);
});

Now, to test our API, we can use tools like curl or Postman to send HTTP requests to the API endpoints.


For example, to create a new product, we can send a POST request to http://localhost:8000/api/products with a JSON payload:

{
    "name": "Product A",
    "description": "This is product A",
    "price": 19.99
}

To retrieve all products, we can send a GET request to http://localhost:8000/api/products.

To update a product, we can send a PUT request to http://localhost:8000/api/products/{product_id} with a JSON payload:

{
    "name": "Product A (updated)",
    "description": "This is product A (updated)",
    "price": 29.99
}


To delete a product, we can send a DELETE request to http://localhost:8000/api/products/{product_id}.


I hope this helps you get started with creating a Laravel API with Sanctum.




How connect mysqli with insert record using PHP

To connect to MySQL database using mysqli and insert a record using PHP, you can follow the steps below:

  1. Establish a connection to the MySQL database using mysqli_connect() function. The function takes four parameters: host, username, password, and database name. Here's an example code:


$servername = "localhost";
$username = "your_username";
$password = "your_password";
$dbname = "your_database_name";

$conn = mysqli_connect($servername, $username, $password, $dbname);

// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}


  1. Once you've established a connection, you can use the mysqli_query() function to execute the SQL query to insert the record. Here's an example code that inserts a record into a "users" table:

$sql = "INSERT INTO users (first_name, last_name, email) VALUES ('John', 'Doe', 'johndoe@example.com')";

if (mysqli_query($conn, $sql)) {
echo "Record inserted successfully";
} else {
echo "Error inserting record: " . mysqli_error($conn);
}



In this example, the SQL query inserts a record with the first name, last name, and email values into the "users" table. The mysqli_query() function executes the query, and if it is successful, the message "Record inserted successfully" is displayed. If there is an error, the message "Error inserting record" along with the error message is displayed.

  1. After executing the query, close the database connection using the mysqli_close() function:

mysqli_close($conn);


That's it! You've now connected to MySQL using mysqli and inserted a record into a table using PHP.

How to add custom function in WordPress

Add custom functions to WordPress by creating a child theme or using a plugin. Here are the steps to add a custom function in WordPress:

  1. Create a child theme: A child theme is a theme that inherits the functionality and styling of its parent theme. Creating a child theme allows you to modify the functionality of the parent theme without affecting its core files. To create a child theme, create a new folder in the wp-content/themes directory and add a style.css file with the following information:

/*
Theme Name: My Child Theme
Template: parent-theme-folder-name
*/



Replace 'My Child Theme' with the name of your child theme and 'parent-theme-folder-name' with the name of the parent theme folder.

  1. Create a functions.php file: Inside your child theme folder, create a new file called functions.php. This file will contain your custom functions.

  2. Write your custom function: Add your custom PHP function to the functions.php file. Here's an example:


function my_custom_function() {
// your code here
}



  1. Add your custom function to WordPress: To add your custom function to WordPress, you need to use an action or filter hook. For example, if you want to add your custom function to the 'wp_head' hook, you can use the following code in your functions.php file:


add_action('wp_head', 'my_custom_function');



This code tells WordPress to run your 'my_custom_function' function when the 'wp_head' action is called.

  1. Save your changes and test your function: Save the functions.php file and test your custom function on your website. If everything is working correctly, your custom function should run when the specified hook is triggered.

Note: Be careful when modifying core WordPress files or functions, as it can cause compatibility issues or security vulnerabilities. It's always recommended to use a child theme or plugin to add custom functionality to your WordPress site.


.

how to use multidimensional array in php

 In PHP, a multidimensional array is an array that contains one or more arrays as its elements. It allows you to store data in a hierarchical structure. Here is an example of how to use a multidimensional array in PHP:

// Define a multidimensional array
$students = array(
array("John", "Doe", 25),
array("Jane", "Smith", 22),
array("Bob", "Jones", 28)
);

// Access elements of the multidimensional array
echo $students[0][0]; // Output: John
echo $students[1][1]; // Output: Smith
echo $students[2][2]; // Output: 28


In the example above, we define a multidimensional array called 'students'. Each element of the 'students' array is an array itself, containing three values - the first name, last name, and age of each student.

To access elements of a multidimensional array, you use square brackets to specify the index of each dimension. In the example above, $students[0][0] accesses the first name of the first student, $students[1][1] accesses the last name of the second student, and $students[2][2] accesses the age of the third student.

You can also loop through a multidimensional array using nested loops:

// Loop through the multidimensional array
foreach($students as $student) {
foreach($student as $value) {
echo $value . " ";
}
echo "<br>";
}

// Output:
// John Doe 25
// Jane Smith 22
// Bob Jones 28


In the example above, we use a nested foreach loop to loop through each element of the 'students' array and print out each value. The outer loop iterates over each student, while the inner loop iterates over each value in the student's array.

PHP function call using ajax with example

 To call a PHP function using AJAX, you can follow these steps:

  1. Create a PHP file that contains the function you want to call. For example, let's create a file called 'functions.php' and define a function called 'get_data':

// functions.php
function get_data($param) {
// Perform some operation
return $result;
}


  1. Create an AJAX request in your HTML or JavaScript code. For example, let's use jQuery to make an AJAX request to the 'functions.php' file and call the 'get_data' function:

// index.html or script.js
$.ajax({
url: 'functions.php',
type: 'POST',
data: { action: 'get_data', param: 'some_value' },
success: function(response) {
console.log(response);
}
});



Here, we are using the jQuery.ajax() method to make an AJAX POST request to the 'functions.php' file. We are passing the following parameters:

  • url: The URL of the PHP file.
  • type: The HTTP request method (POST in this case).
  • data: The data to be sent with the request. We are passing two parameters: 'action' and 'param'. The 'action' parameter is the name of the function we want to call ('get_data'), and the 'param' parameter is a value we want to pass as an argument to the function.
  • success: A callback function that will be executed when the request is successful. The 'response' parameter contains the data returned by the PHP function.
  1. In the 'functions.php' file, check the value of the 'action' parameter and call the appropriate function. For example:
// functions.php
if(isset($_POST['action'])) {
$action = $_POST['action'];
switch($action) {
case 'get_data':
$param = $_POST['param'];
$result = get_data($param);
echo json_encode($result);
break;
// Add more cases for other functions
}
}



Here, we are checking the value of the 'action' parameter passed in the AJAX request and calling the appropriate function using a switch statement. In this example, we are calling the 'get_data' function and passing the 'param' value as an argument. We are then encoding the result as JSON and echoing it back to the client.

Note: This is just an example and you will need to modify the code according to your specific requirements and function parameters. Also, make sure to properly validate and sanitize user input to prevent security vulnerabilities.


Laravel : How to get a all records from database

How to Retrieving All Records From Users Table, You may use the table method on the DB facade to begin a query. will get the results using the get method.


<?php

namespace App\Http\Controllers;

use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Controller;

class UserController extends Controller
{
    /**
     * Show a list of all of the application's users.
     *
     * @return Response
     */
    public function index()
    {
        $users = DB::table('users')->get();

        return view('user.index', ['users' => $users]);
    }
}
The get method returns an Illuminate\Support\Collection containing the results where each result is an instance of the PHP stdClass object.


foreach ($users as $user) {
     echo $user->name;
    echo $user->email;
}


Compact function in Laravel

We mostly use compact in Laravel to send the values to the view. Something like this:


<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use Illuminate\Support\Facades\DB;

class CategoryController extends Controller
{
    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Contracts\Support\Renderable
     */
    public function index()
    {
        $categories = DB::table('categories')->get();
        return view('admin.pages.category.view',compact('categories'));
    }
}
Laravel expects an array to be passed to the view helper function. Second argument in view helper function is an array that where keys are the names of the variable and the value are the contents of those variables. These variables will be available in our views to be used.


How to Get generated html content of php script on same server


How to retrieve this HTML source code dynamically via PHP.  with passing query string at the end of the URL to get the result in HTML source code.

And Generating file to store HTML code.


Let's go through the example 

URL:   example.com/report.php?date=2018-01-06

how to call Class direct into function

In function direct call parent class and it's functions using the object,

Parent class now, available to inherit using function before we inherited class to class, can call specific function only.


public function function_name(): CLASS_Name { } 
After the creating a object of the Class $object = new CLASS_Name();

call function of class using object

$obA->index();
The Following complete tutorial with guide to how to call parent class to specific child class's function.
<?php
//Limited return type covariance and argument type contravariance
//how to call Class direct into method.
class A {
  
public function index(){
    echo "test1";
}
  
}
class B extends A {}

class Producer {
    public function test(): A {
      $obA = new A();
      echo $obA->index();
      echo "test2";
    }
}
class ChildProducer extends Producer {
    public function method(): B {}
}

$ob = new Producer();
$ob->test();

?>

PHP : Converts double slashes in a string to a single slash

In this tutorial learn how to Converts double slashes in a string to a single slash, except those found in http:// ,

http://www.example.com//index.php 

becomes: 

http://www.example.com/index.php

Tutorial

PHP : Removes single and double quotes from a string

In this tutorial learn how to Removes single and double quotes from a string using str_replace() method.

Tutorial

PHP : Removes slashes contained in a string

In this tutorial learn how to Removes slashes contained in a string using function with stripslashes() method.


PHP : How to get Number of days in a month

In this tutorial learn how to get number of days in month using function, pass parameter month and year in function only

PHP : Check if variable is a numeric array

In this tutorial learn how to Check if variable is a numeric array in php using a is_array() and array_keys() method - programming technology world

function is_numeric_array($var): bool
{
    if (!is_array($var)) {
        return false;
    }
    
    $keys = array_keys($var);
    return ($keys === array_keys($keys));
}

PHP : Removes a particular value from an array

In this tutorial learn how to remove value from an array (numeric or associative) in php using unset() method.

 function removearrayValue($array, $value)
    {
        $IsNumericArray = true;
        foreach ($array as $key => $item) {
            if ($item === $value) {
                if (!is_int($key)) {
                    $IsNumericArray = false;
                }
                unset($array[$key]);
            }
        }
        if ($IsNumericArray) {
            $array = array_values($array);
        }

        return $array;
    }

PHP : array sort by sub array value

In this tutorial learn how to sort array by sub array value using array_multisort() and array_map() function.
Can sort array ascending(SORT_ASC) or Descending(SORT_DESC) order with Sub Array value.

Pass a array and sub array value

<?php

array_multisort(array_map(function($element) {
      return $element['<sub array value>'];
  }, $array), SORT_ASC, $array);
  

PHP : Check if an array contains any value in a set

In this tutorial Learn How to Check if an array contains any value in a set in php using in_array() method


function array_contains_any_val(array $array, array $subset, bool $strict = false) :bool
{
    $contains = false;
    foreach ($subset as $value) {
        if (in_array($value, $array, $strict)) {
            $contains = true;
            break;
        }
    }
    return $contains;
}

PHP : Create Directory if not available

In this tutorial learn how to create directory using php if directory not created without using command.

/*
*  Create Directory if not available 
*/ 
function createDirectory(string $directory): bool
    {
        return !(!\is_dir($directory) && !@\mkdir($directory, 0777, true) && !\is_dir($directory));
    }

echo createDirectory("demo");


Using the mkdir() method can create a new function and check directory using is_check().



PHP : search index of the value in an array

In this tutorial learn how to search index of the value in an array,  Search for the index of a value in an array.

function search($array, $value)
    {
        return array_search($value, $array, true);
    }

PHP : Append a value to an array

In this tutorial learn how to add value to an array or Append a value to an array in php using array_push() method



function appendelement($array, $value)
    {
        array_push($array, $value);

        return $array;
    }

PHP : Check if an item is in an array

In this tutorial learn how to Check if an item is in an array or not in array using in_array() method

function contains($array, $value)
    {
        return in_array($value, $array, true);
    }


how to call ssh from vs code

 To call SSH from VS Code, you can use the built-in Remote Development extension. This extension allows you to open a remote folder or works...