laravel筆記

composer

composer基本使用

  1. 在指定文件夾下創(chuàng)建composer.json,填寫相關(guān)的配置(注意:文件中所有的引號都是雙引號,json字符串的格式不能有誤)
{
  "require":{
        "endroid/qrcode":"1.7.3"
}
}
  1. 在命令行下執(zhí)行composer install(執(zhí)行命令的時候,一定要將命令行的目錄 切換到創(chuàng)建composer.json文件下)
  2. 創(chuàng)建php腳本,并且要引入vendor文件夾下的autoload.php
  3. 查看文檔,使用工具包

更新composer.json文件

  1. 修改文件
{
    "require:"{
        "endroid/qrcode":"1.7.3",
        "gregwar/captcha":"v1.1.1"

    }

}

2.更新
composer update

軟件更新

composer self-update

laravel

運行環(huán)境

  1. php版本>=5.5.9
  2. Mcrypt PHP擴展 (php的加密擴展,提供多種加密算法)
  3. openssl擴展 (對傳輸?shù)臄?shù)據(jù)進行加密)
  4. mbstring擴展(提供了針對多字節(jié)字符串字節(jié)編碼)
  5. Tokenlzer PHP擴展(php代碼解析)

安裝

1.composer安裝
composer create-project laravel/laravel your-project-name --prefer-dist "5.*.*"

  1. 直接復制一份安裝

路由

  • 是將信息從源地址傳遞到目的地的角色*
  • 文件位置:app/Http/routs.php或者app/routes/web.php(版本不同位置有差別)
  • 基本路由:
  1. Route::get('/',function(){ return 'hello world!' });
  2. Route::post('/insert',function(){});
  3. Route::put(......);
  4. Route::delete('.....');
  • laravel框架中所有的模板文件都是存放在resources/views中,模板文件都是以.blade.php結(jié)尾

  • 在每一個post表單中需要添加隱藏域來完成請求{{csrf_field()}}

  • 加參數(shù)的路由

//限制參數(shù)的類型
Route::get('/goods/{id}',function($id){
  echo ‘商品詳情頁當前id為’.$id;
})->where('id','\d+');

//多個參數(shù)
Route::get('/{type}-{id}',function($type,$id){
  echo '當年的類型為'.$type.',當前的id為'.$id;
});

//別名
Route::get('/Admin/User/index',[
'as'=>'ulist',
'uses'=>function(){
  echo "這里是后臺用戶顯示";
  echo route('ulist'); //route函數(shù)是通過路由來快速創(chuàng)建完整url的
}  
]);

//路由組
Route::group([],function(){

});

  • 404頁面設(shè)置
  1. abort(404,'沒有找到相關(guān)頁面!');
  2. 設(shè)置模板——>resources/views/errors/404.blade.php

中間件

  1. 創(chuàng)建(默認不直接生效)
    php artisan make:middleware LoginMiddleware
    生成的中間件都在 app/Http/Middleware

  2. 編寫代碼

  3. 注冊
    ——全局注冊
    在Kernel.php——>$middleware成員屬性中添加
    ——路由注冊
    在Kernel.php——>$routeMiddleware成員屬性中添加

  4. 使用

Route::get('/middle',['middleware'=>'test',function(){
 return 'hello world!';
}]);

Route::get('/aa',function(){
 return "aa";
})->middleware('test');

控制器

app/Http/Controllers

  1. 創(chuàng)建控制器
    php artisan make:controller UserController
    php artisan make:controller UserController --plain(無多余方法的)
  2. 路由以及訪問
//當前用戶請求服務(wù)器上的/controller路徑時,會執(zhí)行UserController控制器文件中的show方法
Route::get('/controller','UserController@show');

//使用別名
Route::get('admin/user/delete/{id}',[
  'as'=>'udelete',
  'uses'=>'UserController@delete'
]);

Route::get('admin/user/index',[
  'middleware'=>'login',
  'uses'=> 'UserController@index'
]);
  1. 隱式控制器
//如果是goods開頭的路徑,都交給GoodsController處理
Route::controller('goods','GoodsController')

//在GoodsController中添加add方法,前面加請求方式(get/post)
//GET  /goods/add  HTTP/1.1
public function getAdd(){
}

//插入的請求方式為post
//POST /goods/insert HTTP/1.1
public function postInsert(){}


4.restful控制器

Route::resource('photos', 'PhotoController');

方法 路徑 動作 路由名稱
GET /photos index photos.index
GET /photos/create create photos.create
POST /photos store photos.store
GET /photos/{photo} show photos.show
GET /photos/{photo}/edit edit photos.edit
PUT/PATCH /photos/{photo} update photos.update
DELETE /photos/{photo} destroy photos.destroy

