Laravel Route not working properly - php

I have this function in the laravel controller
public function rawquery()
{
$resultado = DB::statement('SELECT * FROM "w8_w8shipment"');
dd($resultado);
return response()->json($resultado);
}
And this is the route to get access to it
Route::get('shipment/rawquery', 'ShipmentController#rawquery');
In the browser and postman, it shows an empty object
{}
And a 200 OK code
I don't know what's wrong. i've already read the docs.

Try using this function
public function rawQuery()
{
$data = 'SELECT * FROM "w8_w8shipment"';
$resultado = DB::select(DB::raw($data));
return response()->json(['status' => 'success', 'data' => $resultado], '200');
}

Related

Route with $id or all data in Codeigniter

I want to get all my data or select with by id, but something is wrong. When I try with route, not work. If i try without route, the select by ID work, and without id have "Missing argument..."
mysite.com/ws/v1/article - Return all my data (ok) but also a "Missing argument for Articles".
mysite.com/ws/v1/article/6 (6 = id example) Return "The page is not found".
Routes
$route['ws/v1/article'] = "api/articles/getArticle";
Controller
public function getArticle_get($id)
{
header("Access-Control-Allow-Origin: *");
// Load Authorization Token Library
$this->load->library('Authorization_Token');
/**
* User Token Validation
*/
$is_valid_token = $this->authorization_token->validateToken();
if (!empty($is_valid_token) AND $is_valid_token['status'] === TRUE)
{
if (empty($id)){
$data = $this->db->get("ga845_clientes")->result();
}else{
$data = $this->db->get_where("ga845_clientes", ['id' => $id])->row_array();
}
$this->response($data, REST_Controller::HTTP_OK);
} else {
$this->response(['status' => FALSE, 'message' => $is_valid_token['message'] ], REST_Controller::HTTP_NOT_FOUND);
}
}
This is how you pass the parameters in your api.
mysite.com/ws/v1/article/$6
To make your parameter optional,
$route['ws/v1/article/?(:id)?'] = "api/articles/getArticle/$1";

Laravel restore back deleted record

I'm trying to implement the queue that system will be restored back a deleted record. Now my code is working without error but the record will not restore back after deleted.
public function delete_invoice($job, $data)
{
Debugbar::info("invoiceSale");
try {
return DB::transaction(function ()use ($job,$data) {
});
} catch (TransactionException $e) {
# reestore function
extract($data);
$data = $Class::withTrashed()->find($id);
$data->restore();
Debugbar::info($data->toArray());
return Response::json(['errors' => array_flatten($e->getErrors())], 400);
}
}
This is the function from controller
public function destroy($id, $message = '')
{
Debugbar::info("ok");
Queue::push('IQueue#delete_invoice', [
'id' => $id,
'Class' => $this->Class,
]);
return parent::destroy($id, trans("$this->class.invoice")); <--delete invoice
}
you can use the following code hope it will help you.
public function destroy(Trip $trip)
{
$trip->delete();
flash()->warning('Trip '.$trip->id.' successfully deleted! <a href=trips/'.$trip->id.'/restore>UNDO</a>');
return redirect('trips');
}
public function restore(Request $request)
{
$trip = Trip::withTrashed()->where('id', $request['id'])->restore();
return redirect ('trips');
}
I'm assuming your code deletes the record somewhere else and the code you presented here is supposed to restore that record, based on the model class and record id passed via the $data array as ['Class' => ..., 'id' => ...].
Then what is your transaction meant to do? Is there any code you did not paste in? Otherwise catch is never called as there is no exception thrown and hence you code is not executed.
So just remove the try and catch.

error: Showing undefined variable .in laravel 5.2 while passing two array to View

GetEstimateController.php
public function fill_dropbox(){
$data = ProcedureTreat::get(['pro_name']);
$data1 = HospitalPackage::get(['address']);
// return $this->get_estimate();
// dd($data);
return View::make('get_quote')->with('address',$data1)->with('procedureName',$data);
}
public function get_estimate($name,$addr){
// dd($name);
$HospitalPack = HospitalPackage::where(['pro' => $name, 'address' => $addr])->orderBy('treat_price', 'desc')->get()->first();
$Dropbox_fill = $this->fill_dropbox();
// dd($HospitalPack);
return View::make('get_quote')->with(compact('Dropbox_fill','HospitalPack'));
}
if I'm using
return View::make('get_quote')->with(compact('Dropbox_fill','HospitalPack'));
this line it is showing error while using
return View::make('get_quote')->with(compact('HospitalPack'));
this code it is not showing error.
Turns out the problem was indeed in the return statement inside the fill_dropbox() method, so if you did it like this:
public function get_estimate($name,$addr){
$HospitalPack = HospitalPackage::where(['pro' => $name, 'address' => $addr])->orderBy('treat_price', 'desc')->get()->first();
$data = ProcedureTreat::get(['pro_name']);
$data1 = HospitalPackage::get(['address']);
return View::make('get_quote')->with(compact('data', 'HospitalPack', 'data1'));
}
Everything should be working now :)

Unable to authenticate with invalid token error in dingo/api with jwt-auth

