userの論理削除

論理削除用のカラムを追加します
[vagrant@localhost test]$ php artisan make:migration add_column_softDeletes_users_table –table=users
Created Migration: 2019_08_20_001651_add_column_softDeletes_users_table

migrationsにも追加されていますね。

laravel migrate:refreshとmigrate:resetの違い

migrate:refresh と migrate:reset 何が違うんや?
migrationを再実行の場合はrefreshでいいのかな?

[vagrant@localhost test]$ php artisan migrate:refresh
Nothing to rollback.

In Connection.php line 647:
                                                                                                                                   
  SQLSTATE[42S01]: Base table or view already exists: 1050 Table 'users' already exists (SQL: create table `users` (`id` int unsi  
  gned not null auto_increment primary key, `name` varchar(255) not null, `email` varchar(255) not null, `password` varchar(255)   
  not null, `remember_token` varchar(100) null, `created_at` timestamp null, `updated_at` timestamp null) default character set u  
  tf8 collate utf8_unicode_ci)                                                                                                     
                                                                                                                                   

In Connection.php line 449:
                                                                                         
  SQLSTATE[42S01]: Base table or view already exists: 1050 Table 'users' already exists

already existってエラーが出てる。resetでやってみると、

[vagrant@localhost test]$ php artisan migrate:reset
Nothing to rollback.                                                                                      

mysql> use test;
Database changed
mysql> show tables;
+—————-+
| Tables_in_test |
+—————-+
| migrations |
| users |
+—————-+
2 rows in set (0.00 sec)

あれ、うまくいってない??
mysql> drop table migrations;
Query OK, 0 rows affected (0.01 sec)

mysql> drop table users;
Query OK, 0 rows affected (0.00 sec)

[vagrant@localhost test]$ php artisan migrate
Migration table created successfully.
Migrating: 2014_10_12_000000_create_users_table
Migrated: 2014_10_12_000000_create_users_table
Migrating: 2014_10_12_100000_create_password_resets_table
Migrated: 2014_10_12_100000_create_password_resets_table

mysql> show tables;
+—————–+
| Tables_in_test |
+—————–+
| migrations |
| password_resets |
| users |
+—————–+
3 rows in set (0.00 sec)

いまいち理解できてないです。

公式では、、
migrate:refresh Reset and re-run all migrations
migrate:reset Rollback all database migrations
resethはrollbackで、refreshはre-runですな。

register controller

ユーザー情報はここで編集する

protected function validator(array $data)
    {
        return Validator::make($data, [
            'name' => ['required', 'string', 'max:255'],
            'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
            'password' => ['required', 'string', 'min:8', 'confirmed'],
        ]);
    }

    /**
     * Create a new user instance after a valid registration.
     *
     * @param  array  $data
     * @return \App\User
     */
    protected function create(array $data)
    {
        return User::create([
            'name' => $data['name'],
            'email' => $data['email'],
            'password' => Hash::make($data['password']),
        ]);
    }

Laravelの認証をカスタマイズする

/app/Http/Controllers/Auth/LoginController.php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;

class LoginController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Login Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles authenticating users for the application and
    | redirecting them to your home screen. The controller uses a trait
    | to conveniently provide its functionality to your applications.
    |
    */

    use AuthenticatesUsers;

    /**
     * Where to redirect users after login.
     *
     * @var string
     */
    protected $redirectTo = '/home';

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest')->except('logout');
    }

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

usernameメソッドを変更する

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

ほう、そういうことか。

laravelでlogin後のリダイレクト先を変更

App/Http/Middleware/RedirectAuthenticated.phpを編集します。

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\Auth;

class RedirectIfAuthenticated
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @param  string|null  $guard
     * @return mixed
     */
    public function handle($request, Closure $next, $guard = null)
    {
        if (Auth::guard($guard)->check()) {
            // return redirect('/home');
            return redirect('/top');
        }

        return $next($request);
    }
}

TopController.phpをつくります。

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class TopController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth');
    }

    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Contracts\Support\Renderable
     */
    public function index()
    {
        return view('top');
    }
}

上手くいくようになりました。

herokuで実行されない時

app logsを見ます。
[vagrant@localhost heroku]$ heroku logs -t
2019-08-17T06:29:07.714312+00:00 app[web.1]: [17-Aug-2019 06:29:07 UTC] PHP Fatal error: Uncaught Error: Call to undefined function mb_convert_encoding() in /app/backlog.php:23

ん? 
mb_convert_encoding()?

とりあえずcomposer.jsonをupdateして、herokuにpush

{
	"require" : {
		"ext-mbstring": "*",
		"google/apiclient": "^2.0"
	}
}

きたーーーーーーーーーーー 結局、GCP→Heroku→Google Spread sheetもOKでした。

backlog APIで値を取得して、スプレッドシートに表示

$message[0] = array('チケット','タイトル','ステータス','担当者','開始日','期限日');
$i= 1;
foreach($json as $value){
    $message[$i][0] = $value["issueKey"];
    $message[$i][1] = $value["summary"];
    $message[$i][2] = $value["status"]["name"];
    $message[$i][3] = $value["assignee"]["name"];
    $message[$i][4] = date("Y/m/d", strtotime($value["startDate"]));
    $message[$i][5] = date("Y/m/d", strtotime($value["dueDate"]));
    $i++;
}

