Laravel ティップス

Artisanコンソール

$php artisan tinker

tinkerコマンドによるLaravelアプリケーション内のコード動作確認

https://laravel.com/docs/7.x/artisan

ex) tinkerコマンドによるリレーションテーブルを含めたモデルインスタンスの確認

PHP Lambdas and Closures

正規関数内で一時的に関数処理する際に使用される無名(匿名)関数(関数名を定義しない)。
LambdasClosuresの詳細については下記参照のこと。

Lambdas使用例

 // Anonymous function  
 // assigned to variable  
 $greeting = function () {  
 return "Hello world";  
 }

// Call function  
 echo $greeting();  
 // Returns "Hello world" 

Closuresの使用例

// Set a multiplier  
 $multiplier = 3;

// Create a list of numbers  
 $numbers = array(1,2,3,4);

// Use array_walk to iterate  
 // through the list and multiply  
 array_walk($numbers, function($number) use($multiplier){  
 echo $number * $multiplier;  
 });

Closureの内部で変数を変更しても、その内容は反映されないため、変更する場合は ’&’ を前置すること。

// Set counter  
$i = 0;  
// Increase counter within the scope  
// of the function  
$closure = function () use ($i){ $i++; };  
// Run the function  
$closure();  
// The global count hasn’t changed  
echo $i; // Returns 0

// Reset count  
$i = 0;  
// Increase counter within the scope  
// of the function but pass it as a reference  
$closure = function () use (&$i){ $i++; };  
// Run the function  
$closure();  
// The global count has increased  
echo $i; // Returns 1 

Laravelでの使用例

URL /user/philip にアクセスすると ”Hello phillp”を返します。

Route::get(‘user/(:any)’, function($name){  
return "Hello " . $name;  
});  

Auth::guard(Laravelファサード )

https://laracasts.com/discuss/channels/laravel/what-does-authguard-mean

https://laravel.com/docs/7.x/authentication

Guard Customization

You may also customize the “guard” that is used to authenticate and register users. To get started, define a guard method on your LoginController , RegisterController , and ResetPasswordController . The method should return a guard instance:

use Illuminate\Support\Facades\Auth;

protected function guard()
{
    return Auth::guard('guard-name');
}

Retrieving The Authenticated User

You may access the authenticated user via the Auth facade:

use Illuminate\Support\Facades\Auth;

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

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

Alternatively, once a user is authenticated, you may access the authenticated user via an Illuminate\Http\Request instance. Remember, type-hinted classes will automatically be injected into your controller methods:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class ProfileController extends Controller
{
    /**
     * Update the user's profile.
     *
     * @param  Request  $request
     * @return Response
     */
    public function update(Request $request)
    {
        // $request->user() returns an instance of the authenticated user...
    }
}

Determining If The Current User Is Authenticated

To determine if the user is already logged into your application, you may use the check method on the Auth facade, which will return true if the user is authenticated:

use Illuminate\Support\Facades\Auth;

if (Auth::check()) {
    // The user is logged in...
}

Namespaces Laravel API

API, Namespaceについて以下参照
https://laravel.com/api/7.x/index.html

Illuminate\Contracts\Auth\Guard

interface Guard (View source)
https://laravel.com/api/7.x/Illuminate/Contracts/Auth/Guard.html

Illuminate/Support/Facades/Auth

class Auth extends Facade (View source)
https://laravel.com/api/7.x/Illuminate/Support/Facades/Auth.html

Authentication

Authenticating

Now that you have routes and views setup for the included authentication controllers, you are ready to register and authenticate new users for your application! You may access your application in a browser since the authentication controllers already contain the logic (via their traits) to authenticate existing users and store new users in the database.

Path Customization

When a user is successfully authenticated, they will be redirected to the /home URI. You can customize the post-authentication redirect path using the HOME constant defined in your RouteServiceProvider :

public const HOME = '/home';

If you need more robust customization of the response returned when a user is authenticated, Laravel provides an empty authenticated(Request $request, $user) method that may be overwritten if desired:

/**
 * The user has been authenticated.
 *
 * @param  \Illuminate\Http\Request  $request
 * @param  mixed  $user
 * @return mixed
 */
protected function authenticated(Request $request, $user)
{
    return response([
        //
    ]);
}

Username Customization

By default, Laravel uses the email field for authentication. If you would like to customize this, you may define a username method on your LoginController :

public function username()
{
    return 'username';
}

Guard Customization

You may also customize the “guard” that is used to authenticate and register users. To get started, define a guard method on your LoginController , RegisterController , and ResetPasswordController . The method should return a guard instance:

use Illuminate\Support\Facades\Auth;

protected function guard()
{
    return Auth::guard('guard-name');
}

Other Authentication Methods

Authenticate A User Instance

If you need to log an existing user instance into your application, you may call the login method with the user instance. The given object must be an implementation of the Illuminate\Contracts\Auth\Authenticatable contract. The App\User model included with Laravel already implements this interface:

Auth::login($user);

// Login and "remember" the given user...
Auth::login($user, true);

You may specify the guard instance you would like to use:

Auth::guard('admin')->login($user);

Retrieving The Authenticated User

You may access the authenticated user via the Auth facade:

use Illuminate\Support\Facades\Auth;

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

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

