Handling laravel api resource store and create endpoints - vue.js

I have the following in my controller
class WrittersController extends Controller
{
public function index()
{
return view('backend.writters.dashboard');
}
public function store(Request $request){
//confused on when to use this
}
public function create(Request $request){
//add new user functionality
}
Now in my routes i would like to use the resource routes
Route::resource('writters','WrittersController');
Now the confusion comes in my vue axios http endpoints. I uderstand that i index is a get request but axios doesnt have a store or create point.
When should i use the store and create endpoints in the vuejs
UPDATE ON MY AXIOS. Am using axios via
axios.post("url") //how do i go about create and store here

The store function is called when you want to create i.e you will create and then store. So I usually call the create method from inside the store. I do this just to seperate the code and make it more readable. There is no store or create http requests. The store uses post request. So you will need to use post request with axios. Just use Route::resource in your web.php and then go to the terminal and check your routes with
php artisan routes (laravel 4)
php artisan route:list (laravel 5)
This will list all your registered routes and tell you which functions they use.

You use the other resources in the same way you used it for the get request.
Assuming your resource route looks like the following.
Route::resource('/mydata', 'MyDataController');
You would construct your requests in the following manner.
As you observed already, if you use axios.get('/mydata') you are routed to the index method. However if you use axios.post('/mydata'), Laravel will automatically route you to the store method.
If you want to use the create action you change the url to use axios.get('/mydata/create') and you are routed to the create method. Please note that the create action is not used for creating the record but rather for fetching the view where the user will create the record, e.g. a form. Then you will store the data entered in that form with a POST request.
If you want to use PUT (or PATCH) you use axios.put(/mydata/{some_id}) and you are routed to the update method.
So Laravel handles all the routing automatically for you depending on the type of request that is made (GET, POST, PUT/PATCH, DELETE). You only need to supply a parameter in the URL for those "Verbs" that require it.
Look at the documentation here link Look for the chart or table labeled "Actions Handled By Resource Controller" and you will see the various actions what verbs to access them with, and their respective URLs and Routes.
Also note that you can add custom methods to the resource controller if needed, but you will have to define the route. You do this by declaring the route in your routes file e.g. web.php before you declare the actual resource.
Say you want to add an new post method 'archived' to mark some record as being no longer active. You would do something like the following in your routes.
Route::post('/mydata/archived/{some_id}', 'MyDataController#archive');
Route::resource('/mydata', 'MyDataController');
As demonstrated above you can use axios.put() or axios.patch() and they will both be routed to the update method. There are times when you need to handle those requests differently. For example when using a autosave feature and I want to validate some form data when only one field has changed, I would use patch to validate just that single field as follows.
public function update(Request $request, $id)
{
if($request->isMethod('patch')){
$this->validateSingle($request);
}else{
$this->validateAll($request);
}
//....
}

Related

Adding property to the request using Node and Express

I have a MEAN application, and I'm handling authentication using passport. What I want to do is exactly what happens to the user on the passport, which can be accessed from the request like req.user. I have not found any solutions to reach that result. Can you give me any advice?
You can add properties to the request or response objects by creating a middleware and using it in your app. E.g.
// Defining middleware
function myMiddleware(req, res, next) {
req.myField = 12;
next();
}
// Using it in an app for all routes (you can replace * with any route you want)
app.use('*', myMiddleware)
Now all your request objects in your handlers will have myField property.
To add extra properties to the request and response object you need to extend the response and request interface.
index.d.ts files are used to provide typescript type information about a module that’s written in JavaScript.For express, the index.d.ts is present inside the #types/express folder inside the node_modules folder.
Use this link-
https://dev.to/kwabenberko/extend-express-s-request-object-with-typescript-declaration-merging-1nn5

Pass data across Hapi JS application

I want to detect current selected language from a domain (like es.domain.com, de.domain.com) so I need to pass it to all non static route handlers and to all views.
To detect a language I need a request object. But global view context it is possible to update where request object is not accessible (in server.views({})). Also server.bind (to pass data to route handler) works only where request object is not accessible.
Hapi version: 11.1.2
You could try something like this:
server.ext('onPreResponse', function (request, reply) {
if (request.response.variety === 'view') {
request.response.source.context.lang = request.path;
}
reply.continue();
});
This will attach a lang data point to the context that is being sent into the view. You'll have to extract the lang from the url as request.path is probably not what you actually want.
Also, if you look here you'll see a few pieces of request data is made available to every view via reply.view() If the locale/language is available directly in one of those data points, or can be derived from them, you can skip the extension point approach entirely.
Again, this is assuming version 10+ of hapi. If you're using an older version, the extension point method is your best bet.

Provide / Find all remote routes

We have a number of separate laravel projects using routes to implement online api's. I am creating a separate laravel 5 project to 'collect' these routes.
As theses routes can change over time, I thought it would be a sensible option to create a route in each separate laravel project which returned a json of available routes in that project. Something like;
App\Http\Controllers\RoutesController#routes
with method
public function routes(Request $request)
{
$routeCollection = Route::getRoutes();
$routePaths = [];
foreach ($routeCollection as $route) {
$routePaths[] = $route->getPath();
}
return response()->json(['routes'=> $routePaths], 200);
}
Then the collecting app can simply query this same route for each individual project url. I think this feels like a fairly good solution. However I want to check before I implement this that I am not reinventing the wheel.
Does laravel have a way to 'broadcast' all publicly available routes? - or some way to scan for all available routes from a given url? Or are there better ways of doing this?
You can get a list of all routes in the same way that the artisan route:list does, you can see the function you can call here:
https://github.com/laravel/framework/blob/6e31296d6531d0148aadf09c5536b89dda49dc27/src/Illuminate/Routing/RouteCollection.php#L243

How to setup REST API routes for CREATE, UPDATE, GET AND DELETE in Express.js?

I am building my first "real" MEAN application, and I am playing around with how to structure my REST api, which I would like to use as my backend.
I would like to know how to design the typical API methods in Express:
GET
POST
CREATE
UPDATE
I have made the following code, which solves the GET, UPDATE and DELETE. But how to implement POST? And is this decent practice?
Code:
app.get('/api/serials',function(req,res){
// get all serials code
});
app.get('/api/serials/:id',function(req,res){
// get by id code
});
app.get('/api/serials/:id/update',function(req,res){
// update code
});
app.get('/api/serials/:id/delete',function(req,res){
// delete code
});
You might be missing a fundamental concept here. A RESTful API responds to requests to the same URI differently, depending on the HTTP method.
// So it's NOT this:
app.get('/api/serials/:id/update', updateHandler);
app.get('/api/serials/:id/delete', deleteHandler);
// but rather `PUT` requests for updates
app.put('/api/serials/:id', updateHandler);
// and a `DELETE` requests for deletes
app.delete('/api/serials/:id', deleteHandler);
... where all requests that operate on an individual member of a resource collection are sent to the same URI.
Requests that operate on the resource collection are sent to the collection or base URI for the resource:
// the READ you already have right
app.get('/api/serials', indexHandler);
// but new resources should be created by POSTing to the collection URI
app.post('/api/serials', createHandler);

Sails.js - Change routing order (custom routes after blueprints)

I am having a very similar issue to this post here: How to use custom route middleware with Sails.js? (ExpressJS)
in that I want all non ajax requests (or all routes with the prefix /api) to load the same view, regardless of route. I have implemented the given answer in that question, but came across the issue that the policy is not called for any unspecified routes.
If I was to catch all routes so that the policy was called, all my blueprints would be overwritten.
Ideally, I would catch all routes last, after the blueprints, since every non API route should be sent to the front end.
I am using angularjs for the front end and want angular to deal with all non API routing.
I would rather not use a .htaccess file as I need to put session information into the page on it's initial load.
Thanks
It seems like your use case is very similar to a HTTP 404 Error situation - you want all requests which don't satisfy blueprint (and possibly route.js) routes to be handled in the same manner.
From api/responses/notFound.js:
* NOTE:
* If a request doesn't match any explicit routes (i.e. `config/routes.js`)
* or route blueprints (i.e. "shadow routes", Sails will call `res.notFound()`
* automatically.
*/
You can have special handling code here which calls the appropriate view if the request path contains /api:
if (req.path.match('^/api')) {
return res.view('your-view-here');
}