I'm getting started with PHP and I wanted to know if there is a way that you can extract data from the DB in a model.
If I have a Users table in my DB, I'm looking for something like Users.all in rails that will use the model to extract all the entires in the Database.
Does PHP offer that type of functionality?
The closest to Rails is Laravel. Laravel's database layer Eloquent was already mentioned in the comment. Eloquent: Getting Started
If you go for an ORM instead of Eloquent's active record pattern Doctrine is the most popular project. Doctrine Website
Pure php doesn't provide an ORM out of the box ( I suppose you can install a package or something), but if you are using Laravel (since the tag in your question), you need to create a model (supposing you have a migration for users_table)
php artisan make:model user
then simply 'use' the model in any controller
use App\User
and get all users :
$users = User::all();
Related
For a project at work I'm creating an API in Laravel. I wanted to use MongoDB as database driver which is new to me. So I want to use Eloquent with MySQL in the beginning and when I'm confident enough switch to MongoDB.
I was reading some tutorials about the repository pattern in Laravel and saw that some returned an eloquent model, like this one. It seems to me that when returning a model on for example create($data), you're limited to database drivers which are suitable with Eloquent. I was wondering if it is a good practice to return an eloquent model. Because if I want to use MySQL for now and in the future MongoDB (without the Laravel MongoDB package), I need to rewrite some code in the controllers because the use the eloquent models instead of an array (for example). Maybe a 'wrapper' between the model and your code is a possibility? Any good recommendations, tips or thoughts on this?
If you're wondering why I want to use MySQL for now and later switch to MongoDB, the reason is there is a time limit on the project. I'm still learning Mongo. So to fulfil the needs of my employer, I'm not using MongoDB until finishing the first version / prototype.
If you use eloquent and its methods, you should be good. Just do not use the DB::raw() method as it may break your query if it does not match the DB engine you are currently in.
I wrote a repository pattern article if you want to look at it (with tdd).
But if you really want future proof, you can mix Doctrine w Laravel since Doctrine is a Data Mapper Pattern. Link
With laravel-doctrine package, you persist the data in your db engine that you prefer.
Is something like laravel-mongodb good?
Extending Eloquent to use MongoDB instead of MySQL.
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
I'm learning laravel 5 and it's relationship with databases. I can find tons of info regarding how to work with sqlite and mysql but I'm having problems understanding what migrations are, how they are related with databases and my main issue...
If I have a pre-created postgres database with, let's say, 10 tables and their relationships already up and running, how can I make Laravel interact with them?
For example, I have my postgres schema table defined like this:
CREATE TABLE "users" (
"id" integer NOT NULL DEFAULT nextval('users_seq'),
"name" character varying(30) NOT NULL,
"email" character varying(50) NOT NULL UNIQUE,
"password" character varying(120) NOT NULL UNIQUE,
CONSTRAINT users_pk PRIMARY KEY ("id")
) WITH (
OIDS=FALSE
);
I already know Laravel comes with a generic migration for users table but how exactly should I work from within Laravel connecting to my db?
By the way, my database's name would be dummy.
May I use something like a migration class?
But as far as I understand, migrations are for creating/deleting/etc tables, right?
Or should I directly create a controller to interact with de db like these?
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
class PagesController extends Controller
{
public function index()
{
$users = DB::table('users')->get();
return view('DBHandler',compact('users'));
}
}
And I imagine this is the query builder way of doing things and eloquent's way is quite different.
Any help would be appreciated.
According to Documentation of Laravel:
Migrations are like version control for your database, allowing a team to easily modify and share the application's database schema. Migrations are typically paired with Laravel's schema builder to easily build your application's database schema.
If you have a team working with you, is highly recommendable to use them for changes that must be applied on the scheme to the application works, these migrations let you to apply changes to database like drop, create, update, etc. On the other hand if you're going to start developing with a Schema already created, there is no problem you can interact with your scheme with Eloquent.
The way as Laravel take information from your database is with Eloquent a ORM, Here is the introduction from Laravel Documentation:
The Eloquent ORM included with Laravel provides a beautiful, simple ActiveRecord implementation for working with your database. Each database table has a corresponding "Model" which is used to interact with that table. Models allow you to query for data in your tables, as well as insert new records into the table.
So you have to create a Model for each one of your tables, except tables many to many. If your table is Users you must name the model User and Eloquent take it automatically if not, you must overwrite the $table attribute at the model like this:
public $table = 'user';
The rest what you can do with Eloquent you can find it at the documentation here
I hope this helps you out.
From the blog laravelbooks.com, quoting:
[...] Migrations are the Laravel way of helping you to evolve the database schema of your application (also known as its DDL) without having to drop and re-create the database each time you make a change. And not having to drop and recreate the database each time a change happens means that you don’t lose your development data. The only changes made when you execute a migration are those necessary to move the schema from one version to another, whether that move is forward or backward in time.
Not only does Laravel migration provide you with a means to change your database schema in an iterative manner, but it lets you do so using PHP code, rather than SQL! The Laravel Schema Builder allows us to create database tables and insert columns or indices quickly. It uses clean and expressive syntax to make database operations happen. You may think of Laravel migration as version control for your databases! [...]
There I found a more explanatory way to laravel than the official documentation, though the later it's also good
...or I really need to create a class for each Table? then.. everytime i changes table structure i need to update the code..
You could use an ORM (Object-relational mapper) such as Eloquent, which is included in Laravel, and then just create an model (class) for each table in your database. Eloquent automatically maps each field into a PHP object. If you haven't ever used an ORM, I highly recommend you check out Laravel... it's what made me stick with PHP and I do almost all my projects using Laravel. Best of luck!
Adding to BakerStreet Response.
Eloquent fits your needs as the ORM itself will fetch all the columns you specify if you leave it as default. By default the drivers that it works with are: mysql, postgreSQL, and Sqlite.
Eloquent itself can be downloaded without Laravel being involved.
Please refer to Jeffrey Way's Laracast for instruction:
https://laracasts.com/lessons/how-to-use-eloquent-outside-of-laravel
...thanks all, ended up writting my own magic class:
DBIntrd - Simple PHP framework for SQLite3 databases
Tired of spending time writting a bunch of code to create PHP classes & methods for SQLite tables?
DBIntrd is magic way to dinamically instance objects and persists data at SQLite3 tables..
To make it clear let's make classic example - User and Post.
Creating db schema in Symfony2 is clean and simple:
we create entities Post and User
additionaly we can simply add columns/indexes to each.
then just add value with OneToMany annotation in User and ManyToOne in Post
..well, that's it. Now if we run db:schema:update --force and we can get what we want - database schema and simple adding another rows in database.
What about Laravel4? So far only solution I found:
create/generate Post and User models
declare in each model which table it refers to
create migrations and in Post migration add foregin key to user_id column
run migration
add in each model methods in which we refer to the other model (hasMany, belongsTo .. )
As I wrote it, it doesn't seem so complicated, but it's not so concentrated in Laravel as it is in Symfony. I'm kinda lazy person and I really enjoy the process in Symfony, while in Laravel it is a little bit too diffuse. Is there any simpler ( lazier :P ) way to do this in Laravel? Something like creating schema based on Model?
The question makes sense but unfortunately there isn't such functionality on Laravel at the moment.
As opposed to running migrations from your models (symfony) you must create the migrations first, the you can use the models to seed database tables if they have foreign keys.
I use the Jeffrey Way Generators https://github.com/JeffreyWay/Laravel-4-Generators
to speed up the process so for example if I have a users table and a profile table (many to many) then I would perform these tasks on command line:
php artisan generate:migration create_users_table --fields="username:string, password:string, email:string"
php artisan generate:migration create_profiles_table --fields="name:string, lastname:string, phone:string"
php artisan migrate
php artisan generate:pivot users profiles
php artisan migrate
Then you can create your models (you can also generate an entire CRUD resource or Scaffold)
php artisan generate:model user
php artisan generate:model profile
Then in your User Model
public function profile()
{
return $this->belongsToMany('Profile');
}
In your Profile Model
public function user()
{
return $this->belongsToMany('User');
}
Yes, there are some plugins / commands that speed up the development.
For example Jeffrey Way's Laravel-4-Generators