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)
Related
My app was working fine until I wanted to replace my "get" routes with a single "resource" to be able to include a delete function. I remind you that I am a beginner in laravel so it is surely due to the fact that I can not be able to make a "resource" route.
This is my code :
Route::get('/', function(){
return view('front.pages.homepage');
})->name('homepage');
Route::get('/garages', [GarageController::class, 'index'])->name('garage.index');
Route::get('/garages/{garage}', [GarageController::class, 'show'])->name('garage.show');
Route::get('/garages_create', [GarageController::class, 'create'])->name('garage.create');
Route::post('/garages_create', [GarageController::class, 'garage_create'])->name('garage_create');
Route::resource('cars', [CarController::class]);
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Car;
use App\Models\Garage;
class CarController extends Controller
{
public function index()
{
$list = Car::paginate(10);
return view('cars', [
'list' => $list
]);
}
public function store()
{
$garages = Garage::orderBy('name')->get();
return view('carCreate/carCreate', [
'garages' => $garages,
]);
}
public function create(Request $request)
{
{
$request->validate([
'name' => 'required',
'release_year' => 'required',
'garage_id' => 'required', 'exists:garage_id'
]);
$car = new Car();
$car->name = $request->name;
$car->release_year = $request->release_year;
$car->garage_id = $request->garage_id;
$car->save();
return redirect('/cars');
}
}
public function show(Car $car)
{
return view('carShow/carShow', compact('car'));
}
public function edit($id)
{
//
}
public function update(Request $request, $id)
{
//
}
public function destroy($id)
{
//
}
}
And my error is : ErrorException
Array to string conversion
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
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!']);
}
}
}
It is OK in Get, Post, Delete in my laravel code.
But I can't update the field.
function update in BookController.php
$data = $this->request->all();
If show the dd($data), it is null.
What reason?
Help me please.
BookRequest.php Code:
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class BookRequest extends FormRequest
{
public function authorize()
{
return true;
}
public function rules()
{
return [
'name' => 'required|max:255',
'coment' => 'required'
];
}
}
BookController.php Code:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Book;
use Illuminate\Http\Response;
use App\Http\Requests\BookRequest;
class BookController extends Controller
{
protected $request;
protected $book;
public function __construct(Request $request, Book $book) {
$this->request = $request;
$this->book = $book;
}
public function update(BookRequest $request, $id) {
$data = $this->request->all();
$book = $this->book->find($id);
$book->name = $data['name'];
$book->coment = $data['coment'];
$book->save();
return response()->json(['status' => Response::HTTP_OK]);
}
}
If i were you i would replace the Controller like below:
<?php
namespace App\Http\Controllers;
use App\Book;
use Illuminate\Http\Response;
use App\Http\Requests\BookRequest;
class BookController extends Controller
{
public function update(BookRequest $request, $id) {
$book = Book::find($id);
$book->update($request->all());
return response()->json(['status' => Response::HTTP_OK]);
}
}
If you have set up Route:model binding then you can simplify Code more better. Below code only works if you have a Route::model setup in your route file web.php.
Check this docs for more details:
https://laravel.com/docs/5.6/routing#route-model-binding
public function update(BookRequest $request, Book $book) {
$book->update($request->all());
return response()->json(['status' => Response::HTTP_OK]);
}
Try this:-
$request->all();
instead of
$this->request->all()
I have solved.
My request: http://127.0.0.1:8000/api/book
POST , key: _method: PUT
Update Code
$data = $request->all();
$book = Boook::find($id);
$book->name = $data['name'];
$book->coment = $data['coment'];
$book->save();
Regards.
Undefined property: Illuminate\Validation\Validator::$errors in laravel
here is my controller file how to solve it i think here problem is any namespace where is it i do not know please guide me
namespace App\Http\Controllers;
use Illuminate\Support\Facades\Route;
use Input;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Http\Request;
use App\models\Designation;
use Validator;
use Illuminate\Support\Facades\Response;
class Cdesigination extends Controller
{
public $flight;
public function __construct(){
$this->flight = new Designation;
}
public function index()
{
return view('designation');
}
public function techer(Request $request) {
$Validator =Validator::make(array(
'name'=>Input::get('name'),
'detail'=>Input::get('detail')
),array(
'name' => 'required',
'detail' => 'required'
));
if ($Validator->fails()) {
return Response::json([
'success'=>false,
'error' =>$Validator->errors->toArray()
]);
}
else{
$this->flight->name = $request->name;
$this->flight->detail = $request->detail;
$this->flight->save();
return Response::json([
'success'=>true]);
}
}
$Validator->errors()->toArray()
Errors() is function, so the braces are important