Laravelの馴染みのない知識ポイント
PHPパラメータのデフォルト値
<code><span><span><?php</span><span><span>function</span><span>makecoffee</span><span>(<span>$type</span> = <span>"cappuccino"</span>)</span> {</span><span>return</span><span>"Making a cup of $type.\n"</span>; } <span>echo</span> makecoffee(); <span>echo</span> makecoffee(<span>null</span>); <span>echo</span> makecoffee(<span>"espresso"</span>); <span>?></span></span></code>
Output
<code>Making <span>a</span> cup <span>of</span> cappuccino. Making <span>a</span> cup <span>of</span> . Making <span>a</span> cup <span>of</span> espresso.</code>
Model Binding(モデルバインディング)
RouteServiceProviderではブートメソッドにモデルバインディングを実装
<code><span>public</span> function boot(Router <span>$router</span>) { <span>parent</span><span>::boot</span>(<span>$router</span>); <span>$router</span><span>-></span>model(<span>'users'</span>, <span>'App\User'</span>); <span>$router</span><span>-></span>model(<span>'goods'</span>, <span>'App\Good'</span>); <span>$router</span><span>-></span>model(<span>'categories'</span>, <span>'App\Category'</span>); <span>$router</span><span>-></span>model(<span>'tryClothes'</span>, <span>'App\TryRecord'</span>); <span>$router</span><span>-></span>model(<span>'carts'</span>, <span>'App\Cart'</span>); <span>$router</span><span>-></span>model(<span>'orders'</span>, <span>'App\Order'</span>); <span>$router</span><span>-></span>model(<span>'orderItems'</span>, <span>'App\OrderItem'</span>); <span>//</span> }</code>
Form Request(フォームリクエスト)
<code><span>php</span><span>artisan</span><span>make</span><span>:request</span><span>CreateArticleRequest</span></code>
<code><span>public</span><span><span>function</span><span>authorize</span><span>()</span> {</span><span>return</span><span>true</span>; }</code>rree
<code><span>public</span><span><span>function</span><span>rules</span><span>()</span> {</span><span>return</span> [ <span>'title'</span> => <span>'required|min:3'</span>, <span>'body'</span> => <span>'required'</span>, <span>'published_at'</span> => <span>'required|date'</span>, <span>// 也可以使用数组</span><span>//'published_at' => ['required', 'date'],</span> ]; }</code>
<code><span>public</span><span><span>function</span><span>store</span><span>(Request <span>$request</span>)</span>{</span><span>$this</span>->validate(<span>$request</span>, [<span>'title'</span> => <span>'required|min:3'</span>, <span>'body'</span> =><span>'required'</span>, <span>'published_at'</span> => <span>'required|date'</span>]); Article::create(<span>$request</span>->all()); <span>return</span> redirect(<span>'articles'</span>); }</code>
<code>Article<span>::create</span>(<span>$request</span><span>-></span><span>all</span>());</code>