2019年5月30日木曜日

laravel middleware

Controllers also allow you to register middleware using a Closure. This provides a convenient way to define a middleware for a single controller without defining an entire middleware class:

$this->middleware(function ($request, $next) {
    // ...

    return $next($request);
});

resource controller

php artisan make:controller PhotoController --resource
Route::resource('photos', 'PhotoController');
Route::resources([
    'photos' => 'PhotoController',
    'posts' => 'PostController'
]);

Partial Resource Routes

Route::resource('photos', 'PhotoController')->only([
    'index', 'show'
]);

Route::resource('photos', 'PhotoController')->except([
    'create', 'store', 'update', 'destroy'
]);

Route::apiResources([
    'photos' => 'PhotoController',
    'posts' => 'PostController'
]);

If you need to add additional routes to a resource controller beyond the default set of resource routes, you should define those routes before your call to Route::resource

Route::get('photos/popular', 'PhotoController@method');
Route::resource('photos', 'PhotoController');

You may even restrict the middleware to only certain methods on the controller class:

public function __construct()
    {
        $this->middleware('auth');

        $this->middleware('log')->only('index');

        $this->middleware('subscribed')->except('store');
    }

// 一覧
GET /projects (index)

// 新規ページ
GET /projects/create (create)

// 保存
POST /projects (store)

// show project
GET /projects/{id}

// 編集ページ
GET /projects/{id}/edit (edit)

// 更新
PATCH /projects/{id} (update)

// 削除
DELETE /projects/{id} (destroy)

Dependency Injection & Controllers

Injectionの場所は2つある
1)Constructor Injection
class UserController extends Controller
{
    /**
     * The user repository instance.
     */
    protected $users;

    /**
     * Create a new controller instance.
     *
     * @param  UserRepository  $users
     * @return void
     */
    public function __construct(UserRepository $users)
    {
        $this->users = $users;
    }
}

2)Method Injection
class UserController extends Controller
{
    /**
     * Store a new user.
     *
     * @param  Request  $request
     * @return Response
     */
    public function store(Request $request)
    {
        $name = $request->name;

        //
    }
}

laravel Authorization

Gates provide a simple, Closure based approach to authorization while policies, like controllers, group their logic around a particular model or resource.
Gates are most applicable to actions which are not related to any model or resource, such as viewing an administrator dashboard. In contrast, policies should be used when you wish to authorize an action for a particular model or resource.

Gates are Closures that determine if a user is authorized to perform a given action and are typically defined in the App\Providers\AuthServiceProvider class using the Gate facade. Gates always receive a user instance as their first argument, and may optionally receive additional arguments such as a relevant Eloquent model:

public function boot()
{
    $this->registerPolicies();

    Gate::define('update-post', function ($user, $post) {
        return $user->id == $post->user_id;
    });

    Gate::define('update-post', 'App\Policies\PostPolicy@update');
}

Authorizing Actions

To authorize an action using gates, you should use the allows or denies methods. Note that you are not required to pass the currently authenticated user to these methods. Laravel will automatically take care of passing the user into the gate Closure:

if (Gate::allows('update-post', $post)) {
    // The current user can update the post...
}

if (Gate::denies('update-post', $post)) {
    // The current user can't update the post...
}

If you would like to determine if a particular user is authorized to perform an action, you may use the forUser method on the Gate facade:

if (Gate::forUser($user)->allows('update-post', $post)) {
    // The user can update the post...
}

if (Gate::forUser($user)->denies('update-post', $post)) {
    // The user can't update the post...
}

You may use the before method to define a callback that is run before all other authorization checks:

boot function中で下記追加

Gate::before(function ($user, $ability) {
    if ($user->isSuperAdmin()) {
        return true;
    }
});
If the before callback returns a non-null result that result will be considered the result of the check.

You may use the after method to define a callback to be executed after all other authorization checks:

Gate::after(function ($user, $ability, $result, $arguments) {
    if ($user->isSuperAdmin()) {
        return true;
    }
});

