命令行:php
php artisan controller:make UserControllerhtml
This will generate the controller at /app/controller/user.php and user.php.laravel
php artisan db:seed --class=AuthorTableSeeder
php artisan db:seed,能夠執行多個填充類。該方法是執行的DatabaseSeeder這個類
獲取已持久化的用戶提交的信息:git
Input::old('username')github
Querying using raw SQL statementsweb
$sql=" insert into shows(name,rating,actor) VALUES(?,?,?)"; $data1 = array('Doctor Who', '9', 'Matt Smith'); $data2 = array('Arrested Development', '10', 'Jason Bateman'); $data3 = array('Joanie Loves Chachi', '3', 'Scott Baio'); DB::insert($sql,$data1); DB::insert($sql,$data2); DB::insert($sql,$data3); $sql = "DELETE FROM shows WHERE name = ?"; DB::delete($sql, array('Doctor Who')); DB::delete($sql, array('Arrested Development')); DB::delete($sql, array('Joanie Loves Chachi'));
class Show { public function allShows($order_by = FALSE, $direction = 'ASC') { $sql = 'SELECT * FROM shows'; $sql .= $order_by ? ' ORDER BY ' . $order_by . ' ' . $direction : ''; return DB::select($sql); } }
Route::get("shows",function(){ $shows=new Show(); $shows_by_rating=$shows->allShows('rating','DESC'); dd($shows_by_rating); });
dd:Dump the passed variables and end the script. sql
$data1 = array('name' => 'Doctor Who', 'rating' => 9, 'actor' => 'Matt Smith'); $data2 = array('name' => 'Arrested Development', 'rating' => 10, 'actor' => 'Jason Bateman'); $data3 = array('name' => 'Joanie Loves Chachi', 'rating' => 3, 'actor' => 'Scott Baio'); DB::table('shows')->insert(array($data1,$data2,$data3)); DB::table('shows')->where('name', 'Doctor Who') ->orWhere('name', 'Arrested Development') ->orWhere('name', 'Joanie Loves Chachi') ->delete();
獲取model全部數據。swift
$shows=Show::all();
echo '<h1>All shows</h1>';
foreach($shows as $show)
{
echo $show->name,' - '.$show->rating . ' - '. $show->actor .'<br/>';
}api
用戶驗證:restful
<?php class User extends Eloquent { protected $table = 'users'; private $rules = array( 'email' => 'required|email', 'username' => 'required|min:6' ); public function validate($input) { return Validator::make($input, $this->rules); } }
Make a route that loads the ORM and tries to save some data:
$user = new User();
$input = array();
$input['email'] = 'racerx@example.com';
$input['username'] = 'Short';
$valid = $user->validate($input);
if ($valid->passes()) {
echo 'Everything is Valid!';
// Save to the database
} else {
var_dump($valid->messages());
}
There are a few other ways to validate our data using models. One way is to use a package
that will handle most of the validation work for us. One great package to use is Ardent, which
can be found at https://github.com/laravelbook/ardent.
Using advanced Eloquent and relationships
Schema::create('show_user', function($table) { $table->increments('id'); $table->integer('user_id'); $table->integer('show_id'); $table->timestamps(); });
Create a User.php file in the app/model directory:
class User extends Eloquent {
public function shows()
{
return $this->belongsToMany ('Show');
}
}
5. Create a Show.php file in our app/model directory:
class Show extends Eloquent {
public function users()
{
return $this->belongsToMany ('User');
}
}
6. Make a route in routes.php to add a new user and attach two shows:
Route::get('add-show', function() { $user=new User(); $user->username = 'John Doe'; $user->email = 'johndoe@example.com'; $user->save(); //attach two shows $user->shows()->attach(1); $user->shows()->attach(3); foreach($user->shows()->get() as $show) { var_dump($show->name); } });
Make a route to get all the users attached to a show:
Route::get('view-show', function()
{
$show = Show::find(1)->users;
dd($show);
});
很奇怪attach()方法是怎麼插入數據到
上面三張表分別是:(最好在模型設置$table="name";
users shows show_user.
是根據名字來的。
把shows改爲show不行。
都改爲單數
user sho show_user能夠。
把show_user改爲user_show不行。
由於:
the show_user is derived from the alphabetical order of the related model names.
另外還有一點,user表中的creaetd_at,udpate_at是會存進去的。咱們調用$user->save()程序會自動作的。
可是
$user->shows()->attach(1); 就不會了,須要咱們本身傳進去
$date=date("Y-m-d H:i:s");
$user->shows()->attach(1,array('created_at'=>$date,'updated_at'=>$date));
調用belongsToMany返回http://laravel.com/api/class-Illuminate.Database.Eloquent.Relations.BelongsToMany.html
BelongsToMany類,調用get方法能夠get( array $columns = array('*') )
Execute the query as a "select" statement。
There's more...
Database relationships can get fairly complicated and this recipe merely scratches the surface
of what can be done. To learn more about how Laravel's Eloquent ORM uses relationships, view
the documentation at http://laravel.com/docs/eloquent#many-to-many.
該文檔部份內容:
Many-to-many relations are a more complicated relationship type. An example of such a relationship is a user with many roles, where the roles are also shared by other users. For example, many users may have the role of "Admin". Three database tables are needed for this relationship: users
,roles
, and role_user
. The role_user
table is derived from the alphabetical order of the related model names, and should have user_id
and role_id
columns.
We can define a many-to-many relation using the belongsToMany
method:
class User extends Eloquent {
public function roles()
{
return $this->belongsToMany('Role');
}
}
Now, we can retrieve the roles through the User
model:
$roles = User::find(1)->roles;
If you would like to use an unconventional table name for your pivot table, you may pass it as the second argument to the belongsToMany
method:
return $this->belongsToMany('Role', 'user_roles');
You may also override the conventional associated keys:
return $this->belongsToMany('Role', 'user_roles', 'user_id', 'foo_id');
Of course, you may also define the inverse of the relationship on the Role
model:
class Role extends Eloquent { public function users() { return $this->belongsToMany('User'); } }
Creating a CRUD system
To interact with our database, we might need to create a CRUD (create, read, update, and
delete) system. That way, we add and alter our data without needing a separate database
client. This recipe will be using a RESTful controller for our CRUD system.
<?php class UsersController extends BaseController { public function getIndex() { $users=User::all(); return View::make('users.index')->with('users',$users); } public function getCreate() { return View::make("users.create"); } public function postCreate() { $user=new User(); $user->username=Input::get("username"); $user->email=Input::get("email"); $user->save(); return Redirect::to('users'); } //編輯Edit get public function getRecord($id) { $user=User::find($id); return View::make('users.record')->with('user',$user); } //編輯Edit post public function putRecord() { $user = User::find(Input::get('user_id')); $user->username = Input::get('username'); $user->email = Input::get('email'); $user->save(); return Redirect::to('users'); } public function deleteRecord() { $user = User::find(Input::get('user_id')) ->delete(); return Redirect::to('users'); } }
路由:Route::controller('users', 'UsersController');
僅僅看上面的或許不理解,看官網文檔:
Laravel allows you to easily define a single route to handle every action in a controller using simple, REST naming conventions. First, define the route using the Route::controller
method:
Route::controller('users', 'UserController');
The controller
method accepts two arguments. The first is the base URI the controller handles, while the second is the class name of the controller. Next, just add methods to your controller, prefixed with the HTTP verb they respond to:
class UserController extends BaseController { public function getIndex() { // } public function postProfile() { // } public function anyLogin() { // } }
The index
methods will respond to the root URI handled by the controller, which, in this case, isusers
.
If your controller action contains multiple words, you may access the action using "dash" syntax in the URI. For example, the following controller action on our UserController
would respond to the users/admin-profile
URI:
官網文檔看完了,接着上面的。
幾個視圖以下:
index.phppublic function getAdminProfile() {}
<style> table, th, td { border:1px solid #444 } </style> <table> <thead> <tr> <th>User ID</th> <th>User Name</th> <th>Email</th> <th>Actions</th> </tr> </thead> <tbody> <?php foreach($users as $user): ?> <tr> <td><?php echo $user->id ?></td> <td><?php echo $user->username ?></td> <td><?php echo $user->email ?></td> <td> <a href="users/record/<?php echo $user->id ?>">Edit</a> <form action="users/record" method="post"> <input type="hidden" name="_method" value="DELETE"> <input type="hidden" name="user_id" value="<?php echo $user->id ?>"> <input type="submit" value="Delete"> </form> </td> </tr> <?php endforeach; ?> </tbody> </table> <a href="users/create">Add New User</a>
注意畫紅線的:
<input type="hidden" name="_method" value="DELETE">.
若是去掉這個點擊delete會找不到,緣由大概是由於http如今不支持delete和put方法,laravel採用了一個隱藏的_method 來實現這個。
create.php
<form action="create" method="post"> Username:<br> <input name="username"><br> Email<br> <input name="email"><br> <input type="submit"> </form>
record.php
<form action="" method="post"> <input type="hidden" name="_method" value="put"> <input type="hidden" name="user_id" value="<?php echo $user->id ?>"> Username:<br> <input name="username" value="<?php echo $user->username ?>"><br> Email<br> <input name="email" value="<?php echo $user->email ?>"><br> <input type="submit"> </form>
------------------------
一個小技巧
Using attributes to change table column name
Sometimes we may be working with a database that was created using less-than-logical
column names. In those cases, we can use Laravel's Eloquent ORM to allows us to interact
with the table using more standardized names, without having to make database changes.
好比user表有個column name是MyUsernameGoesHere,
這個很是很差,能夠在模型裏面定義一個方法:
public function getUsernameAttribute($value) {
return $this->attributes['MyUsernameGoesHere'];
}
而後就能夠用$odd->username 了。
Building a RESTful API with routes
A common need for a modern web application is having an API that third-parties can run
queries against. Since Laravel is built with RESTful patterns as a focus, it's quite easy to build
a full API with very little work.
參考<laravel devolpment cookbook>
We could also use Laravel's resourceful controllers to accomplish something similar. More
information about those can be found in the documentation at http://laravel.com/
docs/controllers#resource-controllers.
傳遞數據給view
Route::get('home', function()
{
$page_title = 'My Home Page Title';
return View::make('myviews.home')->with('title',
$page_title);
});
Route::get('second', function()
{
$view = View::make('myviews.second');
$view->my_name = 'John Doe';
$view->my_city = 'Austin';
return $view;
});
There's more...
One other way to add data to our views is similar to the way in our second route; however we
use an array instead of an object. So our code would look similar to the following:
$view = View::make('myviews.second');
$view['my_name'] = 'John Doe';
$view['my_city'] = 'Austin';
return $view;
Loading a view into another view/nested views
Route::get('home', function()
{
return View::make('myviews.home')
->nest('header', 'common.header')
->nest('footer', 'common.footer');
});
home.php:
<?= $header ?>
<h1>Welcome to the Home page!</h1>
<p>
<a href="second">Go to Second Page</a>
</p>
<?= $footer ?>
adding assets增長資產
Adding assets
A dynamic website almost requires the use of CSS and JavaScript. Using a Laravel asset
package provides an easy way to manage these assets and include them in our views.
http://www.tuicool.com/articles/N3YRFf
http://eric.swiftzer.net/2013/06/laravel-4/
http://www.tuicool.com/articles/6viiem
http://laravelbook.com/laravel-user-authentication/
http://www.tuicool.com/articles/qaAn2a
laravel restful:
http://www.tuicool.com/articles/7baI3a