2019年5月17日金曜日

laravel validation

use the validate method provided by the Illuminate\Http\Request object. If the validation rules pass, your code will keep executing normally; however, if validation fails, an exception will be thrown and the proper error response will automatically be sent back to the user. In the case of a traditional HTTP request, a redirect response will be generated, while a JSON response will be sent for AJAX requests.

$validatedData = $request->validate([
        'title' => 'required|unique:posts|max:255',
        'body' => 'required',
    ]);

Stopping On First Validation Failure

Sometimes you may wish to stop running validation rules on an attribute after the first validation failure. To do so, assign the bail rule to the attribute:
$request->validate([
    'title' => 'bail|required|unique:posts|max:255',
    'body' => 'required',
]);

If your HTTP request contains "nested" parameters, you may specify them in your validation rules using "dot" syntax:
$request->validate([
    'title' => 'required|unique:posts|max:255',
    'author.name' => 'required',
    'author.description' => 'required',
]);

Displaying The Validation Errors

@if ($errors->any())
    <div class="alert alert-danger">
        <ul>
            @foreach ($errors->all() as $error)
                <li>{{ $error }}</li>
            @endforeach
        </ul>
    </div>
@endif

You may also use the @error Blade directive(form 5.8.13)to quickly check if validation error messages exist for a given attribute. 
<input id="title" type="text" class="@error('title') is-invalid @enderror">

@error('title')
    <div class="alert alert-danger">{{ $message }}</div>
@enderror

Working With Error Messages

$errors = $validator->errors();
echo $errors->first('email');

retrieve an array of all the messages for a given field, use the get method:

foreach ($errors->get('email') as $message) {
    //
}

foreach ($errors->all() as $message) {
    //
}

if ($errors->has('email')) {
    //
}

Manually Creating Validators

If you do not want to use the validate method on the request, you may create a validator instance manually using the Validator facade.
$validator = Validator::make($request->all(), [
            'title' => 'required|unique:posts|max:255',
            'body' => 'required',
        ]);

if ($validator->fails()) {
            return redirect('post/create')
                        ->withErrors($validator)
                        ->withInput();
        }

If you would like to create a validator instance manually but still take advantage of the automatic redirection offered by the requests's validate method, you may call the validate method on an existing validator instance. If validation fails, the user will automatically be redirected or, in the case of an AJAX request, a JSON response will be returned:

Validator::make($request->all(), [
    'title' => 'required|unique:posts|max:255',
    'body' => 'required',
])->validate();

Custom Error Messages

$messages = [
    'email.required' => 'We need to know your e-mail address!',
];
$validator = Validator::make($input, $rules, $messages);

Validating When Present

email field will only be validated if it is present in the $data array.
$v = Validator::make($data, [
    'email' => 'sometimes|required|email',
]);

$v = Validator::make($data, [
    'email' => 'required|email',
    'games' => 'required|numeric',
]);
$v->sometimes('reason', 'required|max:500', function ($input) {
    return $input->games >= 100;
});
The first argument passed to the sometimes method is the name of the field we are conditionally validating. The second argument is the rules we want to add. If the Closure passed as the third argument returns true, the rules will be added.

A Note On Optional Fields

By default, Laravel includes the TrimStrings and ConvertEmptyStringsToNull middleware in your application's global middleware stack. These middleware are listed in the stack by the  App\Http\Kernel class. Because of this, you will often need to mark your "optional" request fields as nullable if you do not want the validator to consider null values as invalid.

laravel request

// http://domain.com/foo/bar, the path method will return foo/bar
$request->path();

// verify that the incoming request path matches a given pattern
if ($request->is('admin/*')) {
    //
}

// Without Query String...
$url = $request->url();

// With Query String...
$url = $request->fullUrl();

// method
if ($request->isMethod('post')) {
    //
}

By default, Laravel includes the TrimStrings and ConvertEmptyStringsToNull middleware in your application's global middleware stack. These middleware will automatically trim all incoming string fields on the request, as well as convert any empty string fields to null.

$input = $request->all(); // may same with $request->input();
// default value 'Sally'
$name = $request->input('name', 'Sally');

When working with forms that contain array inputs, use "dot" notation to access the arrays:
$name = $request->input('products.0.name');
$names = $request->input('products.*.name');

While the input method retrieves values from entire request payload (including the query string), the query method will only retrieve values from the query string:

$name = $request->query('name');
or  $name = $request->name; // dynamic properties

When using dynamic properties, Laravel will first look for the parameter's value in the request payload. If it is not present, Laravel will search for the field in the route parameters.

if ($request->has('name')) {
    //
}

If you would like to determine if a value is present on the request and is not empty, you may use the filled method:
if ($request->filled('name')) {
    //
}

Retrieving Old Input

$username = $request->old('username');
<input type="text" name="username" value="{{ old('username') }}">

2019年4月1日月曜日

python basic

x = 3
y = 4
z = 5

