Laravel, Controllers, APIs, Transformation to fit response into a Select Input - laravel

I have a Model called : Federation.
In my View, I load a Select Combo via AJAX from a API Call.
I share the same controller for the API and for the view dispatcher --> FederationController, I don't have a separed architecture between Front end and Back end ( like Full Angular or Full VueJS architecture), it's mixed.
So, basically, my Controller says:
if (Request::ajax()){ // This is an API call from JS
return json;
else
return view;
And it works well ( I may have a problem when I will include an Android app...)
Thing is in some case, I don't want the full json model, but just the info tu fill the Select input, in general, I do
federations->lists('name','id'), or with pluck, as lists has been deprecated.
Thing is I don't really know how to organize it, because my API is based on returning Full Models, this is OK, but this kind of transformation is quite frequent.
So, I should create a kind of transformToSelect($model) Method or use great lib like Fractal to transform it, but I don't really know how to invoke without losing my endpoint.
In my routes.php, I have a group of routes like:
Route::group(['prefix' => 'api/v1'], function () {
Route::get("federations", 'FederationController#index');
// All my APIs
});
And I'm glad with it, because it sticks with REST.
I could get a solution having my route like:
Route::get("federations", 'FederationController#getForCombo');
But soon, I will have a mess, so, I wish there were a simple an elegant solution to my problem...
Any idea how to solve it?

Related

Laravel: form method != save method?

I am new to Laravel coming from CakePHP where the form and save method for a form is one and the same function name. I saw in many Laravel tutorials that the from method (that displays the form) is different than the method to save form (that actually saves data). Why using 2 different method names?
For example what's wrong with:
pub function xyz(Request $request)
{
if($results->isMethod('post')){
... then save and return redirect
}
... the code for showing the form in case there is no POST.
then having 2 routes one for GET and one for POST on the same url?
It is because people like to filter out things at route level not in controller, Also it helps developer to apply middleware grouping for each route separately. so that they can apply roles and permission etc. easily at route level.
It will looks horrible if mix all things in controller.
Think about middleware and groups in your code.
It is because you don't wanna mix a lot of logic in the same method . The case you have simple is the simple scenario . But there will be case where you wanna pass initial data in the create form . You have to write logic for that also in the same method and while you store the data you need to do the validation and calculate other business logic . If you combine all those things in one method it will mix all the things in one method and code difficult to read

Convention for a controller that generates a view from several models

In Sails.js, a route is set up against a controller method which can render a view. For the most part, this is straightforward, i.e. you could set up a GET /users route that points to UserController.find (which is usually set up automatically anyway).
However, say the home page of a blog renders the 10 most recent posts in the main section and a column with a list of authors and categories. The controller method has to fetch posts, authors, and categories before rendering the view and sending it back to the client. Clearly, a method like this doesn't really belong in PostController, AuthorController, or CategoryController.
What's the best thing to do in this situation? Create a controller for rendering views that rely on data from multiple models? Is there a good name for such a controller?
Thanks!
What I would do (this is purely opinion-based) is creating a PageController and create an action for each page you'd want.
For your home page example you can create a home action, get whatever you need and then render it with res.ok() (if everything is fine).
Another option would be to use Sails as a pure API and use HTTP requests (Ajax) or sockets to get your data in JSON. If you want to do so, I'd advise you to use a front end framework such as Angular, Ember, React...
By the way you could also create actions rendering HTML in your existing controllers and create a route to hit them through Ajax requests and just print them in your page. I'd prefer the 2nd solution because it takes full advantage of the Blueprint API (you don't need new controller or action whatsoever).
As Yann pointed out, this answer has to be a little opinionated. It seems that you are using the views system and not building a single page application. For the home page, I would go for an IndexController.js file with a home(req, res) action.
// api/controllers/IndexController.js
module.exports = {
home: function (req, res) {
// Retrieve all the information you need
// Take care about managing the asynchronous calls before rendering the view
return res.view('homepage');
}
};
Declare the route
// config/routes.js
module.exports.routes = {
'get /': 'IndexController.home'
}
Create the view in views/homepage.ejs.

Top js library to work with data model and ajax?

we are working on new project using Reactjs. We drop all oldschool libs like jquery and keep just simple React with some polyfills and small 3rd party libs. It works like a charm, it is small and fast.
But now we want to integrate some logic around backend models. I am not sure how to handle that.
First question:
What is currently "best" or most using ajax library? I check some like fetch, superagent and I am not sure if they are verified and production ready.
Send one:
For example model represent User entity. I want to cover basic REST ajax calls and custom ones find, findAll, create, update, destroy, or custom toggleFollow. And it should know about model logic like fullName = function() {return firstName + " " + lastName}. It is not hard to write by myself, but there is so many catches to handle. And it should be flux or flux-like compatible :)
Any suggestions, what is today popular and "in"?
Thanks

