I am new to Laravel and not quite sure how to move my PHP code to Laravel
currently, I have an android app that communicates with the server with android volley throught a url www.example.com/test.php
android volley sends out some POST parameters ( example: userID, RestaurantId etc ) to the .php file
In the file it creates the correct .json structure from table(s) using PDO with prepared statements to connect to the db
then it returned a .json with json_encode()
how do I move this code to laravel?
do I really need an authorization/login page for this?
You will have to do a bunch of stuff to achieve this. You will probably not be able to transform your code since laravel will do all the database communication using eloquent. Routing is also a completely different concept than in plain php.
I still highly recommend using laravel since you will have less security issues.
Here's a list of topics and steps you will need to have a look at to achieve what you described.
Assuming you have a fresh laravel setup with the newest version you will have to look at the web middleware which you probably don't need for an api. It can be found in the RouteServiceProvider where it is defined to be used on every route in your routes.php file. If you have an older version of Laravel 5.2 it might be defined as group in the routes.php itself. Remove web middleware and maybe add api middleware if needed
Create routes in your routes.php file to define which "url" are used to respond to requests
Create controllers to handle those incoming requests. If you do not have a lot of code you can handle them directly in the routes.php as anonymous function
Models are basically your Tables. You should define a model for each of your tables. A user model is already defined by default. Have a look in it's code. You will also define relations between models. This will make CURD operators on linked models very easy.
Migrations are the definitions of your tables. It consists of "what should be done when the migration is run" (up function) and "what should be done in case of a rollback" (down function)
If you return classes / arrays in laravel it will automatically be parsed to json
Looking at your example I'd assume you will have a user model and a restaurant model if you for example have a vote system where a user votes / rates a restaurant you would have a many to many relationship between user and a restaurant.
if a restaurant belongs to an user it would be oneToMany since a user can have multiple restaurants.
Defining relations looks like this ( User.php Model )
public function restaurants() {
return $this->hasMany('App\Restaurants');
}
The Restaurant.php would look like this
public function user() {
return $this->belongsTo('App\User');
}
With this setup ensure your Restaurant table has a "user_id" foreign key field to the user table.
Querying all restaurants of a user will now look like this
return $user->restaurants;
But these are just some high level examples which should explain to you how laravel works and why you can benefit from it. It reduces your boilerplate code and provides you with a solid set of functions, helpers and concepts that will help you to easily enhance your application - once it was set up.
You can have a look into the docs for more details https://laravel.com/docs/5.2
And find awesome tutorials at http://laracasts.com
Related
I have a question in regards to design/refactoring an existing app. My existing app is in Laravel. We have models like User, which you would imagine be linked to the Users table in the database.
Now I am planning to move this User table to an external database, which can be reached from my application with an API call.
In all the Different parts of the application there are calls to the Current User Model like User::find(Id). This wont work anymore since now Users table is not there anymore in the database.
1st Question: how to accomplish the above by changing the model reference to call an API instead of a DB table. Is there any design pattern that can be leveraged so that I dont have to change all the User::find in all of the applications.
2nd Question: How would you handle places where the table is directly referenced by joins. Like table.x = User.x
Any help/guidance would be appreciated. Thanks
What it sounds like you need is a layer that sits over your models (perhaps something similar to the Repository Pattern). This way you can abstract out your data access layer (currently Models) and make it easily swappable for another implementation (such as API requests). This is a bit more work in Laravel 4 than 5, and may possibly require significant refactoring.
As for your second question, your API will have to govern more advanced queries and have an endpoint/method for them.
I am building a PHP Laravel v5.3 app that will function as a Notebook with Notes and Tags as well as Note revisions/versions which can be used to restore a Note record to an older version of the Note.
It is basically an EverNote Clone in PHP similar to the open source Project Paperwork but will not be using AngularJS.
Based on that description above, my project has these Models:
Notebook
Note
NoteVersion
NoteTag
I have these Controller Classes to process the incoming HTTP Requests to the server Notebooks, Notes, and NoteVersions.
I need to have a function that will query the database for 2 NoteVersion records and return them as part of a JSON response which will be used as part of a view to show a comparison of 2 Note Versdions so a user can see the difference between the 2 records.
So assuming I add a new Controller Method to build this view, if I don't want the COntroller Method to handle the whole process of query the Database and doing all the work, what type of File would I put a function like that in instead?
Assume the function I want to build is like this:
get2NoteVersionsForComparison($currentNoteId, $oldNoteId);
In my controller method I want to call this method get2NoteVersionsForComparison($currentNoteId, $oldNoteId) and have it return a JSON response.
So where best would my get2NoteVersionsForComparison($currentNoteId, $oldNoteId) method live at?
A Repository, Model, ServioceProvider?
I like to create a new project or company-specific folder and create a class in that folder. So, for example, App\Acme\MyClassFile.php would be the location. Create classes that do everything else. Sort of like a repository, if you will. But where doesn't matter as long as you use proper namespacing.
We are developing an application with Laravel framework, it is supposed to be a RESTful Application which is implemented via the resources of Laravel framework, given the following example:
class CategoryController extends Controller
{
public function __construct() {
}
public function index()
{
return response()->json($this->getAll());
}
public function create()
{
//
}
public function store(Request $request)
{
//
}
Let's take the following example:
Some methods like store and create are only permitted by the admin of the website but index method is permitted by all the users and there are so many cases like this example-different type of users can only access some methods of a Contrller.
In this case we can either benefit from Multi Auth of Laravel and create different tables for the storing the users or define different type for users in the same table and handle users' access with middleware that apply to some specific functions
Question:
which way do you recommend and please provide the reasons behind your suggestion as well
So, the answer depends on various parameters. The goal you're trying to achieve can be achieved using Laravel Multi-Auth or any RBAC (Role Based Access Control) system.
Situations where you should use RBAC: If your application is small you should go for any Role Based thing.
For Example.. Let's say you're working on some CMS then you won't create tables for each position (Manager, Developer, Marketing Head etc..) hence the RBAC is good option for you.
Situations Where you should use Multi-Auth: If your goal is big and you want to separate user login table and admin login table for any reason you can go for it.
What I suggest
What I suggest is to go for both, Multi auth as well as RBAC ( only if you're working on or trying to build very large scale application )
But as you're described, just keeping that in mind I would suggest you to go with RBAC not multi auth.
Some Useful links
Laravel Docs
RBAC (One of the Most Popular RBAC package for laravel)
If you feel like going for Multi Auth please follow This blog post Multi-Auth with Laravel 5.2
If I'm missing something or the answer can be improved any way, feel free to comment.
Just really what the title says, does anybody have a decent explanation on how to use models properly in laravel 4? I'm fine with using the pre-existing User model. But I read somewhere that queries and such should be done in a model of your own.
So what I have is basically a form where you can make a status update (like facebook) and it stores it in a database but the query is run through the controller.
I want it to be done through a model.
Any information on this would be great! Thanks in advance
It's a broad question and right place to learn about how to use model in Laravel-4 is the laravel site itself, but anyways.
Actually, model is the the place where you should keep the business logic in any MVC framework, it could be database related or anything else that is the heart of the application and controller and View are just two parts of the application whose responsibility is only communicate to the model, fetch data and present it to the user but all the data processing should be done in the model and controller should be kept slim and view is only a mechanism to present the user a UI.
So, if you want to have a User model in your application (laravel-4) then you may extend it from Eloquent like
class User extends Eloquent{
// code goes here
}
and then call it's methods from the controller, like
$user = User::get(1);
then passing it to the view like
return View::make('viewname', $user);
That's it. But, if you think, where the find method come from then, it's because, you have extended the Eloquent model and in that model all the necessary methods (find e.t.c) are available and your User model inherited the behavior of Eloquent model, so you can use all the methods from User and it's not necessary to a single method in your User model unless you need to write some special methods for that User model, like relationship functions and so. well, the perfect place to seek help or to know the basic about it is the Laravel site, try to understand it from there and if you fail or just stuck anywhere then come here to ask with specific problem. Also, check Basic Database Usage and Query Builder.
BTW, you may check this post for a detailed answer on model of MVC.
Cake's documentation says "Most commonly, controllers are used to manage the logic for a single model." I'm finding this is uncommon for most of my code, and I don't want to break convention unless it is proper to do so.
For example, my application sends a user to their account dashboard after they log in - this uses data from probably half a dozen tables, not all of which are even related. Do I create a "dashboard" controller for this (even though there is no dashboard model or table)? Or do I create a dashboard method in an existing controller?
Thanks, Brian
I have a similar situation and how I handle it is keeping the actions that connect a lot of models in the controller that is the most centric. For instance, my user can create voicenotes, comments, has settings, has twitter and facebook information. All this information I can get from my user model $this->User->Voicenotes->find('all'), for example.
I believe creating additional controllers might just confuse you, use what cake gives you, you can specify that models are to be used in a controller either by setting the $uses variable or using loadModel in the controller action, if you have your relations set up you can just do it the way i described before, no need to create additional controllers.
I guess it depends on how you want your own app to work and what comes easier in your situation.