I am just starting to look at backbone.js but am struggling with the server side of things.
I have seen documentation declaring the urlRoot as 'user/' after a bit of googling I have figured out that this is a reference to a RESTful API, however I have not been able to figure out how to implement such a structure with WAMP (will be moving to a hosted server once I have a working solution).
I had a play with Laravel but after 2 days I have not been able to set up a route to a dummy controller. This is my current attempt:
routes.php
Route::post('users', 'UsersController#create');
UsersController.php
<?php
class UsersController extends BaseController {
public function index() {
}
public function create() {
$input = Input::json();
return json_encode($input);
}
}
backbone.js
window.User = Backbone.Model.extend({
defaults: {
FirstName: "Test",
LastName: "User"
},
urlRoot: "user/"
})
However when I create a new user and attempt to call save, chromes network tools tell me that it sends a post request to users/ and then a get request to users
Is there an easier way to set my site up to talk with backbone or am I just doing something really wrong?
You should use :
Route::controller('users', 'UserController');
and
public function getCreate() {}
see this http://laravel.com/docs/controllers#restful-controllers
Related
Im new to Botman.
I try to implement a simple function to test how it works, but I keep getting empty response, it look like botman do not hears my message.
I installed botman without studio since, I'm trying to keep things simple. I also installed a webdriver as it says in documentation.
In my project I use JWT as an authentification, so i created a protected route like this:
Route::group(['middleware' => ['assign.guard:user', 'jwt.auth']], function () {
Route::post(
'/',
'UserBotManController#startConversation'
)->name('botman.user.start');
});
The controller looks like this:
<?php
namespace Project\UI\Api\Controllers\User\Botman;
use App\Http\Controllers\Controller;
use BotMan\BotMan\BotMan;
use BotMan\BotMan\BotManFactory;
use BotMan\BotMan\Drivers\DriverManager;
class UserBotManController extends Controller
{
public function startConversation()
{
$config = [];
DriverManager::loadDriver(\BotMan\Drivers\Web\WebDriver::class);
$botman = BotManFactory::create($config);
$botman->hears('hello', function (BotMan $bot) {
$bot->reply('Hello yourself.');
});
$botman->listen();
}
}
No when I send a request to this route a get empty response:
Looks like botman can't hear my message...
I try to looked inside with: dd($botman->getDriver());
And I see that the content has all the data:
Can any one help me to understand, how I can make it work?
Ok, so finally I found a solution. I have checked what request it sends from https://botman.io website and it is Form Data, not JSON.
diver field must be set to web!
Hope it will help someone.
Brief:
Actually, I'm little bit confused while using Laravel api route file.
Question:
If I need to access the data of my web site in other platform (like android app) that is made using laravel, then should I create a different route in api.php file?
If yes then I will be declaring two routes and controllers for each request, first in web.php and second in api.php. Is it correct?
Basically, I want to ask that how I can make an api, so that I can access the data in website as well as in other platforms?
I was searching for a good tutorial for this, but I didn't got a good one.
Ideally the API routes and Web routes should be completely different but if you want it to be same then instead of defining routes in different file you can add routes only in web.php and add a special parameter from your client and in controller if you are getting the parameter then return the JSON Object or else return the view.
Eg.
web.php
Route::get('getUsers','UserController#getUsers');
UserController.php
...
public function getUsers(Request $request)
{
...
if ($request->has('api')) {
return $users; //API Route (Laravel will by Default return the JSON Response no need to do json_encode)
}
return view('pages.user_list'); //Normal Routes hence returning View
}
...
Requests
Normal Request
<Yourdomain>/getUsers
API Request
<Yourdomain>/getUsers?api=true
I hope that helped...
Write your api routes in api.php and web routes in web.php.
The Api routes always have the name api in the routes thus you can differentiate the routes., I mentioned here because as #Akshay Khale mentioned an example with query parameter.
if you want to use the same controller for both API and Web, Api Requests always have the Header Content-Type : Json and "Accept":"application/json" so in your controller you can do it as below.
public function getUsers(Request $request)
{
...
if ($request->wantsJson()) {
return response()->json($users, 200); //here why we are extending response object because using json() method you can send the status code with the response.
}
return view('pages.user_list'); //Normal Routes hence returning View
}
for the laravel 5.6 and above the above answers won't work for me , so here is my 2 cents.
I have put the routes in web.php and api.php and normal no any magic tricks .
public function getUsers(Request $request)
{
....
if( $request->is('api/*')){
...
return response()->json($user_data, 200);
}
...
return view('users', ['users_data'=>$user_data]);
}
It will return json output for
127.0.0.1:8000/api/users
and normal view in html for
127.0.0.1:8000/users
I'm trying to accomplish API versioning of the APIs I've written using Slim framework.
All my versioned APIs look like this:
$app->get('/:version/book/search', function() {...});
I'm trying to create an application wide Route Condition for this version as follows:
\Slim\Route::setDefaultConditions(array(
'version' => 'v[3-6]'
));
So only the APIs with version number v3,v4,v5 and v6 should be allowed to get it.
My requirement is to store the exact version of the API call made in $app->version, and then do version specific code changes if needed for that. I have created a middleware which I added to the $app itself, so it gets executed for each API calls:
$app->add(new \GetVerMiddleware());
class GetVerMiddleware extends \Slim\Middleware
{
public function call()
{
// HOW TO GET THE version route parameter??
// ????
$app->version = $version;
$this->next->call();
}
}
So I want to know how to get the route parameter version inside the GetVerMiddleware. Is it even possible to get that? I know how to get the entire route printed (link), but I'm interested only in the version parameter.
OK, I've figured out the solution after some researching, the following link particularly helped:
Slim Framework forum
$app->add(new \GetVerMiddleware());
class GetVerMiddleware extends \Slim\Middleware
{
public function call()
{
$this->app->hook('slim.before.dispatch', array($this, 'onBeforeDispatch'));
$this->next->call();
}
public function onBeforeDispatch()
{
$route_params = $this->app->router()->getCurrentRoute()->getParam('version');
$this->app->version = $version;
}
}
I think the solution was pretty much there, apologies!
I have created a fully functional CakePHP web application. Now, i wanna get it to the next level and make my app more "opened". Thus i want to create an RESTful API. In the CakePHP docs,i found this link (http://book.cakephp.org/2.0/en/development/rest.html) which describes the way to make your app RESTful. I added in the routes.php the the two lines needed,as noted at the top of the link,and now i want to test it.
I have an UsersController.php controller,where there is a function add(),which adds new users to databases. But when i try to browse under mydomain.com/users.json (even with HTTP POST),this returns me the webpage,and not a json formatted page,as i was expecting .
Now i think that i have done something wrong or i have not understood something correctly. What's actually happening,can you help me a bit around here?
Thank you in advace!
You need to parse JSON extensions. So in your routes.php file add:
Router::parseExtensions('json');
So a URL like http://example.com/news/index you can now access like http://example.com/news/index.json.
To actually return JSON though, you need to amend your controller methods. You need to set a _serialize key in your action, so your news controller could look like this:
<?php
class NewsController extends AppController {
public function index() {
$news = $this->paginate('News');
$this->set('news', $news);
$this->set('_serialize', array('news'));
}
}
That’s the basics. For POST requests, you’ll want to use the RequestHandler component. Add it to your controller:
<?php
class NewsController extends AppController {
public $components = array(
'RequestHandler',
...
);
And then you can check if an incoming request used the .json file extension:
public function add() {
if ($this->RequestHandler->extension == 'json') {
// JSON request
} else {
// do things as normal
}
}
I am working with Laravel for a new project, and I am wanting to setup a new URL,
/project/create
I thought this would be as easy as doing the following,
<?php
class Project_Controller extends Base_Controller {
public function action_create()
{
return "Step 1";
}
}
However this returns a 404, can you not just setup an url base on /controller/action is this not the case, will I have to do this,
Route::get('/project/create', function()
{
return View::make('project.index');
});
or similar for every URL/request the site needs?
You can do controller routing.
Option 1:
// Register a specific controller
Route::controller('project');
Option 2 (not recommended in Laravel 3 as known to be buggy sometimes):
// Register all controllers and all routes
Route::controller(Controller::detect());
You can see more options about routing and controller routing here