Laravel

Laravel 常用操作

2016-11-10  本文已影响236人  皮丘吉尔

基于5.1


零 、关闭debug

.env文件

APP_DEBUG=false

一、Laravel 数据库操作

1.1查询构建器(Query Builder)

php artisan make:migration create_mail_table
php artisan make:migration create_users_table --create=users//指定表名
php artisan make:migration add_votes_to_users_table --table=users//创建表
php artisan migrate//执行
php artisan migrate:rollback//回滚
php artisan migrate:reset//回滚所有
php artisan migrate:refresh//reset then migrate
php artisan migrate:refresh --seed
//判断表、列是否存在
if (Schema::hasTable('users')) {
    //
}

if (Schema::hasColumn('users', 'email')) {
    //
}
//其他db连接
Schema::connection('foo')->create('users', function ($table) {
    $table->increments('id');
});
//存储引擎
Schema::create('users', function ($table) {
    $table->engine = 'InnoDB';
    $table->increments('id');
});
Schema::rename($from, $to);
//创建列
Schema::table('users', function ($table) {
    $table->string('email');
});
//删除表
Schema::table('users', function ($table) {
    $table->dropColumn('votes');
});
use DB;
......
......
DB::select('select * from users where id = :id', ['id' => 1]);
DB::select('select * from users where active = ?', [1]);
DB::insert('insert into users (id, name) values (?, ?)', [1, 'Dayle']);
DB::update('update users set votes = 100 where name = ?', ['John']);
DB::delete('delete from users');
DB::statement('drop table users');
DB::table('users')->skip(10)->take(5)->get();
//事务
DB::beginTransaction();
DB::commit();
DB::rollBack();
//多个数据库连接
DB::connection('foo')->select(...);

1.2 Eloquent

php artisan make:model User
php artisan make:model Mail -m(生成mgration,用于表还没建立的情况)

laravel Models 文件夹、laravel model 指定路径
1、

2、composer.json

"psr-4": {
           "App\\": "app/",
           "App\\Models\\": "app/Models"
       }

composer install
3、php artisan make:model Models/Task
生成的model在app\Models\,namespace App\Models;

protected $primaryKey = 'st_id';
public $timestamps = false;
  protected $dateFormat = 'U';
$tasks = Task::where('name', 1)
               ->orderBy('id', 'desc')
               ->take(10)
               ->get();
Task::chunk(200, function ($tasks) {
    foreach ($tasks as $task) {
        //
    }
});
$task=Task::where('id',$request->id)->firstOrFail();//对应first()
$task=Task::findOrFail($id);//对应find()
$count = Task::where('active', 1)->count();
$max = ask::where('active', 1)->max('price');
         $task=new Task;
         $task->name='ok';
         $task->save();

返回创建的对象

$task = Task::create(['name' => 'jin']);//前提在model里 protected $fillable = ['name'];
 Task::firstOrCreate(['id'=>52,'name'=>'jin']);
 Task::firstOrNew(['id'=>53,'name'=>'jin'])->save(s);
//model里
public function scopeBigId($query,$id)
{
        return $query->where('id', '>', $id);
}
//调用
$a=Task::bigId(20)->orderBy('name')->get();

return $this->belongsToMany('App\Role', 'user_roles', 'user_id', 'role_id');


  ```
class User extends Model{
  /**
   * 用户角色
   */
  public function roles()
  {
      return $this->belongsToMany('App\Role');
  }
。。。
}
class Role extends Model{
  /**
   * 角色用户
   */
  public function users()
  {
      return $this->belongsToMany('App\User');
  }
}
  ```
>访问中间表属性`pivot`

    ```
$user = App\User::find(1);
foreach ($user->roles as $role) {
  echo $role->pivot->created_at;
}
  ```
- 访问器 修改器
> 访问器会修改访问的属性值($task->name),但不会修改attribute,修改器会
public function getNameAttribute($value)
{
    return '经过访问器:' . $value;
}
public function setIdAttribute($value)
{
    $this->attributes['id'].=$value;
}
----

## Middleware
-  ### 1.1新建
`php artisan make:middleware OldMiddleware`

请求之前 

<?php
namespace App\Http\Middleware;
use Closure;
class BeforeMiddleware
{
public function handle($request, Closure $next)
{
// 执行动作

    return $next($request);
}

}

 请求之后

<?php
namespace App\Http\Middleware;
use Closure;
class AfterMiddleware
{
public function handle($request, Closure $next)
{
$response = $next($request);

    // 执行动作

    return $response;
}

}

注册

// 在 App\Http\Kernel 里中
protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,];

Route::get('admin/profile', ['middleware' => 'auth', function () {
//
}]);

验证认证用户是否拥有指定的角色,可以创建一个RoleMiddleware
来接收角色名作为额外参数
public function handle($request, Closure $next, $role)
{
    if (! $request->user()->hasRole($role)) {
        // Redirect...
    }

    return $next($request);
}

Route::put('post/{id}', ['middleware' => 'role:editor', function ($id) {
//
}]);

在控制器中使用
public function __construct()
{
    $this->middleware('auth');

    $this->middleware('log', ['only' => ['fooAction', 'barAction']]);

    $this->middleware('subscribed', ['except' => ['fooAction', 'barAction']]);
}
上一篇下一篇

猜你喜欢

热点阅读