請求

1.基本信息獲取

$request->method(); #獲取請求方法
$request->IsMethod('post');#檢驗方法
$request->path();#請求路徑
$request->url();#獲取完整url
$request->ip();#獲取ip
$request->getPort();#獲取端口
  1. 提取請求參數(shù)
$name = $request->input('name'); #基本獲取 
$request->input('name','Sally'); #設(shè)置默認值
$request->has('name'); #檢測是否存在
$input = $request->all(); #提取所有參數(shù)

$request->only(['username','password']); #提取部分
$request->except(['credit_card']); #提取部分

$request->header('Connection');#獲取頭信息

  1. 文件操作
  $request->hasFile('photo'); #檢測是否有文件上傳
  $request->file('photo')->move('./uploads/','001.jpg');#將文件移動到指定位置
  1. cookie操作
  \Cookie::queue('name','Jack',10); #設(shè)置
  return response(' ')->withCookie('uid',10,10); #設(shè)置

\Cookie::get('name'); #讀取
$request->cookie('name'); #讀取

  1. 閃存信息
$request->flash();#將所有參數(shù)寫入閃存
$request->flashOnly('title','price');#將部分參數(shù)寫入閃存
$request->flashExcept('_token');#除去某些參數(shù)之外的參數(shù)
\Session::flash('name','jack'); #自定義閃存

響應(yīng)

return '哈哈哈'; #返回字符串
return response('')->withCookie('id',20,60); #設(shè)置cookie
return response()->json(['a'=>100,'b'=>2000]);#返回json
return response()->download('web.config');#下載文件
return redirect('/goods/add');#頁面跳轉(zhuǎn)
return response()->view('goods.add');#顯示模板
return response('')->head('name','helloworld'); #響應(yīng)頭

視圖

  view('user.add') #解析模板
  view('user.edit',['username'=>'admin']);#分配數(shù)據(jù)到模板

模板引擎blade

resources/views  #模板的默認存放位置
{{$username}} #使用變量
{{time()}}#使用函數(shù)
{{$username or 'guest'}} #設(shè)置默認值
{{!! $name !!}} #顯示html代碼
@include('header')#引入子視圖

模板繼承

      #占位符
            @yield('title')
            @section('content')
            @show

        #新模板內(nèi)容
              @extends('index')
              @section('title','new Title')

              @section('content')
                        new contents is here
              @endsection

流程控制

@if(count($records)===1)
      I have one record!
@elseif(count($records) >1)
      I have multiple records!
@else
      I don't have any records!
@endif

循環(huán)控制

  @for($i = 0;$i<10;$i++){}
  @endfor

  @foreach($users as $user)
  @endforeach

數(shù)據(jù)庫

支持的數(shù)據(jù)庫類型 Mysql ,Postgres, SQLite, SQL Server

數(shù)據(jù)庫連接配置

* 文件位置:`config/database.php`
* 結(jié)果集的返回類型 :`'fetch'=>PDO::FETCH_ASSOC`
* .env環(huán)境快速配置

數(shù)據(jù)庫的基本操作

  ```
    DB::select  #查詢
    DB::insert   #插入
    DB::update #更新
    DB::delete  #刪除
    
     DB::statement('drop table users');#一般語句
     
      #事務(wù)操作
      DB::beginTransaction
      DB::rollBack()
      DB::commit()


      DB::connection('foo')->select(....);#操作多個數(shù)據(jù)庫
  ```    
### 構(gòu)造器

  #### 插入
#單條
  DB::table('users')->insert(
      ['email'=>'xxx@qq.com','votest'=>0]
    );
  #多條
  DB::table('users')->insert([
       ['email'=>'xxx@qq.com','votest'=>0],
       ['email'=>'zzz@qq.com','votest'=>0]
 ] );  
  #獲取id插入
  $id = DB::table('users')->insertGetId(
          ['email'=>'xxx@qq.com','votes'=>0]
    );


更新

DB::table('users')->where('id',1)->update(['votes'=>1]);

刪除

DB::table('users')->where('votes','<',100)->delete();

查詢

DB::table('users')->get() #查詢所有
DB::table('users')->first() #查詢單條
DB::table('users')->value('username')#查詢單條結(jié)果中的某個字段
DB::table('users')->lists('username') #獲取一列數(shù)據(jù)

