How to receive JSON from POST? - laravel

I receive JSON from Vue.JS client via REST Api, and I'd like to get data using Eloquent, but it doesn't work. It's not blade and not standard form-submit data, I receive JSON Api from client, single-page application.
This is the JSON, addressed to route '/order' from client, method POST:
{
"name": "John",
"phone": "+7 794 910 5708",
"email": "example#gmail.com"
}
The route is:
Route::post('/order','OrderController#order');
In a Controller I try to do that:
<?php
namespace App\Http\Controllers;
use Request;
use App\Data;
class OrderController extends Controller
{
public function order()
{
$input = Request::all();
$data = new Data;
$data->name = $input['name'];
$data->phone = $input['phone'];
$data->save();
return response()->json(['result' => '200 OK'], 200);
}
}
But nothing happens. What is the right syntax to receive data from REST Api?

Make some changes as per below:
In controller:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Data;
class OrderController extends Controller
{
public function order(Request $request)
{
$post = $request->all();
$data = Data::create($post);
if($data){
return response()->json(['success' => true, 'message' => 'Data has been inserted!']);
} else {
return response()->json(['success' => false, 'message' => 'Data not inserted, Something went wrong!']);
}
}
}

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

use trait variable undefined

I am trying to use trait because I will put the code in several files as it is an api connection.
But when calling the variable that displays the values returned by the api, it is showing undefined in the controller.
App/Http/Traits/UserConnect.php
namespace App\Http\Traits;
use GuzzleHttp\Client;
use GuzzleHttp\RequestOptions;
trait UserConnect
{
public function connectInfo(Request $request)
{
try {
$client = new \GuzzleHttp\Client();
$url = "api_url";
$response = $client->request('GET', $url, [
'headers' => [
'Authorization' => 'Bearer '.$token,
],
]);
$result = json_decode($response->getBody());
return $result;
}catch (\Exception $e){
dd($e);
}
}
}
Controller
<?php
namespace App\Http\Controllers;
use App\Http\Traits\UserConnect;
class HomeController extends Controller
{
use UserConnect;
public function page(Request $request)
{
$api = $this->connectInfo($result);
dd($api);
}
$result is returning undefined but $ api is forcing 1 variable.
Your call should be $api = $this->connectInfo($result$request); because your function declaration accepts Request public function connectInfo(Request $request)

How to return custom response when validation has fails using laravel form requests

When we use Laravel Form Requests in our controllers and the validation fails then the Form Request will redirect back with the errors variable.
How can I disable the redirection and return a custom error response when the data is invalid?
I'll use form request to GET|POST|PUT requests type.
I tried the Validator class to fix my problem but I must use Form Requests.
$validator = \Validator::make($request->all(), [
'type' => "required|in:" . implode(',', $postTypes)
]);
if ($validator->fails()) {
return response()->json(['errors' => $validator->errors()]);
}
Creating custom FormRequest class is the way to go.
namespace App\Http\Requests;
use Illuminate\Contracts\Validation\Validator;
use Illuminate\Validation\ValidationException;
use Illuminate\Http\Exceptions\HttpResponseException;
class FormRequest extends \Illuminate\Foundation\Http\FormRequest
{
protected function failedValidation(Validator $validator)
{
if ($this->expectsJson()) {
$errors = (new ValidationException($validator))->errors();
throw new HttpResponseException(
response()->json(['data' => $errors], 422)
);
}
parent::failedValidation($validator);
}
}
Class is located in app/Http/Requests directory. Tested & works in Laravel 6.x.
This is the same but written differently:
protected function failedValidation(Validator $validator)
{
$errors = (new ValidationException($validator))->errors();
throw new HttpResponseException(
response()->json([
'message' => "",
'errors' => $errors
], JsonResponse::HTTP_UNPROCESSABLE_ENTITY)
);
}
Base class FormRequest has method failedValidation. Try to override it in your FormRequest descendant
use Illuminate\Contracts\Validation\Validator;
class SomeRequest extends FormRequest
{
...
public function failedValidation(Validator $validator)
{
// do your stuff
}
}
use this on function
dont forget to take on top // use App\Http\Requests\SomeRequest;
$validatedData = $request->validated();
\App\Validator::create($validatedData);
create request php artisan make:request SomeRequest
ex.
use Illuminate\Contracts\Validation\Validator;
class SomeRequest extends FormRequest
{
public function rules()
{
return [
'health_id' => 'required',
'health' => 'required',
];
}
}

Laravel: One to Many Poly relation not updating automatically

3 types of posts: Personal, Business & Nature.
Below is the Post Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\Relation;
Relation::morphMap([
'Personal' => 'App\Personal',
'Business' => 'App\Business',
'Nature' => 'App\Nature',
]);
class Post extends Model
{
public function postable()
{
return $this->morphTo();
}
}
Below is the Personal Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Personal extends Model
{
public function posts()
{
return $this->morphMany(Post::class,'postable');
}
}
Likewise Busines & Nature models.
When I manually enter the data in phpMyAdmin, the tinker shows the result as required, but when I create a post from front-end (via form), the posts table remains unchanged.
I tried googling, but nothing works! :(
Below is the PersonalController
public function create()
{
if(Auth::guest()){
return redirect()->route('login');
}
$sectors = Sector::all();
$cities = City::all();
$ranges = Range::all();
return view('front.personal-register',compact('sectors','cities','ranges'));
}
public function store(Request $request)
{
$this->validate($request,[
"sectors" => "required",
"cities" => "required",
"ranges" => "required",
"g-recaptcha-response" => "required|captcha"
]);
$franchisee = new Personal;
$franchisee->user_id = Auth::user()->id;
$franchisee->save();
$franchisee->sectors()->sync($request->sectors);
$franchisee->cities()->sync($request->cities);
$franchisee->ranges()->sync($request->ranges);
return redirect(route('personal.index'))->with('message','Thank You! Your post has been added');
}

Laravel 5.4: JWTAuth, ErrorException in EloquentUserProvider.php

I am a newbie of laravel, so it might be my mistake. Using laravel with tymondesigns/jwt-auth
to verify user. I am watching this tutorial Complete JWT-AUTH api with Laravel and followed every step, the tymon package installation and logging in user. But i am getting this error. I posted code below, tell me if you need more code from any other file.
ErrorException in EloquentUserProvider.php line 120: Argument 1 passed
to Illuminate\Auth\EloquentUserProvider::validateCredentials() must be
an instance of Illuminate\Contracts\Auth\Authenticatable, instance of
App\User given
This is my user model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
protected $hidden = ["password"];
protected $fillable = [
"id",
"name",
"password",
"mobile_number",
"gender",
"age",
"company_name",
"profile_image",
"email"
];
}
?>
This is my ApiAuthController.php
use JWTAuth;
use Illuminate\Http\Request;
use Tymon\JWTAuth\Exceptions\JWTException;
class ApiAuthController extends Controller
{
public function authenticate(){
$credentaials = request()->only('email', 'password');
print_r($credentaials);
try {
$token = JWTAuth::attempt($credentaials);
if(!$token){
return response()->json(['error'=>'invalid credentaials'], 401);
}
} catch (JWTException $e) {
return response()->json(['error'=>'something went wrong'], 500);
}
return response()->json(['token'=>$token], 200);
}
}
User store function in my UsersController:
public function store(Request $request)
{
$payload = json_decode($request->payload, true);
$validator = Validator::make($payload, $this->rules);
if ($validator->passes()) {
$user = (new User())->fill($payload);
if($user->save()){
$response = [
"msg" => "User created",
"link" => "/api/users/" . $user->id
];
return response()->json($response, 200);
}
$response = [
"msg" => "An error occured"
];
return response()->json($response, 404);
}
else {
return response()->json($validator->messages(), 404);
}
}
In storing user request, payload is key and value is json object, the small sample object is given below:
payload={
"name": "Alexa",
"email": "alexa#gmail.com",
"password":"12345",
"gender": "Male",
"age": 24
}
Add this to your model
use Illuminate\Foundation\Auth\User as Authenticatable;
and change this line
class User extends Authenticatable
Edit :
Looks like you're storing passwords in plaintext. Add this to your user model.
public function setPasswordAttribute($value)
{
$this->attributes['password'] = bcrypt($value);
}

Resources