Generating Policies

php artisan make:policy PostPolicy
php artisan make:policy PostPolicy --model=Post

Registering Policies

class AuthServiceProvider extends ServiceProvider
{
    /**
     * The policy mappings for the application.
     *
     * @var array
     */
    protected $policies = [
        Post::class => PostPolicy::class,
    ];

Policy Auto-Discovery
Laravel can auto-discover policies as long as the model and policy follow standard Laravel naming conventions.

Any policies that are explicitly mapped in your AuthServiceProvider will take precedence over any potential auto-discovered policies.

class PostPolicy
{
    /**
     * Determine if the given post can be updated by the user.
     *
     * @param  \App\User  $user
     * @param  \App\Post  $post
     * @return bool
     */
    public function update(User $user, Post $post)
    {
        return $user->id === $post->user_id;
    }
}

Guest Users

By default, all gates and policies automatically return false if the incoming HTTP request was not initiated by an authenticated user. However, you may allow these authorization checks to pass through to your gates and policies by declaring an "optional" type-hint or supplying a  null default value for the user argument definition:
public function update(?User $user, Post $post)
    {
        return $user->id === $post->user_id;
    }

For certain users, you may wish to authorize all actions within a given policy. To accomplish this, define a before method on the policy. The before method will be executed before any other methods on the policy

public function before($user, $ability)
{
    if ($user->isSuperAdmin()) {
        return true;
    }
}
If you would like to deny all authorizations for a user you should return false from the before method. If null is returned, the authorization will fall through to the policy method.
The before method of a policy class will not be called if the class doesn't contain a method with a name matching the name of the ability being checked.

Authorizing Actions Using Policies

if ($user->can('update', $post)) {
    // Via The User Model
}

use App\Post;
if ($user->can('create', Post::class)) {
    // Executes the "create" method on the relevant policy...
}

Laravel includes a middleware that can authorize actions before the incoming request even reaches your routes or controllers.
Route::put('/post/{post}', function (Post $post) {
    // The current user may update the post...
})->middleware('can:update,post');
we're passing the can middleware two arguments. The first is the name of the action we wish to authorize and the second is the route parameter we wish to pass to the policy method.
Actions That Don't Require Model Instance
Route::post('/post', function () {
    // The current user may create posts...
})->middleware('can:create,App\Post');

Via Controller Helpers

public function update(Request $request, Post $post)
    {
        $this->authorize('update', $post);

        // The current user can update the blog post...
    }

Via Blade Templates

@can('update', $post)
    <!-- The Current User Can Update The Post -->
@elsecan('create', App\Post::class)
    <!-- The Current User Can Create New Post -->
@endcan

@cannot('update', $post)
    <!-- The Current User Can't Update The Post -->
@elsecannot('create', App\Post::class)
    <!-- The Current User Can't Create New Post -->
@endcannot

2019年5月29日水曜日

laravelのdata_setでarrayの値をobjに代入

validationが通らない場合、row objの値を入力値にしたい

 $row = new \App\Model();
 if ($request->old()) {
        foreach (old() as $key => $value) {
            data_set($row, $key, $value);
        }
    }

2019年5月28日火曜日

laravel session

Retrieving Data

There are two primary ways of working with session data in Laravel: the global session helper and via a Request instance.
$value = $request->session()->get('key');
$value = $request->session()->get('key', 'default');
$value = $request->session()->get('key', function () {
    return 'default';
});

// Retrieve a piece of data from the session...
    $value = session('key');

