laravel速记(笔记)
命令行:
php artisan controller:make UserController
This will generate the controller at /app/controller/user.php and user.php.
php artisan db:seed --class=AuthorTableSeeder php artisan db:seed,可以执行多个填充类。该方法是执行的DatabaseSeeder这个类
获取已持久化的用户提交的信息:
Input::old('username')
Querying using raw SQL statements
$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.
$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所有数据。
$shows=Show::all();
echo '<h1>All shows</h1>';
foreach($shows as $show)
{
echo $show->name,' - '.$show->rating . ' - '. $show->actor .'<br/>';
}
用户验证:
<?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');
仅仅看上面的或许不理解,看官网文档:
RESTful Controllers
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:
public function getAdminProfile() {}官网文档看完了,接着上面的。
几个视图如下:
index.php
<style>
table, th, td {
border:1px solid #
}
</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
laravel速记(笔记)的更多相关文章
- Laravel学习笔记(三)--在CentOS上配置Laravel
在Laravel框架上开发了几天,不得不说,确实比较优雅,处理问题逻辑比较清楚. 今天打算在CentOS 7上配置一个Laravel,之前都是在本机上开发,打算实际配置一下. 1)系统 ...
- Laravel学习笔记之Session源码解析(上)
说明:本文主要通过学习Laravel的session源码学习Laravel是如何设计session的,将自己的学习心得分享出来,希望对别人有所帮助.Laravel在web middleware中定义了 ...
- Laravel学习笔记之PHP反射(Reflection) (上)
Laravel学习笔记之PHP反射(Reflection) (上) laravel php reflect 2.1k 次阅读 · 读完需要 80 分钟 3 说明:Laravel中经常使用PHP的反 ...
- 慕客网laravel学习笔记
session中set方法使用 Session::set('user.username.age','18')嵌套使用得出$user = ['username'=>['age'=>18]]; ...
- laravel安装 笔记
http://laod.cn/hosts/2015-google-hosts.html 谷歌FQIP laravel安装和设置流程 1安装composer , VirtualBox和Vagrant 下 ...
- laravel 学习笔记 — 神奇的服务容器
2015-05-05 14:24 来自于分类 笔记 Laravel PHP开发 竟然有人认为我是抄 Laravel 学院的,心塞.世界观已崩塌. 容器,字面上理解就是装东西的东西.常见的变量.对象属 ...
- laravel安装笔记
一.安装composer 安装之前将\php\php.ini文件中的php_openssl.dll扩展库开启,否则composer在安装过程中会出现错误提示. (我在安装过程中发现apache目录下的 ...
- Laravel学习笔记(五)数据库 数据库迁移案例2——创建数据结构,数据表,修改数据结构
默认假设 所有的列在定义的时候都有默认的假设,你可以根据需要重写. Laravel假定每个表都有一个数值型的主键(通常命名为”id”),确保新加入的每一行都是唯一的.Laravel只有在每个表都有数值 ...
- Laravel学习笔记(四)数据库 数据库迁移案例
创建迁移 首先,让我们创建一个MySql数据库“Laravel_db”.接下来打开app/config目录下的database.php文件.请确保default键值是mysql: return arr ...
随机推荐
- ActiveMQ之Topic
与Queue不同,Topic实现的是发布/订阅模型,在下面的例子中,启动两个消费者共同监听一个Topic,然后循环给这个Topic发送多个消息. 例子: public class TopicTest ...
- 多实例MySQL批量添加用户和密码并授权
OS:Cent OS 6.3 DB:5.5.14 如果一台服务器上有100个MySQL数据库实例,此时需要给不同端口的几个数据库添加用户名.密码并授权应用IP,一个个授权没问题,反正累的不是我,哇咔咔 ...
- ASP.NET MVC 学习第一天
今天开始第一天学习asp.net mvc,写的不是很好,高手不要喷,希望大家能一起进步学习. 好了,开始学习 新建项目,选择mvc 4应用程序 接下来选择基本,视图引擎当然要选择Razor,如果在选择 ...
- openstack安装、卸载与启动
一.安装: 更新: sudo apt-get update sudo apt-get upgrade 安装图形化界面: sudo apt-get install ubuntu-desktop 安装gc ...
- 学习Ember遇到的一些问题
1.在模板中不能省略结束标签: 在Ember的模板中,如果省略结束标签的话,会有好多无解的问题(可能是:不更新.更新后结构不对.model和view不同步等),苦苦找了很久.... 2.childVi ...
- 51nod 1640 天气晴朗的魔法 最小生成树
题目链接: http://www.51nod.com/onlineJudge/questionCode.html#!problemId=1640 题解: 先求最小生成树,记录最大边. 然后求最大生成树 ...
- Hadoop集群中pig工具的安装过程记录
在Hadoop环境中安装了pig工具,安装过程中碰到了一些问题,在此做一下记录: 主要安装流程参考:http://www.cnblogs.com/yanghuahui/p/3768270.html ...
- SQL SERVER其它函数
本篇文章还是学习<程序员的SQL金典>内容的记录,此次将讲解的是SQL SERVER常用的其它函数.(其它数据库这里就不罗列了,想看更多的可以关注<程序员的SQL金典>). 具 ...
- javascript小实例,PC网页里的拖拽(转)
这是现在的效果,可能改了一些,原来的效果是,里面的这张图是可以上下左右拖动的,然后房子上面的显示的楼栋号,也跟着图片一起移动,当时js能力还不行,未能实现项目经理的要求,不过后来项目经理又把这个效果推 ...
- 关闭VS时, 每次都 会弹出 保存以下各项的更改吗?
如果是添加项目, 或修改了解决方案的配置, 会弹出这个是正常的. 如果在没有修改的情况下还这样就是有问题的. 原因: 在Vs中安装了PowerDesigner插件, 并在VS中点了该插件的东西 ...