consuming web service with laravel and guzzle - laravel

I'm trying to retrieve some information on my controller
using GuzzleHttp
use \GuzzleHttp\Client;
class ClientsController extends Controller
{
public function index()
{
$client = new Client(['base_uri' => 'http://localhost/systeml/public/ws/clients']);
$response = $client->request('GET', '');
$contents = $response->getBody()->getContents();
dd($contents);
}
when I run this command the following problem appears
(1/1) ServerException Server error: GET
http://localhost/systeml/public/ws/clients
resulted in a 500 Internal Server Error response:
the guzzle is running normal and having problems trying to access the other local server?

Make sure in the other project you run php artisan serve in the root directory of the project.
And use postman also.

Related

How can write test for laravel api route with auth.basic middleware

My laravel project has an API route by auth.basic middleware which is used id of the authenticated user in the controller. when I call it in postman it works well and I get 401 when the username or password is incorrect, but in laravel APITest which extends from DuskTestCase, authentication does not take place so I get 500 instead of 401 when the user's informations were incorrect. However, by correct information, I have the same error because auth() is null.
it is written like below, which is wrong?
api.php route:
Route::get('/xxxxxx/xxxxxx/xxxxxxx', 'xxxxx#xxxx')->middleware('auth.basic');
APITest:
$response = $this->withHeaders(['Authorization' => 'Basic '. base64_encode("{$username}:{$password}")])->get("/xxxxxx/xxxxxx/xxxxxxx");
You can use actingAs() method for authentication in tests.
An example from docs:
public function testApplication()
{
$user = factory(App\User::class)->create();
$this->actingAs($user)
->withSession(['foo' => 'bar'])
->visit('/')
->see('Hello, '.$user->name);
}
Another example that you can use for an API:
$user = User::factory()->create();
$response = $this->actingAs($user)->json('GET', $this->uri);
$response->assertOk();
For more information: https://laravel.com/docs/5.1/testing#sessions-and-authentication

PHPUnit - post to an existing controller does not return an error

I am new to PHPUnit and TDD. I just upgrade my project from Laravel 5.4 to 5.5 with phpunit 6.5.5 installed . In the learning process, I wrote this test:
/** #test */
public function it_assigns_an_employee_to_a_group() {
$group = factory(Group::class)->create();
$employee = factory(Employee::class)->create();
$this->post(route('employee.manage.group', $employee), [
'groups' => [$group->id]
]);
$this->assertEquals(1, $employee->groups);
}
And I have a defined route in the web.php file that look like this
Route::post('{employee}/manage/groups', 'ManageEmployeeController#group')
->name('employee.manage.group');
I have not yet created the ManageEmployeeController and when I run the test, instead of get an error telling me that the Controller does not exist, I get this error
Failed asserting that null matches expected 1.
How can I solve this issue please?
The exception was automatically handle by Laravel, so I disabled it using
$this->withoutExceptionHandling();
The test method now look like this:
/** #test */
public function it_assigns_an_employee_to_a_group() {
//Disable exception handling
$this->withoutExceptionHandling();
$group = factory(Group::class)->create();
$employee = factory(Employee::class)->create();
$this->post(route('employee.manage.group', $employee), [
'groups' => [$group->id]
]);
$this->assertEquals(1, $employee->groups);
}
You may not have create the method in the Controller but that doesn t mean your test will stop.
The test runs.It makes a call to your endpoint. It returns 404 status because no method in controller found.
And then you make an assertion which will fail since your post request
wasn't successful and no groups were created for your employee.
Just add a status assertion $response->assertStatus(code) or
$response->assetSuccessful()

Laravel Auth get disconnected when i try post file

Hello i'm using Laravel 5.5 and trying to upload a file with vuejs and axios post,
when i upload the file a function is fired but at the server the auth is disconnected don't know why
i've disabled the VerifyCsrfToken because break all my previous axios posts
that's my code at Vuejs :
// update profile picture
uploadProfilePicture(){
let file = event.target.files
let form = new FormData();
form.append('file',file[0]);
axios.post('update-picture',form)
.then((response)=>console.log(responsea.data))
.catch((error)=>console.log(error.response.data))
},
that's my code at server
// update photo profile
public function updatePicture(Request $request)
{
$file = $request->file;
$res = Storage::disk('localLinked')->put('default/user/profile',$file);
$picture = \App\Picture::create([
'link'=>$res
]);
Auth::user()->profilePicture()->delete();
Auth::user()->update([
'idProfilePicture'=>$picture->id
]);
dd('done');
}
the error is that Auth::user() always null
please help i'm stack here
Thanks

Dynamic social app credentials in socialite package in Laravel

I'm trying to build a multi tenant app, where I have configured the database, the views folder, I know there must be some way out to configure the credentials of social app login for socialite. Well I tried few things to set it dynamically.
STEP 1
I created a class with the name of socialite in a separate folder and when the social login is called I'm implementing the following in my controller:
public function redirectSocialLogin()
{
$social = new SocialiteProvider();
$fb = $social->makeFacebookDriver();
return $fb->redirect();
}
and while callback I used following:
public function callbackSocialLogin($media)
{
$user = Socialite::driver($media)->user();
$data['name'] = $user->getName();
$data['email'] = $user->getEmail();
dd($data);
}
In my class I've following codes:
public function makeFacebookDriver()
{
$config['client_id'] = 'XXXXXXXXXXXXXXX';
$config['client_secret'] = 'XXXXXXXXXXXXXXX';
$config['redirect'] = 'http://XXXXXXXXXXXX/auth/facebook/callback';
return Socialite::buildProvider('\Laravel\Socialite\Two\FacebookProvider', $config);
}
It redirects perfectly to the social page but while getting a callback I'm getting an error, It again fetches the services.php file for configuration and doesn't get any.
STEP 2
I made a ServiceProvider under the name of SocialiteServiceProvider and extended the core SocialiteServiceProvider and placed the following codes:
protected function createFacebookDriver()
{
$config['client_id'] = 'XXXXXXXXXXXXXXX';
$config['client_secret'] = 'XXXXXXXXXXXXXXXXXXXX';
$config['redirect'] = 'http://XXXXXXXXXXX/auth/facebook/callback';
return $this->buildProvider(
'Laravel\Socialite\Two\FacebookProvider', $config
);
}
But again it throws back error which says driver is not setup. Help me out in this.
Thanks.
In your STEP 1, update the callback as below mentioned & try. $media is actually Request. So when initialising Socialite::driver($media) you are actually passing Request where you have to pass Facebook.
public function callbackSocialLogin(Request $request) {
$fbDriver = (new SocialiteProvider())->makeFacebookDriver();
$user = $fbDriver->user();
$data['name'] = $user->getName();
$data['email'] = $user->getEmail();
...
}

RequestException while sending Plivo sms in latest laravel 5.1.26

I am doing project in laravel. I followed all the steps mentioned in
plivo.com .
As I had done same steps in my another old project and this worked perfectly, but after updating my composer its not working and throwing same error message as like my new laravel project. Error message is as follow,
Fatal error: Uncaught exception 'GuzzleHttp\Exception\RequestException' with message 'cURL error 60: SSL certificate problem: self signed certificate in certificate chain
My Plivo folder is inside the root folder. Guzzle installed is "guzzlehttp/guzzle": "v6.1.1".
composer.json is,
{
"require": {
"plivo/plivo-php": "~1.1.0"
}
}
Controller.php
<?php
namespace App\Http\Controllers;
use Plivo;
public function signup(Request $request){
$number = $request->input('owner_phone');
$output = $this->validatenumber($number);
}
public function validatenumber($number){
$auth_id = "MAZJFKNTU3OGQ5NMM5YJ";
$auth_token = "NDcyYjU5NmMxMmQzMzYzMjIzODExMTg3NzZmOWVj";
$p = new Plivo\RestAPI($auth_id, $auth_token);
$params = array(
'src' => '14154847489', // Sender's phone number with country code
'dst' => '91'.$number, // Receiver's phone number with country code
'text' => 'Your TaaraGo verification code is '.$otpnumber. '.', // Your SMS text message
'url' => 'http://localhost/untitled/sentsms.php', // The URL to which with the status of the message is sent
'method' => 'POST' // The method used to call the url
);
return $response = $p->send_message($params);
}
?>
and route.php is,
Route::post('auth/signup', 'AuthController#signup');
Is there any solution to this problem? any one having same problem with laravel version 5.1.26, give me solution.

Resources