PHP code example of amanank / hal-client

1. Go to this page and download the library: Download amanank/hal-client library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

amanank / hal-client example snippets




php artisan vendor:publish --tag=config --provider="Amanank\HalClient\Providers\HalClientServiceProvider"

return [
    'base_uri' => env('HAL_API_BASE_URI', 'https://example.com/api/v1/'),
    'headers' => [
        'Authorization' => 'Bearer ' . env('HAL_API_TOKEN'),
        'Accept' => 'application/hal+json',
    ],
];

use Amanank\HalClient\Models\Discovered\User;
use Amanank\HalClient\Models\Discovered\Post;
use Amanank\HalClient\Models\Discovered\Tag;
use Amanank\HalClient\Models\Discovered\Comment;

// Create a new user
$user = new User();
$user->username = 'john.doe';
$user->email = '[email protected]';
$user->save();

// Create a new post
$post = new Post();
$post->title = 'My First Post';
$post->content = 'This is the content of my first post.';
$post->user()->associate($user);
$post->save();

// Create a new tag
$tag = new Tag();
$tag->name = 'PHP';
$tag->save();

// Create a new comment
$comment = new Comment();
$comment->content = 'Great post!';
$comment->post()->associate($post);
$comment->user()->associate($user);
$comment->save();

namespace App\Models;

use Amanank\HalClient\Models\Discovered\User as DiscoveredUser;

class User extends DiscoveredUser {
    // Add your custom methods or properties here
}

use App\Models\User;
use App\Models\Post;
use App\Models\Tag;
use App\Models\Comment;

// Create a new user
$user = new User();
$user->username = 'john.doe';
$user->email = '[email protected]';
$user->save();

// Update a user
$user = User::find(1);
$user->email = '[email protected]';
$user->save();

use Amanank\HalClient\Models\Discovered\User;

// Get paginated users
$users = User::get($page = 1, $size = 10, $sort = 'username');

// Find users by last name
$usersByLastName = User::findByLastName('Doe');

// Get user by email
$userByEmail = User::getByEmail('[email protected]');

use App\Models\User;
use App\Models\Post;
use App\Models\Tag;
use App\Models\Comment;

// Get user's posts
$user = User::find(1);
$posts = $user->posts;

// Get post's comments
$post = Post::find(1);
$comments = $post->comments;

// Attach a tag to a post
$post = Post::find(1);
$tag = Tag::find(1);
$post->tags()->attach($tag);

// Detach a tag from a post
$post->tags()->detach($tag);

use Amanank\HalClient\Models\Discovered\Enums\UserStatusEnum;
use App\Models\User;

// Set user status
$user = User::find(1);
$user->status = UserStatusEnum::ACTIVE;
$user->save();

// Get users with a specific status
$activeUsers = User::where('status', UserStatusEnum::ACTIVE)->get();