Laravel + AngularJS application structure - javascript

Currently im in the process of architecturing an application based on Laravel-4 and AngularJS
I do not want to create a single page application.
Is it ok to structure the application along the follwoing lines:
EventsController
Get() returns a laravel view
index() returns json array of events
show() returns json event object
Store() saves a json event object
and generally all the controllers will act in this way, having a get method that serves a laravel blade view and is then manipulated via AngularJS and its partials. Is this best practice?

The plan
Use laravel to create the routes and let laravel create the views. You only need to create different view templates, which hold references to your angular controllers.
PagesController
What you could do is create routes for pages, which renders the views.
So you could have a PagesController which can do this
EventsController
Then use angular to call for the data and have a EventsController for that.
In the EventsController you could add your CRUD, which calls a Event model.
Then this will be the way the traffic get's called
The Model needs to return data.
The Controller then will return json, with http status codes.
Mini example
Underneath is a way how I do this with flash messages when logging in.
return Response::json(array('flash' => 'Invalid username or password'), 500);

Related

How to connect laravel api with pure html website

Since I am new to laravel api, I don't know hot to connect laravel api to html endpoint. My laravel api is working well and html web pages also completely finish. I just want to connect them together... Please explain how to connect these two.
Thank you
I would suggest two ways to go about this but it all depends on what your API does. If you are looking to serve the HTML with Laravel and have some parts of the application loaded by Laravels view() method, you'd basically need to break your HTML into blade files in resources/view folder and call the blade files via view() in controller to load the desired page.
However if you are looking for a separation of view and API where API is called by the view only for some information, you'd need to utilize AJAX via JavaScript to make a call to the API endpoint and retrieve the data (JSON) for use in your HTML site.
I use axios a lot and here is a sample call:
axios.get(url).then(response => { // do whatever here with the response data });
I'm not sure I understand you. But it reads like you developed your Laravel Application (PHP) and HTML separately. Laravel uses Blade (see: https://laravel.com/docs/7.x/blade) as a template engine into which you can inject PHP objects. Basically, the call of a web page (more or less) works like this:
The user is calling the url
URL goes to the routes/web.php
in this file you can call e.g. a controller
the controller called via (e.g.)
return view('my.site.nice-site', [ key => value]);
blade starts and displays the page to the user with the given key as variable.
I hope this helps you a bit. Otherwise I recommend, just to get started, the documentation from Laravel or YouTube.

How to connect Laravel 5.4 backend with Angular 5 Frontend

I am working on a project where I need to develop frontend in angular 5 and backend business logic in laravel 5.4 with mySql Database. I am a newbie to this technology and dont know how to develop data flow connection between these two framworks.
It will be helpful if you tell me the easiest and most generic way to solve this out.
As with any other technology, you'll need to work with an API.
In your Laravel project:
Your Laravel project should have models, controllers and a file for the route paths for each method in your controllers, right? If you don't know where the routes are, there's a dedicated folder called "routes" at the root of your project.
Inside this folder, you'll have two important files: api.php and web.php. These two work exactly the same way, but the api.php will automatically add '/api' to the beginning of your route.
A route looks like a link, such as: "yourdomain.com/api/person/name/jondoe". Every route has to be accessed through an HTTP method, usually GET, POST, PUT or DELETE.
Example: let's say you need your user to see a list of people. You'll probably have a Person model and a PersonController containing some function called displayAllPeople(), and this function will select the people from your database. In your api.php file you'll add something like:
Route::get('/people', 'PersonController#displayAllPeople');
You can test that in your browser. Try to access http://yourdomain.com/api/people. You should see a JSON output of your function's return data. In this example, a list of people. Now all we have to do is make your Angular project call this API route.
Source: https://laravel.com/docs/5.7/controllers
In your Angular project:
Remember that Person model you created on your backend? Angular will access that model too, so you'll have to create a Person.ts model here. While that's not required to work, it's a good practice to create this model with the same attributes as the backend model.
Now you'll need a service. The service is a file that will access that Laravel route for you. If you're using Angular CLI, just run the command:
ng generate service person
That will create a person.service.ts file for you. Inside this file, you'll write all the functions to select people, update, save, delete people, and so on. Your function will look something like this:
findAll(): Observable<Person[]> {
return this.http.get<Person[]>('yourdomain.com/api/people');
}
Whenever you call the findAll() function, you'll access the Laravel route, which will return the People from your database. You can do that with any operation you want. Just make sure you follow the HTTP standards.
That also works if you want to send some data from your frontend to the backend, like if you want to save some new Person in your database. You'll need a POST call sending your new Person model which will be received by your Laravel's Controller function, and then persist it in the database.
Source: https://angular.io/tutorial/toh-pt4

How can I access this Flask global from AngularJS?

I am building a internal web app with Flask that connects to various clusters. 95% of the URLs start with /cluster/cluster_name so I use the following code in my blueprints:
cluster = Blueprint('cluster', __name__, url_prefix='/cluster/<cluster_name>')
#cluster.url_defaults
def add_cluster_name(endpoint, values):
values.setdefault('cluster_name', g.cluster_name)
#cluster.url_value_preprocessor
def pull_cluster_name(endpoint, values):
g.cluster_name = values.pop('cluster_name')
Which then allows me to use the following code to create a connection to the cluster before each request:
#app.before_request
def before_request():
if not hasattr(g, 'manager'):
g.manager = ClusterInterface(g.cluster_name)
This works perfectly and allows me to use {{ g.cluster_name }} in jinja2 templates.
The problem is that I am moving to an AngularJS app for the frontend so I won't be using jinja2 templates/render_template() anymore.
So how can I have this global available to AngularJS templates without returning its value from every Flask views?
Thank you.
Your views will now send JSON data instead of rendered HTML templates in order to communicate with Angular. So make this data available in the JSON response.
return jsonify(cluster_name=g.cluster_name)
More likely, you should just send the default and available names when you first start the Angular app, and let it handle the value on it's end.
Sending g.manager is impossible, since it's a Python object with (probably) complex behavior, not something that is JSON serializable.

can I pass data when routing in angular

I want to pass a lot of data (json) when routing to a new controller in angular.
In controller A I call $location.path('/B'); which in turn will route to controller B.
I know I can pass parameter in the url itself, but I have a lot of data.
Can angular do something similar to 'POST' method and pass data in this way?
No need to bother with POST like behavior with angular.
You have several ways to do this :
use a service that will preserve data across page loads
pass real GET argument (when the page is specifically linked to this argument, for example an object ID used to display this object details)
store data in local storage / session storage
use controller 'resolve' functionnality to fetch new data before displaying page (not what you want to do though...)
Remember you're not actually changing the page, so you don't need to 'POST' data anywhere or do anything similar.
Instead you should create a service that makes that data available through dependency injection, then specify the dependency when you instantiate the controller that handles the new route.

Backbone.js Push state and page state after reload using Symfony

ive got a question. Im using backbone.js with push state and navigate to push url and execute actions. Im using symfony2 for backend. Now the question is how to handle the routes e.g. /reviews that are loaded via symfony routing, not backone. Is there any was to avoid code duplication?
If you only target is javascript-enabled clients, don't do anything on those routes - just show the same page for all the requests received by symphony.
If you want to support clients without javascript too, try to reuse your templates. You can use the underscore templates http://documentcloud.github.com/underscore/docs/underscore.html#section-120 (just change the delimiters to use {{ and {* and use Twig in symphony). Then, you should make sure you send the same data to the template from symphony and from Backbone. Basically, when you render a template, you send data in the same format as you do on the server.
var PostView = Backbone.View.extend({
render: function() {
$(this.el).html(this.template({post: this.model.toJSON()}));
// so you can use post.title post.description in the template
}
})

Categories

Resources