    // Specifying a default value...
    $value = session('key', 'default');

$data = $request->session()->all();

The has method returns true if the item is present and is not null
if ($request->session()->has('users')) {
    //
}

The exists method returns true if the item is present, even if its value is null:
if ($request->session()->exists('users')) {
    //
}

Storing Data

// Via a request instance...
$request->session()->put('key', 'value');

// Via the global helper...
session(['key' => 'value']);

Pushing To Array Session Values

The push method may be used to push a new value onto a session value that is an array. For example, if the user.teams key contains an array of team names, you may push a new value onto the array like so:

$request->session()->push('user.teams', 'developers');

Retrieving & Deleting An Item

The pull method will retrieve and delete an item from the session in a single statement:

$value = $request->session()->pull('key', 'default');

Flash Data

store items in the session only for the next request
$request->session()->flash('status', 'Task was successful!');

If you need to keep your flash data around for several requests, you may use the reflash method, which will keep all of the flash data for an additional request. If you only need to keep specific flash data, you may use the keep method:

$request->session()->reflash();

$request->session()->keep(['username', 'email']);

Deleting Data

The forget method will remove a piece of data from the session. If you would like to remove all data from the session, you may use the flush method:

// Forget a single key...
$request->session()->forget('key');

// Forget multiple keys...
$request->session()->forget(['key1', 'key2']);

$request->session()->flush();

2019年5月27日月曜日

laravel paginate

$users = DB::table('users')->paginate(15);
$users = App\User::paginate(15);

"Simple Pagination"

If you only need to display simple "Next" and "Previous" links in your pagination view, you may use the simplePaginate method to perform a more efficient query.
$users = DB::table('users')->simplePaginate(15);
$users = User::where('votes', '>', 100)->simplePaginate(15);

Displaying Pagination Results

<div class="container">
    @foreach ($users as $user)
        {{ $user->name }}
    @endforeach
</div>

{{ $users->links() }} // ?page=N

Adjusting The Pagination Link Window
You may control how many additional links are displayed on each side of the paginator's URL "window". By default, three links are displayed on each side of the primary paginator links. However, you may control this number using the onEachSide method:

{{ $users->onEachSide(5)->links() }}

Customizing The Pagination View

{{ $paginator->links('view.name') }}

// Passing data to the view...
{{ $paginator->links('view.name', ['foo' => 'bar']) }}

laravel Authentication

ログイン後のredirect先
LoginController, RegisterController, ResetPasswordController, and  VerificationController:

protected $redirectTo = '/';

modify the RedirectIfAuthenticated middleware's handle method to use your new URI when redirecting the user.

you may access the authenticated user via the Auth facade:

// Get the currently authenticated user...
$user = Auth::user(); // auth()->user()

// Get the currently authenticated user's ID...
$id = Auth::id(); // auth()->id()

public function update(Request $request)
    {
        // $request->user() returns an instance of the authenticated user...
    }

if (Auth::check()) { // auth()->check()  auth()->guest()
    // The user is logged in...
}


Route::get('profile', function () {
    // Only authenticated users may enter...
})->middleware('auth');

If you are using controllers, you may call the middleware method from the controller's constructor instead of attaching it in the route definition directly:

public function __construct()
{
    $this->middleware('auth');
}

Manually Authenticating Users

public function authenticate(Request $request)
    {
        $credentials = $request->only('email', 'password');

        if (Auth::attempt($credentials)) {
            // Authentication passed...
            return redirect()->intended('dashboard');
        }
    }
The intended method on the redirector will redirect the user to the URL they were attempting to access before being intercepted by the authentication middleware. A fallback URI may be given to this method in case the intended destination is not available.

Auth::logout();

Remembering Users

Your users table must include the string remember_token column, which will be used to store the "remember me" token.

if (Auth::attempt(['email' => $email, 'password' => $password], $remember)) {
    // The user is being remembered...
}
If you are "remembering" users, you may use the viaRemember method to determine if the user was authenticated using the "remember me" cookie:

if (Auth::viaRemember()) {
    //
}

2019年5月20日月曜日

laravel soft delete

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Flight extends Model
{
    use SoftDeletes;
}


Schema::table('flights', function (Blueprint $table) {
    $table->softDeletes();
});

when you call the delete method on the model, the deleted_at column will be set to the current date and time. And, when querying a model that uses soft deletes, the soft deleted models will automatically be excluded from all query results.

To determine if a given model instance has been soft deleted, use the trashed method:

if ($flight->trashed()) {
    //
}

you may force soft deleted models to appear in a result set using the  withTrashed method on the query:

$flights = App\Flight::withTrashed()
                ->where('account_id', 1)
                ->get();

onlyTrashed method will retrieve only soft deleted models:
$flights = App\Flight::onlyTrashed()
                ->where('airline_id', 1)
                ->get();

Sometimes you may wish to "un-delete" a soft deleted model. To restore a soft deleted model into an active state, use the restore method on a model instance:

$flight->restore();
You may also use the restore method in a query to quickly restore multiple models. Again, like other "mass" operations, this will not fire any model events for the models that are restored:

App\Flight::withTrashed()
        ->where('airline_id', 1)
        ->restore();

Sometimes you may need to truly remove a model from your database. To permanently remove a soft deleted model from the database, use the forceDelete method:

// Force deleting a single model instance...
$flight->forceDelete();

laravel db migrate

// roll back
php artisan migrate:rollback
php artisan migrate:rollback --step=5  // rollback the last five migrations
php artisan migrate:reset  // roll back all of your application's migrations

roll back all of your migrations and then execute the  migrate command. This command effectively re-creates your entire database:
php artisan migrate:refresh
php artisan migrate:refresh --step=5

//drop all tables and re-run all migrations
php artisan migrate:fresh

laravel Query Builder

Query BuilderのSQL確認方法
$builder->toSql()
$builder->getBindings()

The Laravel query builder uses PDO parameter binding to protect your application against SQL injection attacks. There is no need to clean strings being passed as bindings.

extract a single value

$email = DB::table('users')->where('name', 'John')->value('email');

Retrieving A List Of Column Values

$roles = DB::table('roles')->pluck('title', 'name');
foreach ($roles as $name => $title) {
    echo $title;
}

aggregate methods

->count()/max('price')/min('price')/avg('price')/sum('price')

->exists()/doesntExist()

Select Clause

$users = DB::table('users')->select('name', 'email as user_email')->get();
->distinct()
add a column to its existing select clause
$query = DB::table('users')->select('name');
$users = $query->addSelect('age')->get();

Raw Expressions

$users = DB::table('users')
                     ->select(DB::raw('count(*) as user_count, status'))
                     ->where('status', '<>', 1)
                     ->groupBy('status')
                     ->get();

selectRaw/whereRaw / orWhereRaw/havingRaw / orHavingRaw/orderByRaw

Where Clauses

$users = DB::table('users')->where([
    ['status', '=', '1'],
    ['subscribed', '<>', '1'],
])->get();

->where('votes', '>', 100)
->orWhere('name', 'John')

whereNotXxxx/orWhereXxxx
->whereBetween('votes', [1, 100])

->whereIn('id', [1, 2, 3])

->whereNull('updated_at')

->whereDate('created_at', '2016-12-31')
->whereMonth('created_at', '12')
->whereDay('created_at', '31')
->whereYear('created_at', '2016')
->whereTime('created_at', '=', '11:20:45')

The whereColumn method may be used to verify that two columns are equal:
->whereColumn('first_name', 'last_name')
You may also pass a comparison operator to the method:
->whereColumn('updated_at', '>', 'created_at')

Parameter Grouping

DB::table('users')
            ->where('name', '=', 'John')
            ->where(function ($query) {
                $query->where('votes', '>', 100)
                      ->orWhere('title', '=', 'Admin');
            })
            ->get();
The example above will produce the following SQL:
select * from users where name = 'John' and (votes > 100 or title = 'Admin')

order by

->orderBy('name', 'desc')
->latest ()/ oldest()
By default, result will be ordered by the created_at column.

groupBy/having/skip/take/offset/limit

Conditional Clauses

The when method only executes the given Closure when the first parameter is true. If the first parameter is false, the Closure will not be executed.
$role = $request->input('role');
$users = DB::table('users')
                ->when($role, function ($query, $role) {
                    return $query->where('role_id', $role);
                })
                ->get();

Insert

DB::table('users')->insert([
    ['email' => 'taylor@example.com', 'votes' => 0],
    ['email' => 'dayle@example.com', 'votes' => 0]
]);
$id = DB::table('users')->insertGetId(
    ['email' => 'john@example.com', 'votes' => 0]
);

Update

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

The updateOrInsert method will first attempt to locate a matching database record using the first argument's column and value pairs. If the record exists, it will be updated with the values in the second argument. If the record can not be found, a new record will be inserted with the merged attributes of both arguments:

DB::table('users')
    ->updateOrInsert(
        ['email' => 'john@example.com', 'name' => 'John'],
        ['votes' => '2']
    );

Delete

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

Join

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

laravel table schema mapping

Auto-incrementing UNSIGNED BIGINT (primary key)  => $table->bigIncrements('id');
DATE  => $table->date('created_at');
DATETIME  => $table->dateTime('created_at');
VARCHAR  => $table->string('name', 100);
TEXT  => $table->text('description');
TIMESTAMP  => $table->timestamp('added_on');

Allows (by default) NULL values to be inserted into the column
->nullable($value = true)

Specify a "default" value for the column
->default($value)

Add a comment
->comment('my comment')

Set INTEGER columns as auto-increment (primary key)
->autoIncrement()

2019年5月19日日曜日

laravel relation

class User extends Model
{
    /**
     * Get the phone record associated with the user.
     */
    public function phone()
    {
        return $this->hasOne('App\Phone');
    }
}

one to one
hasOne/belongsTo

one to many
hasMany/belongsTo

many to many
belongsToMany/belongsToMany
$shop = Shop::find($shop_id);
$shop->products()->attach($product_id);
$shop->products()->detach($product_id);

we may access the intermediate table using the pivot attribute on the models:
foreach ($user->roles as $role) {
    echo $role->pivot->created_at;
}
Notice that each Role model we retrieve is automatically assigned a pivot attribute. This attribute contains a model representing the intermediate table, and may be used like any other Eloquent model.

Filtering Relationships Via Intermediate Table Columns
return $this->belongsToMany('App\Role')->wherePivot('approved', 1);
return $this->belongsToMany('App\Role')->wherePivotIn('priority', [1, 2]);

Inserting & Updating Related Models

setting the post_id attribute on the Comment
$comment = new App\Comment(['message' => 'A new comment.']);
$post = App\Post::find(1);
$post->comments()->save($comment);
$post->comments()->saveMany([
    new App\Comment(['message' => 'A new comment.']),
    new App\Comment(['message' => 'Another comment.']),
]);

$post = App\Post::find(1);
$post->comments[0]->message = 'Message';
$post->comments[0]->author->name = 'Author Name';
$post->push();

the difference between save and create is that save accepts a full Eloquent model instance while create accepts a plain PHP array:
$post = App\Post::find(1);
$comment = $post->comments()->create([
    'message' => 'A new comment.',
]);
$post->comments()->createMany([
    [
        'message' => 'A new comment.',
    ],
    [
        'message' => 'Another new comment.',
    ],
]);

Belongs To Relationships

When updating a belongsTo relationship, you may use the associate method. This method will set the foreign key on the child model:

$account = App\Account::find(10);
$user->account()->associate($account);
$user->save();

$user->account()->dissociate();
$user->save();

Many To Many Relationships

$user = App\User::find(1);
$user->roles()->attach($roleId);

When attaching a relationship to a model, you may also pass an array of additional data to be inserted into the intermediate table:
$user->roles()->attach($roleId, ['expires' => $expires]);

$user->roles()->detach($roleId);
// Detach all roles from the user...
$user->roles()->detach();

When working with a many-to-many relationship, the save method accepts an array of additional intermediate table attributes as its second argument:
App\User::find(1)->roles()->save($role, ['expires' => $expires]);

updateExistingPivot method. This method accepts the pivot record foreign key and an array of attributes to update:

$user = App\User::find(1);
$user->roles()->updateExistingPivot($roleId, $attributes);

2019年5月17日金曜日

lavavel blade

@extends
@section
@show
@yield
@parent
@component
@slot
@inculde, @includeIf, @includeWhen, @includeFirst

Hello, @{{ name }}.
In this example, the @ symbol will be removed by Blade; however, {{ name }} expression will remain untouched by the Blade engine, allowing it to instead be rendered by your JavaScript framework.

@verbatim
    <div class="container">
        Hello, {{ name }}.
    </div>
@endverbatim

@if, @elseif, @else

@unless

@isset, @empty

@auth, @guest

@switch, @case, @break, @default

@for, @foreach, @forelse/@empty, @while
@continue, @break

@php

@csrf, @method

@error directive may be used to quickly check if validation error messages exist for a given attribute. Within an @error directive, you may echo the $message variable to display the error message:

<input id="title" type="text" class="@error('title') is-invalid @enderror">

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

You may combine loops and includes into one line with Blade's @each directive:
@each('view.name', $jobs, 'job')
@each('view.name', $jobs, 'job', 'view.empty')

@inject directive may be used to retrieve a service from the Laravel service container.
@inject('metrics', 'App\Services\MetricsService')
<div>
    Monthly Revenue: {{ $metrics->monthlyRevenue() }}.
</div>

laravel Routing

The routes/web.php file defines routes that are for your web interface. These routes are assigned the web middleware group, which provides features like session state and CSRF protection. The routes in routes/api.php are stateless and are assigned the api middleware group.

register a route that responds to multiple HTTP verbs. You may do so using the match method. Or, you may even register a route that responds to all HTTP verbs using the any method:

Route::match(['get', 'post'], '/', function () {
    //
});

Route::any('/', function () {
    //
});

POST, PUT, or DELETE routes that are defined in the web routes file should include a CSRF token field.

Redirect Routes

If you are defining a route that redirects to another URI, you may use the Route::redirect method. This method provides a convenient shortcut so that you do not have to define a full route or controller for performing a simple redirect:

Route::redirect('/here', '/there');

By default, Route::redirect returns a 302 status code. You may customize the status code using the optional third parameter:
Route::redirect('/here', '/there', 301);

You may use the Route::permanentRedirect method to return a 301 status code:
Route::permanentRedirect('/here', '/there');

View Routes

this method provides a simple shortcut so that you do not have to define a full route or controller.
Route::view('/welcome', 'welcome');
Route::view('/welcome', 'welcome', ['name' => 'Taylor']);

Route Parameters

Route::get('user/{id}', function ($id) {
    return 'User '.$id;
});
Route::get('posts/{post}/comments/{comment}', function ($postId, $commentId) {
    //
});
not contain a - character. Instead of using the - character, use an underscore (_).

Optional Parameters

Make sure to give the route's corresponding variable a default value:

Route::get('user/{name?}', function ($name = null) {
    return $name;
});

Route::get('user/{name?}', function ($name = 'John') {
    return $name;
});

Regular Expression Constraints

Route::get('user/{name}', function ($name) {
    //
})->where('name', '[A-Za-z]+');

Route::get('user/{id}', function ($id) {
    //
})->where('id', '[0-9]+');

Route::get('user/{id}/{name}', function ($id, $name) {
    //
})->where(['id' => '[0-9]+', 'name' => '[a-z]+']);

Encoded Forward Slashes

The Laravel routing component allows all characters except /. You must explicitly allow / to be part of your placeholder using a where condition regular expression:

Route::get('search/{search}', function ($search) {
    return $search;
})->where('search', '.*');

Encoded forward slashes are only supported within the last route segment.

Named Routes

Route::get('user/profile', 'UserProfileController@show')->name('profile');

// Generating URLs...
$url = route('profile');

// Generating Redirects...
return redirect()->route('profile');

Route Groups

Route::middleware(['first', 'second'])->group(function () {
    Route::get('/', function () {
        // Uses first & second Middleware
    });

    Route::get('user/profile', function () {
        // Uses first & second Middleware
    });
});

Route::namespace('Admin')->group(function () {
    // Controllers Within The "App\Http\Controllers\Admin" Namespace
});
by default, the RouteServiceProvider includes your route files within a namespace group, allowing you to register controller routes without specifying the full  App\Http\Controllers namespace prefix. So, you only need to specify the portion of the namespace that comes after the base App\Http\Controllers namespace.

Route::domain('{account}.myapp.com')->group(function () {
    Route::get('user/{id}', function ($account, $id) {
        //
    });
});
In order to ensure your sub-domain routes are reachable, you should register sub-domain routes before registering root domain routes. This will prevent root domain routes from overwriting sub-domain routes which have the same URI path.

Route::prefix('admin')->group(function () {
    Route::get('users', function () {
        // Matches The "/admin/users" URL
    });
});
Route::name('admin.')->group(function () {
    Route::get('users', function () {
        // Route assigned name "admin.users"...
    })->name('users');
});

Fallback Routes

define a route that will be executed when no other route matches the incoming request.
Route::fallback(function () {
    //
});
The fallback route should always be the last route registered by your application.

Accessing The Current Route

$route = Route::current();
$name = Route::currentRouteName();
$action = Route::currentRouteAction();

laravel eloquent

Each database table has a corresponding "Model" which is used to interact with that table.
php artisan make:model Flight --migration
php artisan make:model Flight -m

protected $table = 'my_flights';
protected $primaryKey = 'flight_id';
public $incrementing = false;
protected $keyType = 'string';

By default, Eloquent expects created_at and updated_at columns to exist on your tables.
public $timestamps = false;

If you need to customize the format of your timestamps, set the $dateFormat property on your model. This property determines how date attributes are stored in the database
protected $dateFormat = 'U';

const CREATED_AT = 'creation_date';
const UPDATED_AT = 'last_update';

Default Attribute Values

protected $attributes = [
        'delayed' => false,
    ];

App\Flight::all();

$flights = App\Flight::find([1, 2, 3]);

$flights = App\Flight::where('active', 1)
               ->orderBy('name', 'desc')
               ->take(10)
               ->get();

$flight = App\Flight::where('active', 1)->first();

Not Found Exceptions

$model = App\Flight::findOrFail(1);
$model = App\Flight::where('legs', '>', 100)->firstOrFail();
If the exception is not caught, a 404 HTTP response is automatically sent back to the user. It is not necessary to write explicit checks to return 404 responses when using these methods

Retrieving Aggregates

You may also use the count, sum, max, and other aggregate methods provided by the query builder. These methods return the appropriate scalar value instead of a full model instance:

$count = App\Flight::where('active', 1)->count();
$max = App\Flight::where('active', 1)->max('price');

Inserts

$flight = new Flight;
$flight->name = $request->name;
$flight->save();

Updates

$flight = App\Flight::find(1);
$flight->name = 'New Flight Name';
$flight->save();

App\Flight::where('active', 1)
          ->where('destination', 'San Diego')
          ->update(['delayed' => 1]);

Mass Assignment

You may also use the create method to save a new model in a single line. before doing so, you will need to specify either a fillable or guarded attribute on the model, as all Eloquent models protect against mass-assignment by default.

protected $fillable = ['name'];
$flight = App\Flight::create(['name' => 'Flight 10']);
If you already have a model instance, you may use the fill method to populate it with an array of attributes:
$flight->fill(['name' => 'Flight 22']);

protected $guarded = ['price'];
protected $guarded = [];
you should use either  $fillable or $guarded - not both. 

Deleting Models

$flight = App\Flight::find(1);
$flight->delete();

App\Flight::destroy(1);
App\Flight::destroy(1, 2, 3);
App\Flight::destroy([1, 2, 3]);
App\Flight::destroy(collect([1, 2, 3]));

$deletedRows = App\Flight::where('active', 0)->delete();

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') }}">