Laravel Route apiResource

I'm using&nbsp;<code>apiResource</code>&nbsp;in Route which is using&nbsp;<code>(index, create, show, update, destroy)</code>&nbsp;methods in&nbsp;<code>exampleController</code>. When I would like to use show method the route wont work. what shall I do? I think it is because of&nbsp;<code>{fruits}</code>&nbsp;but I do not how solve it?

I'm using apiResource in Route which is using (index, create, show, update, destroy) methods in exampleController. When I would like to use show method the route wont work. what shall I do? I think it is because of {fruits} but I do not how solve it?

Route::apiResource('/fruit/{fruits}/apples', 'exampleController');

My route in browser is:

localhost:8000/api/fruits/testFruitSlug/apples/testAppleSlug


Laravel API Response - Simple Laravel API response wrapper

Laravel API Response - Simple Laravel API response wrapper

Laravel API Response is a good package that we can use to create API responses easily.

Simple and ready to use API response wrapper for Laravel - Simple Laravel API response wrapper.

Installation
  1. Install package through composer: $ composer require obiefy/api-response
  2. publish config file : php artisan vendor:publish --tag=api-response
Basic usage

Create and return JSON response:

use Obiefy\API\Facades\API;
...
public function index()
{
    $users = User::all();
return API::response(200,'users list', $users);

}

Or you can use helper function:

use Obiefy\API\Facades\API;
...
public function index()
{
$users = User::all();

return api()-&gt;response(200, 'users list', $users);

}

Advanced usage

1. General example

use Obiefy\API\Facades\API;
...
public function index()
{
$users = User::all();

return API::response(200, 'users list', $users);

}

result:

{
"STATUS": 200,
"MESSAGE": "users list",
"DATA": [
{"name": "user name"}
]
}

2. Success response

return api()->ok('Success message`, [
'name' => 'Obay Hamed'
]);

result:

{
"STATUS": 200,
"MESSAGE": "Success message",
"DATA": {"name": "Obay Hamed"}
}

you can also return success message with out passing parametters

return api()->ok();

in this case response message will be the default message from config file config('api.messages.success') the same thing for api()->notFound() and api()->validation().

Source Code: https://github.com/obiefy/api-response

Thanks for reading

If you liked this post, share it with all of your programming buddies!

Follow me on Facebook | Twitter

Further reading

Laravel 5.8 Tutorial for Beginners

Tutorial Laravel 6 with Docker and Docker-Compose

How to Laravel 6 Database Migrations - Add Admin Role to Users

Laravel 6 Release New Features and Upgrade

Laravel 6 CRUD Application Tutorial


How to Creat an API in Laravel with Passport

How to Creat an API in Laravel with Passport

You will be learning how to build an API in Laravel Passport and how to generate a token for a user. This token is used to authenticate the user.

In this post, I will be creating an API with Laravel Passport. Laravel Passport provides an easy way to perform API authentication. You will be learning how to build an API in Laravel Passport and how to generate a token for a user. This token is used to authenticate the user.

Installation

Let’s start by installing Laravel Passport via Composer.

composer require laravel/passport

Laravel Passport will create its own tables to store client and access tokens. So we should migrate the database after installing Passport.

php artisan migrate

Next, we will have to create the encryption keys that are needed to generate secure access tokens. We can do this by executing the following command:

php artisan passport:install

Add the HasApiTokens trait to the User model.

<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Laravel\Passport\HasApiTokens;
class User extends Authenticatable
{
    use HasApiTokens, Notifiable;
    protected $fillable = [
        'name', 'email', 'password',
    ];
    protected $hidden = [
        'password', 'remember_token',
    ];
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];
}

In the AuthServiceProvider we should call Passport::routes() within the boot method. This will register routes that are needed to issue access tokens and revoke tokens.

<?php
namespace App\Providers;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
use Laravel\Passport\Passport;
class AuthServiceProvider extends ServiceProvider
{
    protected $policies = [];
    public function boot()
    {
        $this->registerPolicies();
        Passport::routes();
    }
}

There is one more thing that we need to do before we can start building the API. In the config/auth.php change the guards.api.driver to passport.

Defining a route

For now, we will be using a very simple example in the routes/api.php.

<?php

use App\Book;
use App\Http\Resources\Book as BookResource;
use Illuminate\Http\Request;

Route::middleware('auth:api')->get('/books', function (Request $request) {
    return BookResource::collection(Book::all());
});
Creating a user

To be able to test the endpoint we have to create a user. We will be creating a command to do that for us. Let’s start by creating the command:

php artisan make:command CreateUserCommand

The command will create a user and a token based on some options that have to get passed to the command.

<?php

namespace App\Console\Commands;

use App\User;
use Illuminate\Console\Command;

class CreateUserCommand extends Command
{
    protected $signature = 'user:create {--name=} {--email=} {--password=} {--token=}';

    protected $description = 'Create user and token';

    public function handle()
    {
        $user = User::create([
            'name' => $this->option('name'),
            'email' => $this->option('email'),
            'password' => bcrypt($this->option('password'))
        ]);

        $token = $user->createToken($this->option('token'))->accessToken;

        $this->line($token);
    }
}

As you can see we have to pass four options to the command:

  • name
  • email
  • password
  • token, which is the name of the token

Create a user by executing the following command:

php artisan user:create --name=Laravel [email protected] --password=secret --token=LaravelToken

After executing the command you should see a token in your console. Copy this token.

Note:
Make sure that the token that gets printed in the console does not contain any line breaks.

Sending a request to the API

To send a GET request to the /api/books endpoint we have to add the token that you just copied as a Bearer token. To do that in Postman, click on the Authorization tab and select Bearer Token in the Type select box.

Furthermore, in the Headers tab add the Accept key with value application/json.

If the request was successful, you will receive a JSON array with books and status code 200.

Making an endpoint public

In the example above we used Laravel Passport for the API authentication. In some situations, you might want to have a public endpoint. Making an endpoint public is very easy. All you have to is remove the auth:api middleware from your route. This means that anybody can send a request to the endpoint without any form of authentication.

This how you set up an API with Laravel Passport. Please share your thoughts on this article. Make sure to check out my other posts as well. A lot of my content is about Laravel. Feel free to leave a comment if you have any feedback, questions or want me to write about another Laravel related topic.

Thank for read and keep visitting!

Postman and laravel delete api

I am trying to make laravel api, getting request is all working fine but when I use delete request, it show this<a href="https://i.stack.imgur.com/rHB2g.png" target="_blank"><img src="https://i.stack.imgur.com/rHB2g.png"></a>

I am trying to make laravel api, getting request is all working fine but when I use delete request, it show this

Please help , what can I do for this.

And this is in my web.php,

Route::delete('article/{id}','[email protected]');

And in ArticleController

public function destroy($id)
{
    $article=Article::FindOrFail($id);
    if($article->delete()){
        return new ArticleResources($article);
    }
}