で、この値をGoogle Spread sheetに渡す

あれ、いけますね♪

じゃあ、これをHerokuにgit pushしてscheduler登録すればいいんじゃない♪

phpでspreadsheetに書き込む その2

続きをやっていきましょう。

// google/applient:"^2.0"
require __DIR__. '/vendor/autoload.php';

// GCP Sheet APIの認証情報
$keyFile = __DIR__. "/credentials.json";

// アカウント認証情報インスタンスを作成
$client = new Google_Client();
$client->setAuthConfig($keyFile);

// 任意
$client->setApplicationName("Sheet API Test");

//サービス権限のスコープ
$scopes = [Google_Service_Sheets::SPREADSHEETS];
$client->setScopes($scopes);

// シート情報を操作するインスタンスを生成
$sheet = new Google_Service_Sheets($client);

// 保存データ
$values = [
	["Sheet API Append TEST", "登録できていますか?"]
];

// データ操作領域を設定
$body = new Google_Service_Sheets_ValueRange([
	'values' => $values,
]);

$response = $sheet->spreadsheets_values->append(
	"*******************",
	'シート1',
	$body,
	["valueInputOption" => 'USER_ENTERED']
);

// 書き込んだ処理結果を確認
var_export($response->getUpdates());

はああああああああああ? なにこれえええええええええええ

とりあえず、二行で送りたい。それと1行目を見出しにしたい。

phpでspreadsheetに書き込む その1

まずcomposerを入れます
[vagrant@localhost local]$ curl -sS https://getcomposer.org/installer | php
All settings correct for using Composer
Downloading…

Composer (version 1.9.0) successfully installed to: /home/vagrant/local/composer.phar
Use it: php composer.phar

[vagrant@localhost local]$ ls
backlog.php composer.phar heroku ipa.php

composerでgoogle api clientを落とします。
[vagrant@localhost local]$ php composer.phar require google/apiclient:”^2.0″
./composer.json has been created
Loading composer repositories with package information
Updating dependencies (including require-dev)
Package operations: 13 installs, 0 updates, 0 removals
– Installing ralouphie/getallheaders (3.0.3): Downloading (100%)
– Installing psr/http-message (1.0.1): Loading from cache
– Installing guzzlehttp/psr7 (1.6.1): Downloading (100%)
– Installing guzzlehttp/promises (v1.3.1): Downloading (100%)
– Installing guzzlehttp/guzzle (6.3.3): Downloading (100%)
– Installing phpseclib/phpseclib (2.0.21): Downloading (100%)
– Installing psr/log (1.1.0): Loading from cache
– Installing monolog/monolog (1.24.0): Downloading (100%)
– Installing firebase/php-jwt (v5.0.0): Downloading (100%)
– Installing google/apiclient-services (v0.109): Downloading (100%)
– Installing psr/cache (1.0.1): Loading from cache
– Installing google/auth (v1.5.1): Downloading (100%)
– Installing google/apiclient (v2.2.3): Downloading (100%)
guzzlehttp/psr7 suggests installing zendframework/zend-httphandlerrunner (Emit PSR-7 responses)
phpseclib/phpseclib suggests installing ext-libsodium (SSH2/SFTP can make use of some algorithms provided by the libsodium-php extension.)
phpseclib/phpseclib suggests installing ext-mcrypt (Install the Mcrypt extension in order to speed up a few other cryptographic operations.)
phpseclib/phpseclib suggests installing ext-gmp (Install the GMP (GNU Multiple Precision) extension in order to speed up arbitrary precision integer arithmetic operations.)
monolog/monolog suggests installing graylog2/gelf-php (Allow sending log messages to a GrayLog2 server)
monolog/monolog suggests installing sentry/sentry (Allow sending log messages to a Sentry server)
monolog/monolog suggests installing doctrine/couchdb (Allow sending log messages to a CouchDB server)
monolog/monolog suggests installing ruflin/elastica (Allow sending log messages to an Elastic Search server)
monolog/monolog suggests installing php-amqplib/php-amqplib (Allow sending log messages to an AMQP server using php-amqplib)
monolog/monolog suggests installing ext-amqp (Allow sending log messages to an AMQP server (1.0+ required))
monolog/monolog suggests installing ext-mongo (Allow sending log messages to a MongoDB server)
monolog/monolog suggests installing mongodb/mongodb (Allow sending log messages to a MongoDB server via PHP Driver)
monolog/monolog suggests installing aws/aws-sdk-php (Allow sending log messages to AWS services like DynamoDB)
monolog/monolog suggests installing rollbar/rollbar (Allow sending log messages to Rollbar)
monolog/monolog suggests installing php-console/php-console (Allow sending log messages to Google Chrome)
google/apiclient suggests installing cache/filesystem-adapter (For caching certs and tokens (using Google_Client::setCache))
Writing lock file
Generating autoload files

gasとは

Google Apps Script(GAS)

google spread sheetとの連携に使用する

google spread sheetのidは”/d/” と “/edit” の間にある乱数字のこと
https://docs.google.com/spreadsheets/d/***/edit#gid=0

続いてGoogle sheet apiを有効化

スプレッドシートをgoogle platform userと共有

それでは、プログラムを書いていきましょう♪