5
10

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Laravel備忘録(いつも探して時間の無駄なことまとめ)

Last updated at Posted at 2017-09-13

はじめに

毎回忘れて、色々なページを漁って時間の無駄なので、
チョットでもハマったことは残しとく自分用のメモ。

プロダクトコード

Eloquentモデルのカスタム属性

DBと強力に紐づくEloquentモデル。
DBにないカラムを追加したかったりすることがままある。
そんなときは、以下のフィールドに追加したい属性を定義して、getXXXAttributeメソッドを追加すればOK。

MyModel.php
protected $appends = ['add_filed',];

public function getAddFiledAttribute()
{
    return '返したい何か';
}

ClassのPHPDocに@propertyで書いといてあげれば別のクラスからの呼び出しも楽になる

配列のバリデーション

連想配列については割としっかり書いてあってすぐに見つかるけど、
そうじゃないヤツどうやるんだっけ?っていつも探しにいき、説明不足で読んでもスルーして更に探しに行くという無駄があるので書いておく。

MyFormValidation.php
public function rules()
{
    return [
        'arrays.*'=> 'integer|in:1,9',
    ];
}

これで、連想配列に関係なく全部中身をチェックしてくれる。(もう少ししっかり書いといて欲しさがある)

Resource ControllerのFormバリデーションで任意のHTTPステータスコードを返す

エラーになると前ページにリダイレクトしようとするので、302が返るヤツ。
Resource Controllerだと400が返したい。
ソース読まないと判らなかったから残しておく。

MyResourceFormValidation.php
public function response(array $errors)
{
    return new JsonResponse($errors, 400);
}

Illuminate\Foundation\Http\FormRequest#responseをオーバーライドすればOK。
バリデートに失敗したときにしか呼ばれないから、上記をコピペすれば大概上手くいく。

BladeからGETメソッドにパラメータを追加する

ドキュメントにはroutingのRESTFullっぽい記述のことしか書いてないけど、以下をすれば普通に「?」で繋がる。

route.php
Route::get('/index/{id}', ['as' => 'index', 'uses' => 'HogeController@index']);
view.blade.php
{!! Form::open(['route' => ['index', 1, 'my_arg' => 'get_param'], 'method' => 'get']) !!}

上記のように書くと、こうなる(一応)

<form action='http://localhost/index/1?my_arg=get_param' method='GET'>

</form>

テストコード

HTTPリクエストの投げ方

リクエスト投げる部分はコピペしてるから新しく始めたときにすぐ忘れる。

MyTest.php
$response = $this->call('GET', '/index');

ヘッダーに要素を追加する

引数名が判りづらくて、いつもStack Overflowを徘徊させられる。

MyTest.php
$server = $this->transformHeadersToServerVars(['authorization' => 'hoge']);
$response = $this->call('GET', '/index', [], [], [], $server);

最後に

増えればここに追加します。

5
10
2

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
5
10

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?