How to pass route values to controllers in Laravel 4?

I am struggling to understand something that I am sure one of you will be able to easily explain. I am somewhat new to MVC so please bear with me.
I have created a controller that handles all of the work involved with connecting to the Twitter API and processing the returned JSON into HTML.
Route::get('/about', 'TwitterController#getTweets');
I then use:
return View::make('templates.about', array('twitter_html' => $twitter_html ))
Within my controller to pass the generated HTML to my view and everything works well.
My issue is that I have multiple pages that I use to display a different Twitter user's tweets on each page. What I would like to do is pass my controller an array of values (twitter handles) which it would then use in the API call. What I do not want to have to do is have a different Controller for each user group. If I set $twitter_user_ids within my Controller I can use that array to pull the tweets, but I want to set the array and pass it into the Controller somehow. I would think there would be something like
Route::get('/about', 'TwitterController#getTweets('twitter_id')');
But that last doesn't work.
I believe that my issue is related to variable scope somehow, but I could be way off.
Am I going down the wrong track here? How do I pass my Controllers different sets of data to produce different results?
EDIT - More Info
Markus suggested using Route Parameters, but I'm not sure that will work with what I am going for. Here is my specific use case.
I have an about page that will pull my tweets from Twitters API and display them on the page.
I also have a "Tweets" page that will pull the most recent tweets from several developers accounts and display them.
In both cases I have $twitter_user_ids = array() with different values in the array.
The controller that I have built takes that array of usernames and accesses the API and generates HTML which is passed to my view.
Because I am working with an array (the second of which is a large array), I don't think that Route Parameters will work.
Thanks again for the help. I couldn't do it without you all!
First of all, here's a quick tip:
Instead of
return View::make('templates.about', array('twitter_html' => $twitter_html ))
...use
return View::make('templates.about', compact('twitter_html'))
This creates the $twitter_html automatically for you. Check it out in the PHP Manual.
 
Now to your problem:
You did the route part wrong. Try:
Route::get('/about/{twitter_id}', 'TwitterController#getTweets');
This passes the twitter_id param to your getTweets function.
Check out the Laravel Docs: http://laravel.com/docs/routing#route-parameters

Loading external data into Ember template using ember-data/DataStore

