PHP code example of mleczek / laravel-rest

1. Go to this page and download the library: Download mleczek/laravel-rest 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/ */

    

mleczek / laravel-rest example snippets


'providers' => [
    Mleczek\Rest\RestServiceProvider::class,
]

'providers' => [
    App\Providers\ContextServiceProvider::class,
]

$with = [
    User::class => 'messages',
    Message::class => ['author', 'recipient'],
]

class UserWithContext
{
    public function messages()
    {
        return Auth::check() && Auth::user()->is_root;
    }
}

$with = [
    User::class => UserWithContext::class,
]

$sort = [
    Message::class => MessageSortContext::class,
]

class MessageSortContext
{
    public function latest($query)
    {
        $query->latest();
    }
}

$filter = [
    User::class => UserFilterContext::class,
]

class UserFilterContext
{
    public function scoreAbove($query, $value)
    {
        // Validation of the $value argument...
        
        $query->where('score', '>', $value);
    }
}

response()->item($query);

return response()->item(User::query());

public function show()
{
    $user = rest()->item(User::query());
    $this->authorize('show', $user); // bad usage, see below solution

    return response()->item($user);
}

public function show()
{
    $user = User::first();
    $this->authorize('show', $user);
    
    return response()->item($user);
}

response()->collection($query);

return response()->collection(User::query());

return response()->collection(User::where('is_root', false));

public function show()
{
    $users = rest()->collection(User::query());
    // Some operations goes here...
    // $users->count  - number of retrieved models [0,limit]
    // $users->limit  - max number of retrieved models
    // $users->offset - number of skipped models
    // $users->data   - retrieved models

    return response()->collections($users);
}

response()->accepted();

response()->noContent();

response()->created($model[, $location]);

response()->updated([$model]);

response()->patched([$model]);

response()->deleted();

protected $sort = [
    // Your context classes...
    User::class => \Mleczek\Rest\Context\DefaultSortContext::class,
];

protected $filter = [
    // Your context classes...
    User::class => \Mleczek\Rest\Context\DefaultFilterContext::class,
];

php artisan vendor:publish --provider="Mleczek\Rest\RestServiceProvider"

users?with=messages&offset=3,messages.5