LoginSignup
0
1

More than 3 years have passed since last update.

Laravel基本知識&操作

Last updated at Posted at 2019-12-06

久しぶりにLaravel(5系)を触っているので、忘れないように基本操作メモ

MVCフォルダ構成

  • コントローラ
    • app/Http/Controllers
  • モデル
    • app
  • テンプレート
    • resources/views

バッチ

格納場所

app\Console\Commands

コマンド

  • コマンド名をバッチファイル内の $signature に定義しておく
  • app\Console\Kernel.php$commands に追加
  • バッチ実行
    • php artisan コマンド名

バリデーション

参考

コントローラ/モデル側

$data = $_POST['id']; // チェックしたいデータ
$rule = ['id' => required|integer]; // チェックしたいキーとそのルール
$messages =[ // ルールに引っかかった際のエラーメッセージ
    id.required => 'IDが入力されていません',
    id.integer => 'IDが数字ではありません'
];

Validator::make($data, $rules, $messages)->validate();

テンプレート側

$errors に格納される

@if ($errors->any())
    @foreach ($errors->all() as $error)
        <div>{{$error}}</div>
    @endforeach
@endif

DB操作

参考

SELECT

基本

$result = DB::table('テーブルA')
// 取得するフィールド
    ->select(
        'フィールド1',
        'フィールド2',
    )
// 結合
    // シンプルな結合
    ->join('テーブルB', 'フィールドB1', '=', 'フィールドA1')
    // 複数条件の場合
    ->join('テーブルC', function($join) {
        $join->on('フィールドC1', '=', 'フィールドA1');
        $join->on('フィールドC2', '=', 'フィールドA2');
    })
// 条件
    // シンプルな条件
    ->where('フィールド1', '>', 1)
    // バインドしない場合
    ->whereRaw('フィールド3 IS NULL')
    // 入れ子
    ->where(function($sql) {
    $sql->where('フィールドA5', '!=', 9) 
        ->orWhere('フィールドA6', '!=', 9);
    }
// 並べ替え
    ->orderBy('フィールド1', 'ASC');
// 取得
    // 全件
    ->get();
    // 1行
//  ->first();

foreach ($result as $val) {
    echo $val->フィールド名;
}

特定のフィールド取得

$field = DB::table('テーブルA')
    ->where('id', '=', '1')
    ->value('フィールド名');

取得した値のemptyチェック

if ($result->isEmpty()) {
}

INSERT

基本

DB::table('テーブルA')
    ->insert([
        'フィールド1' => 1,
        'フィールド2' => 'テスト'
    ]);

UPDATE

基本

DB::table('テーブルA')
    ->where('フィールド1', '1')
    ->update(['フィールド2' => 'test']);

ログ系

ログ出力

出力先

  • storage/logs/
Log::info('1111');
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1