Here is what I'm tyrnig to do:
Make ajax request to retrieve JSON data from a PHP script
Insert that information into DataStore Models
Store those models within a controller
Display the information using {{#each}} with a handlebars template
Does ember-data have a built in way of retrieving data? If not, where
should the AJAX request be implemented?
What is the best way to insert the JSON data into the DS model?
What is the best way to then sync the models up with a Controller?
Any examples that implement all of the 4 steps would also be very helpful, since I can't seem to find any.
<edit>
Like I said in the comments, this questions asks a lot at once, so to follow up, here's a work in progress fiddle: http://jsfiddle.net/schawaska/dWcUp/
This is not 100%, but covers some of your questions. It uses the FixtureAdapter.
I'll be updating it as I find time.
</edit>
1 Make ajax request to retrieve JSON data from a PHP script
Ember-Data will take care of that for you. Consider the following:
window.App = Em.Application.create();
App.Store = DS.Store.extend({
revision: 12,
adapter: 'DS.RESTAdapter'
});
App.Product = DS.Model.extend({
name: DS.attr('string'),
imageUrl: DS.attr('string')
})
The code above defines a data store (almost like an ORM) within your client app. Ember uses convention over configuration (heavily), so as per configuration this code expects your backend to have a resource in the same domain as /products which talks to GET, POST, PUT and DELETE.
2 Insert that information into DataStore Models
Considering what I said above, by calling one of the following:
App.store.find(App.Product) or App.Product.find()
EmberData will fire a GET request through AJAX targeting your resource /products, and if you say App.Product.find(1), it will target /products/1.
Your app store will use its adapter and the adapter's serializer to translate the JSON result and materialize its data into your App.Product model.
3 Store those models within a controller
This is done when defining your application router. Regardless of what you do, Ember will run its own workflow, but it provides you several hooks, giving you the control of that specific action. Consider the following:
App.Router.map(function() {
this.resource('products');
});
App.ProductsRoute = Ember.Route.extend({
model: function() {
return App.Product.find();
}
});
The code above populates the model used in the products route (which you would access at http://yourdomain.com/#/products). Internally it will generate the code for your ProductsController, or you can define your own, which should extend ArrayController.
Controllers will have a content property which is an alias to the model or model collection. Again, convention over configuration.
4 Display the information using {{#each}} with a handlebars template
Providing you're following the conventions, in your handlebars template, you should iterate through your collection like this:
{{#each product in controller}}
{{#linkTo 'product' product}}
{{product.name}}
{{/linkTo}}
{{/each}}
Does ember-data have a built in way of retrieving data? If not, where
should the AJAX request be implemented?
Yes, simply call App.Product.find() for a product model and it return you a blank ModelArray while firing the AJAX request to the products resource in your backend, then materialize/populate your data into each model once it receives the data back from the server.
What is the best way to insert the JSON data into the DS model?
You shouldn't be concerned about this if you're using ember-data. The framework does that for you in most cases. That's why we love it. You might, however, have to configure mapping, namespace and plurals depending on your backend.
What is the best way to then sync the models up with a Controller?
Something similar to this:
var product = App.Product.createRecord({
name: 'laptop',
imageUrl: 'path/to/image.png'
});
product.save();
This should fire a POST or PUT request to your backend API.
You should definitely check:
http://emberjs.com/guides/
https://peepcode.com/products/emberjs
http://toranbillups.com/blog/archive/2013/01/03/Intro-to-ember-js-and-the-new-router-api/
Making the AJAX request
// Find all pets.
var pets = App.Pet.find();
// Find pet with ID of 1.
var pet = App.Pet.find(1);
Into DataStore Models
pets above will be a DS.RecordArray containing many App.Pet models, whereas pet is just one App.Pet.
Store in Controller
App.IndexRoute = Ember.Route.extend({
model: function() {
return App.Pet.find(4);
}
});
The router is used to setup the controller, and so we specify here that the IndexController should hold one App.Pet with the ID of 4. This can of course be dynamic. Since your controller represents only one model, it should be of the type ObjectController, but if it was used to store many pets, then it should be of the type ArrayController.
By specify the model, you will have access to it in your IndexController and index view (data-template-name="index"). This is because when you move into your index route, the IndexController is located/instantiated, IndexView is instantiated and placed into the DOM, all after consulting the IndexRoute for setting up the controller.
You can now do something like this in your template (although model. is not necessary): {{model.name}}, which will get you your pet's name.
Display using #each
Find all your pets using a modified version of the above code, but returning all of the pets. Remember, this is done by specifying no arguments to your find method:
App.IndexRoute = Ember.Route.extend({
model: function() {
return App.Pet.find();
}
});
Now we can do loop through all of the pets in the index template. Whilst there are many ways to loop, such as including content./model., excluding .content/model, using this, controller, et cetera..., it's not necessary, but that's for another day. What matters at the moment is that this will work for you, and will be the most self-intuitive:
{{#each pet in controller}}
{{pet.name}}
{{/each}}
I'll put together a jsFiddle for this if you would like. Please let me know.
Questions
Does ember-data have a built in way of retrieving data? If not, where
should the AJAX request be implemented?
Yes, that's Ember Data module which has some good guides on EmberJS.com.
What is the best way to insert the JSON data into the DS model?
Using Ember Data as per the examples up above.
What is the best way to then sync the models up with a Controller?
Using the model hook in the appropriate route to specify which model(s) your controller represents.

Resources