Laravel get input data from POST request in a rest api - laravel

i'm trying to get input data which i post them from rest api as an json format, but in laravel i can't get them on controller and that return empty array of request
my api route:
Route::group(['prefix' => 'v1', 'namespace' => 'Api\v1'], function () {
$this->post('login', 'ApiController#login');
});
and ApiController:
<?php
namespace App\Http\Controllers\Api\v1;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
class ApiController extends Controller
{
public function login(Request $request)
{
dd($request->all());
}
}
output:
[]
ScreenShot

Problem resolved by adding this line:
Content-type: text/json
to RestClient header

use Input Facade class In my case it was work
use \Illuminate\Support\Facades\Input;
$request = Input::All();

Related

How to upload file using Laravel Guzzle HTTP client

I'm using the Alfresco Rest API from a Laravel application!
To do so, I use the laravel guzzlehttp/guzzle package.
Below is my code.
When I run it, I get a status 400
The documentation of my endpoint can be found here: https://api-explorer.alfresco.com/api-explorer/#!/nodes/createNode
// AlfrescoService.php
namespace App\Services;
use Illuminate\Support\Facades\Http;
use Illuminate\Http\Client\Response;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Pagination\Paginator;
use Illuminate\Support\Collection;
class AlfrescoService
{
public static function apiConnexion()
{
$response = Http::withHeaders([
"Content-Type" => "application/json",
])->post('http://192.168.43.152:8080/alfresco/api/-default-/public/authentication/versions/1/tickets', [
'userId' => 'admin',
'password' => 'admin',
]);
return base64_encode( $response["entry"]["id"] );
}
public static function request2($queryType, String $query, array $data=[])
{
$response = Http::withHeaders([
"Authorization" => "Basic ".self::apiConnexion(),
])->attach(
'attachment', file_get_contents('alfresco/doc.txt'), 'doc.txt'
)->$queryType('http://192.168.43.152:8080/alfresco/api/-default-/public/alfresco/versions/1'.$query, $data);
return $response;
}
}
// AlfrescoController.php
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use App\Services\AlfrescoService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
use MercurySeries\Flashy\Flashy;
class AlfrescoController extends Controller
{
public function storeFile(Request $request) {
$data=["name"=>"My new File.txt", "nodeType"=>"cm:content"];
$response=AlfrescoService::request2("post", "/nodes/-shared-/children", $data);
dd($response->status()); // 400
}
}
I dont understand why you have used $querytype but as you have asked in your heading "How to upload file using Laravel Guzzle HTTP client", so here is the answer for that,
public static function request2($queryType, String $query, array $data=[])
{
$file = fopen('alfresco/doc.txt', 'r')
$response = Http::withToken(self::apiConnexion())
->attach('attachment', $file)
->post($url);
return $response;
}
You can see withToken() method in docs
The response should mention what precipitated the bad request. You may try wireshark to capture the upload attempt and compare it with the curl examples here

Laravel test Passport::actingAs($user) use routes?

I have custom passport user login validation (i made it following this) so i make my custom /oauth/token with this route:
/routes/auth.php
Route::post('/oauth/token', [
'uses' => 'Auth\CustomAccessTokenController#issueUserToken'
]);
/app/controllers/auth/CustomAccessTokenController.php
namespace App\Http\Controllers\Auth;
use App\Models\User;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Psr\Http\Message\ServerRequestInterface;
class CustomAccessTokenController extends Controller
{
public function issueUserToken(ServerRequestInterface $request)
{
$httpRequest = request();
if ($httpRequest->grant_type == 'password') {
$user = User::where('email', $httpRequest->username)->first();
return $this->issueToken($request);
}
}
}
If i make a manual POST request to domain.com/oauth/token is correctly handled by the custom controller but when i use Passport::actingAs($user); in a phpunit test not. This Passport::actingAs(); use the routes or have other way to get the authentication token?
You should be able to get the authentication token using
$this->actingAs($user, 'api');

Laravel controller / store

