Reputation:
I got stuck while trying to use cURL to retrieve data from my other site
When I go to http://localhost/api/distributors
BUT When I use the CLI and run this command curl -i --user test:1234 http://localhost/api/distributors
I couldn't connect to it, or see any json at all.
I am not sure what went wrong. I am positive that I type the right username and password.
Here is my route.
Route::get('/api/distributors', array('before' => 'auth.basic', 'uses'=>'DistributorController@api_index'));
It called DistributorController
> api_index
and here is my api_index
function
public function api_index()
{
$distributors = [];
foreach(Distributor::all() as $distributor)
{
$user = $distributor->user()->first();
$distributors[$distributor->id] = [
'user' => $user->toArray(),
'distributor' => $distributor->toArray(),
'contacts' => $distributor->contacts()->get()->toArray(),
'addresses' => $distributor->addresses()->get()->toArray()
];
}
$json_string = json_encode($distributors, JSON_PRETTY_PRINT);
return $json_string;
}
encoding
?It look like this :
<h1>Decode</h1>
<?php
$ch = curl_init("http://localhost/api/distributors");
curl_setopt($ch, CURLOPT_USERPWD, "test:1234");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$body = curl_exec($ch);
curl_close($ch);
?>
<?php $distributor = json_decode($body, TRUE); ?>
<!-- Test -->
<li><?php echo $distributor['distributor']['company_name']; ?></li>
I only have a problem when trying to connect using cURL.
Upvotes: 2
Views: 127
Reputation:
routes.php
Route::group(array('prefix' => 'api', 'before' => 'auth.basic|api'), function(){
Route::resource('url', 'UrlController');
});
filters.php
Add auth.basic
// Auth Basic
Route::filter('auth.basic', function()
{
return Auth::basic("username");
});
Add api
Filter
// API Route::filter('api', function() {
$user = Auth::user();
if ($user){
// Let them in
}
else{
return Response::view('errors.404', array(), 404);
}
});
controller
function and throw this in there ..<?php
class UrlController extends \BaseController {
// public function index(){
// return Response::json(User::all());
// }
public function index()
{
$distributors = [];
foreach(Distributor::all() as $distributor)
{
$user = $distributor->user()->first();
$distributors[$distributor->id] = [
'user' => $user->toArray(),
'distributor' => $distributor->toArray(),
'contacts' => $distributor->contacts()->get()->toArray(),
'addresses' => $distributor->addresses()->get()->toArray()
];
}
return Response::json($distributors);
}
}
Upvotes: 1