x, y, z = 3, 4, 5

my_height = 58

x = int(4.7)   # x is now an integer 4
y = float(4)   # y is now a float of 4.0
>>> print(type(x))
int
>>> print(type(y))
float

String

>>> first_word = 'Hello'
>>> second_word = 'There'
>>> print(first_word + second_word)

HelloThere

>>> print(first_word + ' ' + second_word)

Hello There

>>> print(first_word * 5)

HelloHelloHelloHelloHello

>>> print(len(first_word))

5

>>> first_word[0]

H

>>> first_word[1]

e

print("Mohammed has {} balloons".format(27))
# Mohammed has 27 balloons

new_str = "The cow jumped over the moon."
new_str.split()
# ['The', 'cow', 'jumped', 'over', 'the', 'moon.']

new_str.split(' ', 3)
# maxsplit is set to 3, ['The', 'cow', 'jumped', 'over the moon.']

List

list_of_random_things = [1, 3.4, 'a string', True]
>>> list_of_random_things[-1]
True
>>> list_of_random_things[-2]
a string

When using slicing, it is important to remember that the lower index is inclusive and the upper index is exclusive.

>>> 'isa' in 'this is a string'
False
>>> 5 not in [1, 2, 3, 4, 6]
True

name = "-".join(["García", "O'Kelly"])
print(name)
# García-O'Kelly

letters = ['a', 'b', 'c', 'd']
letters.append('z')
print(letters)
# ['a', 'b', 'c', 'd', 'z']

tuple

location = (13.4125, 103.866667)
print("Latitude:", location[0])
print("Longitude:", location[1])

dimensions = 52, 40, 100
length, width, height = dimensions
print("The dimensions are {} x {} x {}".format(length, width, height))

set

A set is a data type for mutable unordered collections of unique elements.
numbers = [1, 2, 6, 3, 1, 1, 6]
unique_nums = set(numbers)
print(unique_nums)
# {1, 2, 3, 6}

fruit = {"apple", "banana", "orange", "grapefruit"}  # define a set
print("watermelon" in fruit)  # check for element
fruit.add("watermelon")  # add an element
print(fruit.pop())  # remove a random element

dictionary

elements = {"hydrogen": 1, "helium": 2, "carbon": 6}
print(elements["helium"])  # print the value mapped to "helium"
elements["lithium"] = 3  # insert "lithium" with a value of 3 into the dictionary

We can check whether a value is in a dictionary the same way we check whether a value is in a list or set with the in keyword. Dicts have a related method that's also useful, get. get looks up values in a dictionary, but unlike square brackets, get returns None (or a default value of your choice) if the key isn't found.

print("carbon" in elements)
print(elements.get("dilithium"))

Zip

a = [1, 2, 3, 4, 5]
b = [10, 11, 12, 13, 14]
list(zip(a, b)) #[(1, 10), (2, 11), (3, 12), (4, 13), (5, 14)]



2019年2月14日木曜日

php error表示

ini_set('display_errors', "On");
ini_set('error_reporting', E_ALL);

2019年1月24日木曜日

php DateTime diff

DateTime比較するには、diffを使います。

$datetime = new  DateTime("20190101");
$today_dt = new DateTime();
// $datetimeと現在の日付を比較する、$datetime - $today_dt の感じ
$interval = $datetime->diff($today_dt);

どっちが後ろ(大きい)かは、$interval['invert']が1の場合、$datetimeのほうが大きい。

2019年1月19日土曜日

symfony Timestampable

1)StofDoctrineExtensionsBundleをインストール
composer require stof/doctrine-extensions-bundle

2)Activating Timestampable
config
stof_doctrine_extensions:
    default_locale: ja_JP
    orm:
        default:
            timestampable: true

3)Entityに以下追加
<?php

namespace App\Entity;

use Doctrine\ORM\Mapping as ORM;
use Gedmo\Timestampable\Traits\TimestampableEntity;

class User implements UserInterface
{
    use TimestampableEntity;
......

4)bin/console make:migration

5)bin/console doctrine:migrations:migrate

2018年12月14日金曜日

css grid vs flex

Grid is Container-Based, Flexbox is Content-Based
This is an important difference. It shows that the flexbox layout is calculated after its content is loaded whereas the grid layout is calculated regardless of the content inside it. So, if possible, avoid using flexbox to build the overall layout of your website.

Grid Has a “Gap” Property, Flexbox Doesn’t

Flexbox is One Dimensional, Grid is Two Dimensional
Flexbox is best for arranging elements in either a single row, or a single column. Grid is best for arranging elements in multiple rows and columns.

Flexbox Wraps vs Grid Wraps
when a flex-item is wrapped and pushed in a new row, the Flexbox layout algorithm treats it as a part of a different flex-container. Hence the pushed item loses its context.

参考:https://www.webdesignerdepot.com/2018/09/grid-vs-flexbox-which-should-you-choose/