I'm using dingo/api (that has built-in support for jwt-auth) to make an API.
Suppose this is my routes :
$api->group(['prefix' => 'auth', 'namespace' => 'Auth'], function ($api) {
$api->post('checkPhone', 'LoginController#checkPhone');
//Protected Endpoints
$api->group(['middleware' => 'api.auth'], function ($api) {
$api->post('sendCode', 'LoginController#sendCode');
$api->post('verifyCode', 'LoginController#verifyCode');
});
});
checkPhone method that has task of authorize and creating token is like :
public function checkPhone (Request $request)
{
$phone_number = $request->get('phone_number');
if (User::where('phone_number', $phone_number)->exists()) {
$user = User::where('phone_number', $phone_number)->first();
$user->injectToken();
return $this->response->item($user, new UserTransformer);
} else {
return $this->response->error('Not Found Phone Number', 404);
}
}
And injectToken() method on User Model is :
public function injectToken ()
{
$this->token = JWTAuth::fromUser($this);
return $this;
}
Token creation works fine.
But When I send it to a protected Endpoint, always Unable to authenticate with invalid token occures.
The protected Endpoint action method is :
public function verifyCode (Request $request)
{
$phone_number = $request->get('phone_number');
$user_code = $request->get('user_code');
$user = User::wherePhoneNumber($phone_number)->first();
if ($user) {
$lastCode = $user->codes()->latest()->first();
if (Carbon::now() > $lastCode->expire_time) {
return $this->response->error('Code Is Expired', 500);
} else {
$code = $lastCode->code;
if ($user_code == $code) {
$user->update(['status' => true]);
return ['success' => true];
} else {
return $this->response->error('Wrong Code', 500);
}
}
} else {
return $this->response->error('User Not Found', 404);
}
}
I used PostMan as API client and send generated tokens as a header like this :
Authorization:Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiI5ODkxMzk2MTYyNDYiLCJpc3MiOiJodHRwOlwvXC9hcGkucGFycy1hcHAuZGV2XC92MVwvYXV0aFwvY2hlY2tQaG9uZSIsImlhdCI6MTQ3NzEyMTI0MCwiZXhwIjoxNDc3MTI0ODQwLCJuYmYiOjE0NzcxMjEyNDAsImp0aSI6IjNiMjJlMjUxMTk4NzZmMzdjYWE5OThhM2JiZWI2YWM2In0.EEj32BoH0URg2Drwc22_CU8ll--puQT3Q1NNHC0LWW4
I Can not find solution after many search on the web and related repositories.
What is Problem in your opinion?
Update :
I found that not found error is for constructor of loginController that laravel offers :
public function __construct ()
{
$this->middleware('guest', ['except' => 'logout']);
}
because when I commented $this->middleware('guest', ['except' => 'logout']); all things worked.
But if I remove this line is correct?
How should be this line for APIs?
updating my config/api.php to this did the trick
// config/api.php
...
'auth' => [
'jwt' => 'Dingo\Api\Auth\Provider\JWT'
],
...
As I mentioned earlier as an Update note problem was that I used checkPhone and verifyCode in LoginController that has a check for guest in it's constructor.
And because guest middleware refers to \App\Http\Middleware\RedirectIfAuthenticated::class and that redirects logged in user to a /home directory and I did not created that, so 404 error occured.
Now just I moved those methods to a UserController without any middleware in it's constructor.
Always worth reading through the source to see whats happening. Answer: The is expecting the identifier of the auth provider in order to retrieve the user.
/**
* Authenticate request with a JWT.
*
* #param \Illuminate\Http\Request $request
* #param \Dingo\Api\Routing\Route $route
*
* #return mixed
*/
public function authenticate(Request $request, Route $route)
{
$token = $this->getToken($request);
try {
if (! $user = $this->auth->setToken($token)->authenticate()) {
throw new UnauthorizedHttpException('JWTAuth', 'Unable to authenticate with invalid token.');
}
} catch (JWTException $exception) {
throw new UnauthorizedHttpException('JWTAuth', $exception->getMessage(), $exception);
}
return $user;
}

Testing methods and controllers with Laravel 5 [phpunit]

I am tring to make test for my project, could someone show me example how to write tests or give me some good video course to learn testing.
In my example I am tring to test this part:
public function getProjectsForUser(){
if(Auth::user() -> admin_id == NULL){
$this->id = Auth::user() -> id;
}else{
$this->id = Auth::user() -> admin_id;
}
$projects = User::findOrFail(Auth::user() -> id)->projects()->where('admin_id', '=', $this->id)->get();
$role = User::findOrFail(Auth::user() -> id)->roles;
$users = User::where('admin_id', '=', $this->id)->lists('name','id');
return array('projects' => $projects,'users' => $users,'roles' => $role );
}
It was my model Project.php
Here is my PorojectController:
public function project(Project $projects){
$this -> projects = $projects ->getProjectsForUser();
return view('projects',$this -> projects);
}
Here is my test to check if user logged...
public function testHome()
{
$this->be(User::find(1));
$response = $this->call('GET', '/projects');
//CHECK IF AUTH USER
$this->assertTrue($response->isOk());
}
Now I need to check if I get right values inside array, for $project, $role, $users.
You can use assertViewHas() to assert values that should have been passed to the view. For example:
public function testHome(){
$this->be(User::find(1));
$response = $this->call('GET', '/projects');
//CHECK IF AUTH USER
$this->assertTrue($response->isOk());
$this->assertViewHas('projects', 'expected value for projects');
$this->assertViewHas('users', 'expected value for users');
$this->assertViewHas('roles', 'expected value for roles');
}
By the way: If you pass no second argument the method will just assert that the variable exists but won't compare the value.
To accomplish the same with a bit a different syntax you can use assertViewHasAll() and pass everything as array:
$this->assertViewHasAll([
'projects' => 'expected value for projects',
'users' => 'expected value for users',
'roles' => 'expected value for roles'
]);

Categories