連貫操作

  DB::table()->select()->get() #設(shè)置字段
  orderBy('name','desc') #排序
  DB::table(users')->skip(10)->take(5)->get(); #分頁

#連接表
  DB::table('users')
        ->join('contacts','users.id','=','contacts.user_id')
        ->join('orders','users.id','=','orders.user_id')
        ->select('users.*','contacts.phone','orders.price')
        ->get();

條件

  DB::table('users')->where('votes','>',100)->orWhere('name','John')->get();
  DB::table('users')->whereBetween('votes',[1,100])->get();
  DB::table('users')->whereIn('id',[1,2,3])->get() ;

計算

  DB::table('users')->count() #總數(shù)
  DB::table('orders')->max('price')#最大值
  DB::table('order')->avg('price')#平均值

sql語句記錄

Event::listen('illuminate.query',function($query){var_dump($query);});
放入路由文件中

數(shù)據(jù)庫遷移

  • 創(chuàng)建類文件
    php artisan make:migration test

up 方法

  • 創(chuàng)建表
Schema::create('users',function(Blueprint $table){
  $table->increments('id')->comment('主鍵字段');
  $table->string('username')->nullable()->default('abc')->comment('用戶名');
  $table->char('password',100)->comment('密碼');
});
  • 創(chuàng)建表字段
    1.字段類型
    ```
    $table->increments('id'); #主鍵字段
    $table->string('username');#字符串字段
    $table->integer('age');#整型
    $table->float('weight'); #浮點型
    $table->text('intro'); # 文本類型
    ```        
      2. 字段修飾
       ` nullable  default   unsigned  comment  `

      3. 索引
          ```
              $table->primary('id');#主鍵
              $table->index('password');#一般索引
              $table->unique('username');#唯一索引
          ```
       4. 設(shè)置引擎
      `$table->engine = 'myisam;'`          

down方法

Schema::drop('users');#刪除表

命令

php artisan migrate
php artisan migrate:refresh

記錄表結(jié)構(gòu)的變化

  • 檢測表是否存在
    Schema::hasTable('gg')

  • 檢測表中的字段是否存在
    Schema::hasColumn('gg','pic')

  • 增加字段(如果表存在)
    ·Schema::table('users',function($table){ $table->string('email');})·;

  • 修改字段
    這里需要安裝一個包composer require doctrine/dbal
    $table->decimal('price',10,2)->change();

  • 刪除字段
    $table->dropColumn('phone');

  • 檢測 索引

  • 刪除

$table->dropPrimary
$table->dropUnique
$table->dropIndex

數(shù)據(jù)庫數(shù)據(jù)填充

套路一

  1. 創(chuàng)建注入文件(文件默認在database/seed中)php artisan make:seeder user
  2. 在文件中填寫注入代碼
  3. 運行指令 php artisan db:seed --class=user

套路二

  1. 創(chuàng)建注入文件
  2. 在文件中書寫注入代碼
  3. 在DatabaseSeeder 文件中添加代碼
  4. 運行指令 php artisan db:seed

設(shè)置自定義函數(shù)和自定義類文件

//app/library/helper.php
#在項目下的composer.json中添加信息
"autoload":{
  "classmap":[
    "database"
],
"files":[
  "app/Library/helper.php"
]
},

composer dump-auto

調(diào)試工具

debugbar安裝

composer require barryvdh/laravel-debugbar

#在config/app.php里面的providers添加

Barryvdh\Debugbar\ServiceProvider::class

chrome插件postman

模型操作

創(chuàng)建模型

php artisan make:model Order
php artisan make:model Order -m #會自動添加遷移文件

模型限定

  • 模型所對應(yīng)的默認的表名是在模型后面加s
    Order=>orders Goods=>goods
  • 主鍵字段 id
  • 時間字段 create_at update_at

屬性設(shè)置

  • 設(shè)置操作的表名
    public $table= 'userinfo';
  • 設(shè)置默認的時間字段
    public $timestamps = false;
  • 修改默認的主鍵名稱
    public $primaryKey = 'uid';

laravel 使用前端框架Bootstrap

yarn install --no-bin-links
yarn add cross-env
  • 安裝完成之后,讓我們對 Laravel 默認生成的 app.scss 文件進行編輯,刪除此文件里的所有內(nèi)容,只留下面一行,導入 Bootstrap:
    resources/assets/sass/app.scss

    @import "node_modules/bootstrap-sass/assets/stylesheets/bootstrap";

  • 將 Bootstrap 導入成功之后,我們需要使用以下命令來將 .scss 文件編譯為 .css 才能正常使用,編譯命令如下:

    npm run dev

  • 我們也可以通過下面的命令,在每次檢測到 .scss 文件發(fā)生更改時,自動將其編譯為 .css 文件:

    $ npm run watch-poll

    請保證在進行項目開發(fā)時 npm run watch-poll 一直運行著,避免出現(xiàn)前端文件更改后沒有應(yīng)用到頁面上的歧義

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容