I am new to laravel, i am trying to store a tweet to database and i need to insert user id, but this gives me an error
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Tweet;
class TweetController extends Controller
{
public function store(Request $request){
return Tweet::create([ 'tweet' => request('tweet'), 'user_id' => Auth::id()]);
}
}
error i recive:
App\Http\Controllers\Auth' not found in file
/Applications/AMPPS/www/Twitter/Twitter/app/Http/Controllers/TweetController.php
Any idea?
Yes, you are missing the import, that's why it tries to find it in the Controller location, so put
use Illuminate\Support\Facades\Auth;
// or
use Auth; // you must have the Auth alias in the config/app.php array
as an import, or use the helper function auth()->id() instead.
So instead of mass-assigning the user, you can do the following, in your User model add this:
public function tweets()
{
return $this->hasMany(Tweet::class);
}
Then in your controller just do this:
auth()->user()->tweets()->create([ 'tweet' => request('tweet') ]);
You can use auth() helper to get user id:
auth()->user()->id

How to call an Api Controller from API route in laravel?

I have installed jwt authentication & I have created a controller i.e., AuthController Inside Api Directory. I have defined the in routes/api.php as:
Route::group(['prefix'=>'v1', 'namespace' => 'Api'],function($app){
Route::get('/test', function(){
return "HEllo";
});
Route::get('test', 'AuthController#test');
});
When I hit the url as: http://localhost:8000/api/v1/test then I am getting error as Class Cotrollers\Api\AuthController does not exist.
AuthController
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
class AuthController extends Controller
{
public function test() {
return "Hello";
}
}
RouteServiceProvider.php:
Route::prefix('api')
// ->middleware('api')
// ->namespace($this->namespace) ->group(base_path('routes/api.php'));
Uncomment the ->namespace($this->namespace) line.
In your Route::group statement you have defined the namespace of the route group as 'Api'.
But the AuthController resides in the App\Http\Controllers namespace, and not the Api namespace.
To fix this add an Api namespace in your App\Http\Controllers and refer it there (best practice is creating a directory in the Controllers directory named Api so the directory structure follows the namespace):
AuthController.php
namespace App\Http\Controllers\Api;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
class AuthController extends Controller
{
public function test() {
return "Hello";
}
}
Here you need to make changes to,
App\Providers\RouteServiceProvider.php
In the RouteServiceProvider.php add
protected $namespace = 'Path\To\Controllers';
Like:
protected $namespace = 'App\Http\Controllers';
Thats it!
Please let me know if this solved your problem.
Change the Auth controller namespace definition to:
namespace App\Http\Controllers\Api;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\AuthController;
// you need to use your controller top of the api.php file
Route::group([
'namespace' => 'Customers', //namespace App\Http\Controllers\Customers;
'middleware' => 'auth:api', // this is for check user is logged in or authenticated user
'prefix' => 'customers' // you can use custom prefix for your rote {{host}}/api/customers/
], function ($router) {
// add and delete customer groups
Route::get('/', [CustomerController::class, 'index']); // {{host}}/api/customers/ this is called to index method in CustomerController.php
Route::post('/create', [CustomerController::class, 'create']); // {{host}}/api/customers/create this is called to create method in CustomerController.php
Route::post('/show/{id}', [CustomerController::class, 'show']); // {{host}}/api/customers/show/10 this is called to show method in CustomerController.php parsing id to get single data
Route::post('/delete/{id}', [CustomerController::class, 'delete']); // {{host}}/api/customers/delete/10 this is called to delete method in CustomerController.php for delete single data
});

Retrieve json data through route in Laravel 5.3

I am using Laravel 5.3 for my API and my frontend is not included in my view of Laravel. My frontend is on 80 port whereas my API is on 8080 port so whenever I want to make a communication in between I will call Laravel API.
I don't know how to retrive the requested JSON data in Laravel using post route and I want to return the same data in response just to check whether it is working fine or not.
so here is my route and controller(please guide me if i went wrong in my code):
Route::group(['middleware' => ['api','cors'],'prefix' => 'api'], function () {
Route::get('inquiry', 'inquiryController#store');
});
and controller is:
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
class inquiryController extends Controller
{
public function store(Request $request)
{
$data=$requst->json->all();
return response()->json([$data]);
}
}
But this code is not working properly. How can I solve this?
Try to do like this
public function store(Request $request)
{
$data = $request->all();
return response()->json($data);
}

Resources