Alternatively, once a user is authenticated, you may access the authenticated user via an Illuminate\Http\Request instance. Remember, type-hinted classes will automatically be injected into your controller methods:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class ProfileController extends Controller
{
    /**
     * Update the user's profile.
     *
     * @param  Request  $request
     * @return Response
     */
    public function update(Request $request)
    {
        // $request->user() returns an instance of the authenticated user...
    }
}

Determining If The Current User Is Authenticated

To determine if the user is already logged into your application, you may use the check method on the Auth facade, which will return true if the user is authenticated:

use Illuminate\Support\Facades\Auth;

if (Auth::check()) {
    // The user is logged in...
}

HTTP Requests

Accessing The Request

To obtain an instance of the current HTTP request via dependency injection, you should type-hint the Illuminate\Http\Request class on your controller method. The incoming request instance will automatically be injected by the service container:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

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

        //
    }
}

Retrieving Input

Retrieving All Input Data

You may also retrieve all of the input data as an array using the all method:

$input = $request->all();

Retrieving An Input Value

Using a few simple methods, you may access all of the user input from your Illuminate\Http\Request instance without worrying about which HTTP verb was used for the request. Regardless of the HTTP verb, the input method may be used to retrieve user input:

$name = $request->input('name');

You may pass a default value as the second argument to the input method. This value will be returned if the requested input value is not present on the request:

$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');

You may call the input method without any arguments in order to retrieve all of the input values as an associative array:

$input = $request->input();

Illuminate/Foundation/Auth/ResetsPasswords

https://laravel.com/api/5.8/Illuminate/Foundation/Auth/ResetsPasswords.html

Updates

The save method may also be used to update models that already exist in the database. To update a model, you should retrieve it, set any attributes you wish to update, and then call the save method. Again, the updated_at timestamp will automatically be updated, so there is no need to manually set its value:

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

$flight->name = 'New Flight Name';

$flight->save();

URLs

action()

The action function generates a URL for the given controller action. You do not need to pass the full namespace of the controller. Instead, pass the controller class name relative to the App\Http\Controllers namespace:

$url = action('HomeController@index');

$url = action([HomeController::class, 'index']);

If the method accepts route parameters, you may pass them as the second argument to the method:

$url = action('UserController@profile', ['id' => 1]);

asset()

The asset function generates a URL for an asset using the current scheme of the request (HTTP or HTTPS):

$url = asset('img/photo.jpg');

You can configure the asset URL host by setting the ASSET_URL variable in your .env file. This can be useful if you host your assets on an external service like Amazon S3:

// ASSET_URL=http://example.com/assets

$url = asset('img/photo.jpg'); // http://example.com/assets/img/photo.jpg

Add in your layout file:

Just add these latest jQuery & JavaScript CDN scripts in your layout file and your dropdown menu will start working.

<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>

JS

Many of our components require the use of JavaScript to function. Specifically, they require jQuery, Popper.js, and our own JavaScript plugins. Place the following <script> s near the end of your pages, right before the closing </body> tag, to enable them. jQuery must come first, then Popper.js, and then our JavaScript plugins.

We use jQuery’s slim build, but the full version is also supported.

<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js" integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI" crossorigin="anonymous"></script>

Writing CSS

After installing the laravel/ui Composer package and generating the frontend scaffolding, Laravel’s package.json file will include the bootstrap package to help you get started prototyping your application’s frontend using Bootstrap. However, feel free to add or remove packages from the package.json file as needed for your own application. You are not required to use the Bootstrap framework to build your Laravel application - it is provided as a good starting point for those who choose to use it.

Before compiling your CSS, install your project’s frontend dependencies using the Node package manager (NPM):

npm install

Once the dependencies have been installed using npm install , you can compile your SASS files to plain CSS using Laravel Mix. The npm run dev command will process the instructions in your webpack.mix.js file. Typically, your compiled CSS will be placed in the public/css directory:

npm run dev

The webpack.mix.js file included with Laravel’s frontend scaffolding will compile the resources/sass/app.scss SASS file. This app.scss file imports a file of SASS variables and loads Bootstrap, which provides a good starting point for most applications. Feel free to customize the app.scss file however you wish or even use an entirely different pre-processor by configuring Laravel Mix.

Writing JavaScript

All of the JavaScript dependencies required by your application can be found in the package.json file in the project’s root directory. This file is similar to a composer.json file except it specifies JavaScript dependencies instead of PHP dependencies. You can install these dependencies using the Node package manager (NPM):

npm install

By default, the Laravel package.json file includes a few packages such as lodash and axios to help you get started building your JavaScript application. Feel free to add or remove from the package.json file as needed for your own application.

Once the packages are installed, you can use the npm run dev command to compile your assets. Webpack is a module bundler for modern JavaScript applications. When you run the npm run dev command, Webpack will execute the instructions in your webpack.mix.js file:

npm run dev

By default, the Laravel webpack.mix.js file compiles your SASS and the resources/js/app.js file. Within the app.js file you may register your Vue components or, if you prefer a different framework, configure your own JavaScript application. Your compiled JavaScript will typically be placed in the public/js directory.

The app.js file will load the resources/js/bootstrap.js file which bootstraps and configures Vue, Axios, jQuery, and all other JavaScript dependencies. If you have additional JavaScript dependencies to configure, you may do so in this file.