20200721のlaravelに関する記事は16件です。

Laravel7でFontAwesomeの利用

LaravelでfontAwesomeを使う

バージョン

  • laravel: 7.20.0
  • npm: 6.4.1
  • fontawesome-free: 5.14.0

FontAwesomeの導入

$ npm install @fortawesome/fontawesome-free

Font Awesomeのscssファイルをインポートする

@import "~@fortawesome/fontawesome-free/scss/fontawesome.scss";
@import "~@fortawesome/fontawesome-free/scss/regular.scss";
@import "~@fortawesome/fontawesome-free/scss/solid.scss";
@import "~@fortawesome/fontawesome-free/scss/brands.scss";

コンパイル

$ npm run dev

下記のサイトから必要なものを検索して使用する
https://fontawesome.com/icons?d=gallery

  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

LaravelでCSSやJSを動的に生成してHTMLにリンクで読ませる

はじめに

CMSなどで、背景色や文字の色、さらにはJavascriptの変数など、サーバやデータベースに保管したパラメーターを使って、CSSやJavaScriptを使う時に、Viewがすっきりするスマートな方法を紹介します。

CSSファイルを生成しよう

データベースにマスターとして、背景やカテゴリごとのボタン色を指定できるようになっているとします。

CSSファイルをDB保存した時に書き出しますか?
いいえ、いつものHTML表示と同じようにBladeで作りたい。
やってみましょう。

まず、dbをコントローラで読み込んで、ビューに渡します。

ポイントは、レスポンスでビューとヘッダーをつなげるところです。
そして、MIMEタイプを指定する部分にあります。

普通にVIEWで渡すとうまく来ません。
リターン、レスポンスから書いていきましょう。

    /**
     * CSS
     *
     * @return
     */
    protected function css()
    {
        $MtbBackground = MtbBackground::all();
        $MtbCategory = MtbCategory::all();
        return response()
            ->view('front.component.colors',[
                'cssbackgrands'=>$MtbBackground,
                'csscategories'=>$MtbCategory
            ],200)
            ->header('Content-Type','text/css')
            ->header('Content-Disposition','inline');
    }

つづいて、VIEWファイル

<style>
@foreach($csscategories as $csscategory)
.btn.category-{{$csscategory->id}} {
background-color: {{$csscategory->color}};
}
@endforeach
@foreach($cssbackgrands as $cssbackgrand)
.bg-{{$cssbackgrand->id}} {
    background-color: {{$cssbackgrand->color}} !important;
}
@endforeach
</style>

ルーティングを設定します。
普通にファイル名のようにcolor.cssって名前を付けちゃって下さい。

Route::get( '/color.css','Frontend\HomeController@css');

HTMLにCSSをセット

<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="UTF-8">
    <link rel="stylesheet" href="{{url('color.css')}}">

これで、ルーティングに作ったCSSのURLを開いてみます。

CSSファイルがあたかもあるかのように、
狙い通りCSS出力されています。
普通の人がこのリンク先を開いたら、
単なるCSSファイルだと思いますよ。
うふふ。偽装している感じがいい。

あとは、本文中でCSSクラスをを適用していけば、うまくデザインもはまります。

データベースのマスターを変更すれば、反映もすぐです。
JSも同じようやってやれなくないでしょう。

なぜこれを作ったか

ボタンの色や文字の色、運用で追加されるデザインの色要素を、ViewのHTMLのヘッダーにロジックと共にベタ書きしてましたが。
公開されるHTMLのソースコードがダサイ。
Viewがコードが長くなって見ずらい。
CSSファイルとして読み込ませる方法、無いの?って。
JSも同じく、フッターに直でソースコードまるだし。
なーんか、いい方法無いの?

どうして思いついたか

メール機能を作る時、メール送信テンプレートをbladeで、HTMLメールとプレーンのを作ります。
メールって送信しないと、デザインが確認できない。不便すぎる。
という事で、HTMLメールにダミーデータを入れて、プレビューで確認できるように作りました。

こんどは、プレーンはどうなの?見れなくていいのか?という事で、
テキストメールもブラウザに表示すると、普通に改行されずに、表示します。

おやおや。

ブラウザにテキストを表示するには。を調べれば、レスポンスヘッダーを変えればいい事に気がつきます。

アカウント登録認証メールの例(抜粋)

        switch ($type){
            case 'html':
                return response()
                    ->view('emails.RegisterMail',[
                        'title' => $this->title,
                        'header' => $this->header,
                        'token' => 'dummy',
                        'footer' => $this->footer,
                    ],200);
            case 'text':
                return response()
                    ->view('emails.plain.PlainRegisterMail',[
                        'title' => $this->title,
                        'header' => $this->header,
                        'token' => 'dummy',
                        'footer' => $this->footer,
                    ],200)
                    ->header('Content-Type','text/plain')
                    ->header('Content-Disposition','inline');
        }

テキストメールプレビュー機能で、こんな感じでレスポンスヘッダーを付足してみますと、
テキストメールもちゃんとブラウザで確認できます。
OK〜!メール送信しなくても、メールのデザインを調整できる。

勉強になりました。ありがとうございます。

  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

Laravelで多角形の内外判定を行うアルゴリズムの実装案

ユーザの住所が配達を承る範囲内かどうかを調べる必要があったので

実装を行っていましたところ,
https://www.nttpc.co.jp/technology/number_algorithm.html
にとてもよいアルゴリズムがあったのでこれをLaravel(PHP)で使えるようにしようと言うのが今回です.

Crossing Number Algorithm

  • 調べたい範囲の多角形と,点を用意します.
  • 点から真横に線を伸ばす.
  • 多角形内に点があれば多角形の辺との交差数は奇数,外なら偶数になる

ざっとこんなイメージですがいいですかね.詳しくはサイト読んでください.
特殊ケースが4つぐらいあるので,そこは気をつけないといけません.

Laravelでの実装

多角形の準備

config\const.phpに判定したい多角形を準備します.
最初の座標と最後の座標は一緒にしてね.
下記の例だと,四角形だけど準備する点は5つです.

今回はGoogleMapAPI使うので,latとlngで区別します.latをy軸(縦方向),lngをx軸(横方向)として捉えてます.
lng,latの順のほうが良かったな.数学っぽいし.

config\const.php
    'DeliveryArea'=>[
        ["lat"=>1.0,"lng"=>0.0],
        ["lat"=>2.0,"lng"=>0.0],
        ["lat"=>2.0,"lng"=>1.0],
        ["lat"=>1.0,"lng"=>1.0],
        ["lat"=>1.0,"lng"=>0.0],
    ]

配達可能エリアとかそうそう変わらんだろってことで,constに指定.
config('const.DeliveryArea);だけで配列として使えるから便利だよね~.

ユーザの住所

これはGoogleMapAPIのGeoCodingを使います.詳しくは調べてネ.

  • 言語を指定
  • APIキーを指定(極秘事項です.気をつけてね)
  • リクエスト出して,jsonをもらってくる.
  • よしなに返す.

ここでは,arrayにして同時に返してます.受け取るときは,list関数で受け取ればいいかなと.
ああああ とか変な住所が入ってきたら,ZERO_RESULTが返ってくるらしいので,それで判定しました.

Polygon.php
    public static function geo($addr)
    {
        mb_language("Japanese"); //文字コードの設定
        mb_internal_encoding("UTF-8");

        $address = $addr;

        if (config('app.debug')) {
            //テスト環境, ローカル環境用の記述
            $myKey = "デバッグ用のキー";
        } else {
            $myKey = "本番環境用のキー";
        }

        $address = urlencode($address);

        $url = "https://maps.googleapis.com/maps/api/geocode/json?address=" . $address . "+CA&key=" . $myKey;

        $contents = file_get_contents($url);
        $jsonData = json_decode($contents, true);

        if($jsonData["status"]=="ZERO_RESULTS"){
            $lat = null;
            $lng = null;
        }else{
            $lat = $jsonData["results"][0]["geometry"]["location"]["lat"];
            $lng = $jsonData["results"][0]["geometry"]["location"]["lng"];
        }
        return array($lat, $lng);
    }

内外判定

まんまあったのをPHPの形式に直しただけです.あと,geo関数でnull返したので,それを扱うときの条件式を追加.
あと,判定の結果がどうなのかtrueとfalseで返してます.
交点の数が知りたい場合は,$cnを返せばOKでした.

Polygon.php
public static function isPointinPolygon($point,$PolygonArray){
        $cn = 0;
        if($point["lat"]==null){
            $point["lat"]=0.0;
        }
        if($point["lng"]==null){
            $point["lng"]=0.0;
        }
        for($i = 0; $i < count($PolygonArray) - 1; $i++){
            // 上向きの辺。点Pがy軸方向について、始点と終点の間にある。ただし、終点は含まない。(ルール1)
            if( (($PolygonArray[$i]["lat"] <= $point["lat"]) && ($PolygonArray[$i+1]["lat"] > $point["lat"]))
                // 下向きの辺。点Pがy軸方向について、始点と終点の間にある。ただし、始点は含まない。(ルール2)
                || (($PolygonArray[$i]["lat"] > $point["lat"]) && ($PolygonArray[$i+1]["lat"] <= $point["lat"])) ){
                // ルール1,ルール2を確認することで、ルール3も確認できている。
                // 辺は点pよりも右側にある。ただし、重ならない。(ルール4)
                // 辺が点pと同じ高さになる位置を特定し、その時のxの値と点pのxの値を比較する。
                $vt = ($point["lat"] - $PolygonArray[$i]["lat"]) / ($PolygonArray[$i+1]["lat"]- $PolygonArray[$i]["lat"]);
                if($point["lng"] < ($PolygonArray[$i]["lng"] + ($vt * ($PolygonArray[$i+1]["lng"] - $PolygonArray[$i]["lng"])))){
                    ++$cn;
                }
            }
        }
        if($cn%2 == 0){
            return false;//偶数点だと外部
        }
        else{
            return true;//奇数点だと内部
        }
    }

実際の使い方

考えられる状況は,ECサイトでのカート機能とかかと.
ユーザの住所みて,配送料に追加するとか,割引するとかかなと.

この場合は,latとlngをあとづけしたので既存ユーザのlatとlngのデータはnullになってる,けどaddrのデータはあるって人がいるのでこんなことしてるけど,普通は会員登録時とかマイページで情報編集したときにlatとlngを取る.

で,住所の文字列をgeo使ってlatとlngに変換して,ユーザ情報を保存.そのまま内外判定の関数に渡してます.

引数の1つ目はlatとlng要素の配列.
引数の2つ目は判定したいエリアの配列.

trueかfalse返すので自分の好きなように処理して,bladeにかえしてます.

CartController.php
<?php
use App\Utils\Polygon as Polygon;
// useはよしなに

class CartController extends Controller
{
    public function indexcart()
    {
            $Areaadd = 0;
            $message = "";
            if( Auth::user()->lat == null || Auth::user()->lng == null){
                list($lat,$lng) = Polygon::geo(Auth::user()->addr);
                if($lat == null || $lng == null){
                    //取得してもなお不正な場合
                    $message = "ちゃんと住所入れてくれ";
                }else{
                    User::where('id',Auth::id())->update([
                       'lat'=>$lat,
                       'lng'=>$lng
                    ]);
                }
            }

            if(Polygon::isPointinPolygon(["lat"=>Auth::user()->lat,"lng"=>Auth::user()->lng],config('const.DeliveryArea')) == false)
            {//   lat=1.5 lng=0.5とかなら範囲内
                $Areaadd += 999999999;
                $message = "届けてやるぜ";
            }else{//   lat=0.0 lng=0.0は範囲外
                $message = "すまん遠すぎる";
            }

            return view('user.cart')->with('message',$message)->with('Areaadd',$Areaadd);
    }
}

Githubにも置いてます.

https://github.com/a-msy/laravel-utils/blob/master/Polygon.php

以上です.

  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

LaradockでLaravelの環境構築

前提環境

〇Mac
〇docker-compose使用可能
〇git使用可能

手順

1)Laradockのインストール
2)Laradockの.envファイル作成
3)Dockerで開発環境起動
4)Laravelのインストール
5)ブラウザにアクセス

1)Laradockのインストール

適当なディレクトリに移動し、以下コマンドを実行する

$ mkdir my_project
$ cd my_project
$ git clone https://github.com/Laradock/laradock.git

2)Laradockの.envファイル作成

Laradockの設定ファイルの1つである.envファイルを作成する

$ cd laradock
$ cp env-example .env

エディタで.envファイルを編集する

変更前

.env
APP_CODE_PATH_HOST=../
DATA_PATH_HOST=~/.laradock/data
COMPOSE_PROJECT_NAME=laradock

変更後

.env
APP_CODE_PATH_HOST=../laravel
DATA_PATH_HOST=../data
COMPOSE_PROJECT_NAME=my_project

3)Dockerで開発環境起動

以下4つのコンテナを起動する
〇workspace
〇php-fpm
〇nginx
〇postgres

Laradockディレクトリに移動する

$ cd ~/my_project/laradock

コンテナを起動する

$ docker-compose up -d workspace php-fpm nginx postgres

コマンドを実行後、たくさんのメッセージが表示され、最後に以下メッセージが表示されればコンテナの起動に成功

Creating laravel-sns_docker-in-docker_1 ... done
Creating laravel-sns_workspace_1        ... done
Creating laravel-sns_php-fpm_1          ... done
Creating laravel-sns_nginx_1            ... done
Creating laravel-sns_porstgres_1        ... done

コンテナを停止したい場合は、以下コマンドを実行する

$ docker-compose stop

4)Laravelのインストール

my_project/laradockディレクトリで以下コマンドを実行する

$ docker-compose exec workspace composer create-project --prefer-dist laravel/laravel project_name

5)ブラウザにアクセス

Laravelのインストールが完了後、localhostにアクセスする
以下の画面が表示されれば成功
image.png

  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

【Laravel】 データベース 続き

MySQLの設定

config/database.php
'database' => env('DB_DATABASE', 'forge'),

使用するデータベース名
SQLiteではデータベースファイルの名前だが、MySQLはサーバーに用意されているデータベース名を指定。

.envの環境設定について

Laravelの環境変数を以下のように設定する。

.env
DB_CONNECTION=sqlite

DBクラスの利用

コントローラの修正

    public function index(Request $request)
    {
      $items=DB::select('select * from poeple');
      return view('hello.index',['items'=>$items]);
    }

テンプレの修正

@section('content')
<table>
  <tr>
    <th>Nme</th><th>Mail</th><th>Age</th>
  </tr>
  @foreach($items as $item)
  <tr>
    <td>{{$item->name}}</td>
    <td>{{$item->mail}}</td>
    <td>{{$item->age}}</td>
  </tr>
  @endforeach
</table>
@endsection

DB::selectの利用

$変数=DB::select(実行するSQL文);

select文を実行するものだと思えばいい
戻り値はオブジェクトをまとめた配列のためテンプレ側のforeachで表示できる。

パラメータ結合の利用

文字列とパラメータ配列を組み合わせてSQL文を作成する

    public function index(Request $request)
    {
      if(isset($request->id)){
        $param=['id'=>$request->id];
        $items=DB::select('select * from people where id=:id',$param);
      }else {
        $items=DB::select('select * from people');
      }

      return view('hello.index',['items'=>$items]);
    }

/hello?id=とアクセスすると番号のレコードが表示される。

クエリ文字列の項目名から値を取得して
SQL分の第2引数へ配列を渡している。

DB::insert

DB::insert(クエリ文,パラメータ配列);

DB::update

DB::update(クエリ文,パラメータ配列);

DB::delete

DB::delete(クエリ文,パラメータ配列);

上記を使ってCRDUが実現できる。

しかしこれはSQLクレイブンを使った実行の仕方でスマートとは言えない
次はクエリビルダをやってみる

  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

JavaScriptで設定したCookieはLaravelで単純にRequestから取れないので注意

概要

JavaScriptで設定したCookieはLaravelで単純にRequestから取れない。$request->cookie('flag')などするとnullが帰ってきてしまう。

詳細

JavaScriptで以下のように設定したCookie。

Cookie.set('flag', 'true');

LaravelでCookieの中身を見た場合。

Controller.php
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;

class IndexController extends Controller
{
    public function index(Request $request)
    {
        dd($request->cookie());
    }
}

出力は以下のようになる。

array [▼
  "flag" => null
  ~略~
]

なぜ起こるか

Laravelは自分で設定したCookieについては暗号化している。
なので仮に暗号化していなかった場合には、Cookieを復号しようとして失敗する。失敗するとnullが返る。

該当の処理は以下のところ。
Laravelバージョンはv6.9.0のコード。

image.png

対処法

MiddlewareのEncryptCookiesにおいて、暗号化されていないと期待するリストをかけるので追加する。

EncryptCookies.php
use Illuminate\Cookie\Middleware\EncryptCookies as Middleware;

class EncryptCookies extends Middleware
{
    protected $except = [
        'flag'
    ];
}

おまけ

$_COOKIE を取得すれば生のものが取れるよ、という情報もstackoverflowなどでちらほら見られます。
確かに $_COOKIE はPHPの組み込み変数なので、確かに復号の仕組みが入っていないので生のCookieを取得できますが、Laravelを使っているのであればLaravelの仕組みの上に乗ったほうが良さそうです。

参考: https://www.php.net/manual/ja/reserved.variables.cookies.php

  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

【超初心者用】Laravel用のサーバーを起動する

Apacheを使用しなくてもいい

Apacheは8000をリッスンしている。

Apacheを起動してブラウザにlocalhostを入力すると、ルートディレクトリを開くことになるので、設定しているファイルが開かれる。

自分の場合はtop.phpというファイルが開かれる。

Laravelを使うときにもサーバーをたちあげる必要あり

動画なので説明をみていると、MAMPを使っていたり、いきなりlocalhostにアクセスすることで

image.png

この画面が起動していましたが、自分はApacheを使用してサーバーを立ち上げていて、8000をlocalhostに設定していました。

なので当然上記の画面が表示されませんでした。

ポートを指定してサーバーを立ち上げる?!

ウェブ職人のためのPHPフレームワーク。というサイトにちゃんと便利なことも書いてありました。
http://laravel.jp/

image.png

https://readouble.com/laravel/4.2/ja/quick.html

$ php artisan serve --port=8080

後ろの--port=8080というのが8080をポート番号に指定するということらしい。
これにより、複数のサーバーを立てる場合はこのポート番号をかぶらないように指定すればいいみたいですね。

  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

Laravelでログを出し分ける【初級編】

通常ログとは別ファイルにログを出力する

はじめに

Laravelはデフォルトでログ出力機能が実装されていて、

HogeController.php
use Log;

public function index()
{
    Log::debug('これはデバッグ行');
}

このように記述するだけでログとして出力されます。

laravel-2020-07-21.log
[2020-07-21 00:00:00] local.DEBUG: これはデバッグ行

ログ出力を個別で設定してみる

設定ファイルはsrc/config/logging.phpになります

logging.php
    'channels' => [
        'stack' => [
            'driver' => 'stack',
            'channels' => [
                'daily',
                'hogelogs' //ここを今回は追加
            ],
            'ignore_exceptions' => false,
        ],
...
...
...
        // 指定するログチャンネル設定を記述
        'hogelogs' => [
            'driver' => 'daily',
            'path' => storage_path('logs/hogelogs.log'),
            'level' => 'error',
            'days' => 14,
        ],

初級編なので(自分が初級ですからね:-)
もっと複雑な設定も出来るでしょう。
とりあえず通常ログファイルに全部出たらエラーデバッグがやりづらい!
エラーを追うのが面倒!!!
という事で設定してみました。

実際に出力してみよう

HogeController.php
use Log;

public function index()
{
    Log::debug('これはデバッグ行');
    Log::channel('hogelogs')->error('これはhogelogsに出力されます');
}

hogelogs-2020-07-21.log
[2020-07-21 00:00:00] local.ERROR: これはhogelogsに出力されます

簡単に出し分けられるのでsqlだけやAPI、batchで出力先を変えたいなど
遭遇する場面は多いと思います。

終わりに

今回は簡単な手法での紹介になりましたが、
設定する値で変わる(どう変わるかはまだ知らない)
ので、これからも勉強ですね

皆さんも色々とログ周り触ってみて、環境にあったログ設計を試してみてください。

#参考
https://qiita.com/K-Shuuun/items/37b7cc9a95030fe79494
https://qiita.com/hrdaya/items/b01d5621937a0710ca64

  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

【超初心者用】Laravelのインストールがうまくいかなかった

comporserでlaravelをインストールしようとしたら

$ composer global require "laravel/installer"

Using version ^3.2 for laravel/installer
./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)
Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - Installation request for laravel/installer ^3.2 -> satisfiable by laravel/installer[v3.2.0].
    - laravel/installer v3.2.0 requires ext-zip * -> the requested PHP extension zip is missing from your system.


Installation failed, reverting ./composer.json to its original content.

問題が発生しているらしい

./composer.json has been updated

なんかよくわからないが、バージョンが違うのかな。
先の方を読むと、

Installation request for laravel/installer ^3.2 -> satisfiable by laravel/installer[v3.2.0].

リクエストをlaravel/installer[v3.2.0]に変えればいいよという感じですかね。

laravel/installer v3.2.0 requires ext-zip * -> the requested PHP extension zip is missing from your system
ここは、PHPのextensionのzipが見つからないということでしょうか。

とりあえず、最初の方を試してみる。

laravel/installer[v3.2.0]で実行してもダメ

  [InvalidArgumentException]                                                                                         
  Could not find a matching version of package laravel/installer[v3.2.0]. Check the package spelling, your version   
  constraint and that the package is available in a stability which matches your minimum-stability (stable).         


require [--dev] [--prefer-source] [--prefer-dist] [--fixed] [--no-progress] [--no-suggest] [--no-update] [--no-scripts] [--update-no-dev] [--update-with-dependencies] [--update-with-all-dependencies] [--ignore-platform-reqs] [--prefer-stable] [--prefer-lowest] [--sort-packages] [-o|--optimize-autoloader] [-a|--classmap-authoritative] [--apcu-autoloader] [--] [<packages>]...

ext-zipが足りない

laravel/installer v3.2.0 requires ext-zip * -> the requested PHP extension zip is missing from your system.

という記載があるので、laravel/installer v3.2.の要求に関してはext-zipが必要だということですかね。

とりあえずPHPをインストールし直した

$ brew install php

でインストールし直しました

できた!

$ composer global require "laravel/installer"
Changed current directory to /Users/onoharamakoto/.composer
Using version ^3.2 for laravel/installer
./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)
Package operations: 19 installs, 0 updates, 0 removals
  - Installing symfony/polyfill-php80 (v1.18.0): Downloading (100%)         
  - Installing symfony/process (v5.1.2): Downloading (100%)         
  - Installing symfony/polyfill-ctype (v1.18.0): Downloading (100%)         
  - Installing symfony/filesystem (v5.1.2): Downloading (100%)         
  - Installing symfony/polyfill-mbstring (v1.18.0): Downloading (100%)         
  - Installing symfony/polyfill-intl-normalizer (v1.18.0): Downloading (100%)         
  - Installing symfony/polyfill-intl-grapheme (v1.18.0): Downloading (100%)         
  - Installing symfony/string (v5.1.2): Downloading (100%)         
  - Installing psr/container (1.0.0): Downloading (100%)         
  - Installing symfony/service-contracts (v2.1.3): Downloading (100%)         
  - Installing symfony/polyfill-php73 (v1.18.0): Downloading (100%)         
  - Installing symfony/console (v5.1.2): Downloading (100%)         
  - Installing psr/http-message (1.0.1): Downloading (100%)         
  - Installing psr/http-client (1.0.1): Downloading (100%)         
  - Installing ralouphie/getallheaders (3.0.3): Downloading (100%)         
  - Installing guzzlehttp/psr7 (1.6.1): Downloading (100%)         
  - Installing guzzlehttp/promises (v1.3.1): Downloading (100%)         
  - Installing guzzlehttp/guzzle (7.0.1): Downloading (100%)         
  - Installing laravel/installer (v3.2.0): Downloading (100%)         
symfony/service-contracts suggests installing symfony/service-implementation
symfony/console suggests installing symfony/event-dispatcher
symfony/console suggests installing symfony/lock
symfony/console suggests installing psr/log (For using the console logger)
guzzlehttp/psr7 suggests installing zendframework/zend-httphandlerrunner (Emit PSR-7 responses)
guzzlehttp/guzzle suggests installing psr/log (Required for using the Log middleware)
Writing lock file
Generating autoload files
11 packages you are using are looking for funding.
Use the `composer fund` command to find out more!

なんかエラーメッセージが消えました。
どうやらインストールできたようです。

パスを通す

$ vim ~/.bashrc

新しくファイルを作成して開きます。
下の記述を入れる。

export PATH="$HOME/.composer/vendor/bin:$PATH"

:wqで保存して終了する。

次のコマンドを実行する

$ source ~/.bashrc

ここまで来たらLaravelのコマンドが使える

$ laravel
Laravel Installer 3.2.0

Usage:
  command [options] [arguments]

Options:
  -h, --help            Display this help message
  -q, --quiet           Do not output any message
  -V, --version         Display this application version
      --ansi            Force ANSI output
      --no-ansi         Disable ANSI output
  -n, --no-interaction  Do not ask any interactive question
  -v|vv|vvv, --verbose  Increase the verbosity of messages: 1 for normal output, 2 for more verbose output and 3 for debug

Available commands:
  help  Displays help for a command
  list  Lists commands
  new   Create a new Laravel application

エラーメッセージが出てません。動いているらしい。

ターミナルをいったん閉じると

zsh: command not found: laravel

Laravelのコマンドは使えなくなるみたいです。
もう一度source ~/.bashrcを実行してからやればまた使えるようになりました。

結論

Problem 1
    - Installation request for laravel/installer ^3.2 -> satisfiable by laravel/installer[v3.2.0].
    - laravel/installer v3.2.0 requires ext-zip * -> the requested PHP extension zip is missing from your system.

上記のようなエラーが出た場合は
1. PHPをインストールし直すbrew install php
2. composer global require "laravel/installer"を実行してlaravelをインストールする

これで大丈夫みたいです。

真似しないようにお願いします

当方、かなりの素人です。何をやっても一つずつエラーが発生して前に進まないのです。

とりあえず作業を記録しています。自分向けに書いてます。できるだけ他の肩の記事を参考に処理を進めてください。大変なことになるかもしれませんので。

  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

Laravel6.x + Laradockな環境でDuskを実行する

Laradock環境にDusk導入した時色々ハマったので手順化しておきます。

目次

作業の流れ

  1. Laradock設定変更
  2. Dusk導入
  3. Duskでテスト作成・実行する

環境

  • Laravel 6.x
  • Laradock
  • Docker Engine 19.03.x
  • Docker Compose 1.25.x

参考サイト

公式リファレンス
Laravel 6.x Laravel Dusk

Laradock周りでハマった時に参考にしたサイト
laravel5.5でduskがうごかへんねん

Laradock設定変更

laradock/.env の編集

下記を追記する。
.env.exampleも合わせて直しておく

laradock/.env
WORKSPACE_INSTALL_LIBNSS3=true
WORKSPACE_INSTALL_CHROME_DRIVER=true

laradock/docker-compose.yml の編集

workspace > build > argsに下記を追記する。

docker-compose.yml
          - INSTALL_LIBNSS3=${WORKSPACE_INSTALL_LIBNSS3}
          - INSTALL_CHROME_DRIVER=${WORKSPACE_INSTALL_CHROME_DRIVER}

laradock/workspace/Dockerfile の編集

Dockerfile
###########################################################################
# LIBNSS3:
###########################################################################

USER root

ARG INSTALL_LIBNSS3=false

RUN if [ ${INSTALL_LIBNSS3} = true ]; then \
    apt-get -y install libnss3 \
;fi

###########################################################################
# CHROME_DRIVER
###########################################################################

ARG INSTALL_CHROME_DRIVER=false

RUN if [ ${INSTALL_CHROME_DRIVER} = true ]; then \
    apt-get update && apt-get install --no-install-recommends -y wget \
    && wget -q -O - https://dl-ssl.google.com/linux/linux_signing_key.pub | apt-key add - \
    && echo "deb http://dl.google.com/linux/chrome/deb/ stable main" >> /etc/apt/sources.list.d/google.list \
    && apt-get update && apt-get install -y google-chrome-stable \
;fi

Laradockコンテナ郡を停止

docker-compose down

キャッシュ無しでビルド

docker-compose build --no-cache workspace

Laradockコンテナ郡を起動

docker-compose up -d

workspaceコンテナにログイン

docker-compose exec workspace bash

ChromeDriverのバージョン確認

Laravelプロジェクトディレクトリで実行する

vendor/laravel/dusk/bin/chromedriver-linux -v

下記のような文字が表示されればOK

ChromeDriver 84.0.4147.30 (xxxx-refs/branch-heads/4147@{#310})

Dusk導入

Duskパッケージのインストール

composer require --dev laravel/dusk

公式に記載の注意事項です。

Note: 本番環境にDuskをインストールしてはいけません。インストールすると、アプリケーションに対する未認証でのアクセスを許すようになります。

Duskのセットアップ

php artisan dusk:install

ChromeDriverのセットアップ

異なるバージョンのChromeDriverをインストールしているため、下記を実行。

php artisan dusk:chrome-driver

Duskでテスト作成・実行する

サンプルテストを確認

Duskのセットアップの時にサンプルテストが生成されるのでそれを試しに実行してみる。

tests/Browser/ExampleTest.php
<?php

namespace Tests\Browser;

use Illuminate\Foundation\Testing\DatabaseMigrations;
use Laravel\Dusk\Browser;
use Tests\DuskTestCase;

class ExampleTest extends DuskTestCase
{
    /**
     * A basic browser test example.
     *
     * @return void
     */
    public function testBasicExample()
    {
        $this->browse(function (Browser $browser) {
            $browser->visit('/')
                ->assertSee('Laravel');
        });
    }
}

実行

php artisan dusk

成功すればこんな感じで表示されます。

PHPUnit 8.5.8 by Sebastian Bergmann and contributors.

.                                                                   1 / 1 (100%)

Time: 2.74 seconds, Memory: 18.00 MB

OK (1 test, 1 assertion)

トラブルシュート: Chrome failed to start: exited abnormally.

ChromeDriverのインストールした時点のバージョンによって発生するかも

エラー詳細

1) Tests\Browser\ExampleTest::testBasicExample
Facebook\WebDriver\Exception\UnknownErrorException: unknown error: Chrome failed to start: exited abnormally.
  (unknown error: DevToolsActivePort file doesn't exist)
  (The process started from chrome location /usr/bin/google-chrome is no longer running, so ChromeDriver is assuming that Chrome has crashed.)

解決方法

--no-sandboxオプションを追加する

tests/DuskTestCase.php
    protected function driver()
    {
        $options = (new ChromeOptions)->addArguments([
            '--disable-gpu',
            '--headless',
            '--window-size=1920,1080',
            '--no-sandbox',
        ]);

FYI. https://github.com/laravel/dusk/issues/488#issuecomment-423065384

  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

Laravel ルーティング情報を表示してくれるコマンド

目的

  • すでに定義されているルーティング情報の一覧を出力するコマンドを忘れない様に書き留める。

紹介

  • 下記コマンドをLaravelアプリ名ディレクトリに移動してから実行する。

    $ php artisan route:list
    
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

XAMPPでLaravelをスタートする方法

参考にさせていただきました:https://qiita.com/moyashimanjyu/items/17ffe537fd37cccf00c0

  1. VSコードもしくは通常のエクスプローラなどでC:\xampp\htdocs\にLaravelフォルダを作成しておく(もうすでにあればOK)。
  2. VSコードで上記のLaravelフォルダを開く
  3. VSコードでパワーシェルを開く
  4. composer create-project --prefer-dist laravel/laravel [プロジェクト名]を実行
  5. xamppを立ち上げ、アパッチとMYSQLを立ち上げる。
  6. MySqlの管理画面で、データベースを作る。
  7. .envファイルに以下のようにする
  8. DB_CONNECTION=mysql DB_DATABASE=データベース名 DB_USERNAME=DBユーザー名 DB_PASSWORD=パスワード
  9. あとはマイグレーションファイルをつくって、モデルを作って、あとの作業は同じ。
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

LaravelとVue.jsの環境構築

プロジェクト作成

$ laravel new プロジェクト

Vueのインストール

laravel/uiパッケージをインストール

$ composer require laravel/ui

Vueのインストール

$ php artisan ui vue

JavaScriptのライブラリのインストールとコンパイル

$ npm install && npm run dev

Vue Routerのインストール

$ npm install --save-dev vue-router

Vue Routerプラグイン設定

resource/js/app.js
/**
 * First we will load all of this project's JavaScript dependencies which
 * includes Vue and other libraries. It is a great starting point when
 * building robust, powerful web applications using Vue and Laravel.
 */

require('./bootstrap');
import Vue from 'vue';
import VueRouter from 'vue-router';
import router from './router'

window.Vue = require('vue');

/**
 * The following block of code may be used to automatically register your
 * Vue components. It will recursively scan this directory for the Vue
 * components and automatically register them with their "basename".
 *
 * Eg. ./components/ExampleComponent.vue -> <example-component></example-component>
 */

// const files = require.context('./', true, /\.vue$/i)
// files.keys().map(key => Vue.component(key.split('/').pop().split('.')[0], files(key).default))

Vue.component('example-component', require('./components/ExampleComponent.vue').default);

/**
 * Next, we will create a fresh Vue application instance and attach it to
 * the page. Then, you may begin adding components to this application
 * or customize the JavaScript scaffolding to fit your unique needs.
 */

Vue.use(VueRouter);

const app = new Vue({
    el: '#app',
    router,
});

router.jsファイルの作成

router.jsを新規作成する

resource/js/router.js
import Router from 'vue-router'
import Home from './views/Home.vue'

export default new Router({
  mode: 'history',
  routes: [
    {
      path: '/',
      name: 'home',
      component: Home
    },
  ]
});

vueファイルの作成

viewsフォルダ、Home.vueファイルの新規作成

resource/js/views/Home.vue
<template>
    <h1>Home Page</h1>
</template>

bladeファイルへのVue Routerの設定

routes/web.php
Route::get('/', function () {
    return view('welcome');
});
resources¥views¥welcome.blade.php
<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="UTF-8">
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <title>Example</title>
<link rel="stylesheet" href="{{ mix('css/app.css') }}">
</head>
<body>

    <div id="app">
        <div id="nav">
          <router-link to="/">Home</router-link>
        </div>
        <router-view/>
        </div>
    </div>

<script src="{{ mix('js/app.js') }}"></script> 
</body>
</html>

ブラウザで確認

 $ php artisan serve
 $ npm run watch
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

【Laravel】ロリポップでComposer requireをするとPHP Fatal error: Out of memoryが出る場合にやったこと

原因

文字通りメモリ不足です。

つまりメモリがあれば良いわけなのですが、ロリポップではメモリを上限に設定してもPHP Fatal error: Out of memoryが出ます。

また、そもそもロリポップではphp.iniが変更できなかったりと制限があります。

$ composer require intervention/image

とかが普通にできないです。
そういえばcomposerでlaravelをインストールしようとした時もエラーが出たような・・・

対処(正解かどうかはわからない)

個人的にやったことをまとめます。

僕はこのやり方で一応なんとかなったのですが、責任は追いません。

というか、もっと良い方法ありませんか...?

scpコマンドを使用して1回ローカルに落とす

$ scp -r -P[ポート番号] ドメイン名@ssh.lolipop.jp:web [ダウンロード先]

scpコマンドはこちらの記事でわかりやすく解説してくださってます。

例えばこんな感じです。(macのデスクトップのhogeフォルダにコピーする場合)
$ scp -r -P1234 ×××@ssh.lolipop.jp:web ~/Desktop/hoge

ポート番号・パスワードが必要なので、そこはロリポップのメニューの「SSH」から見てみてください。
あと結構時間がかかります。

ローカルでcomposerを使う

$ cd [ダウンロードしたフォルダのパス]
$ composer require [パッケージ名]

composerがcommand not foundの場合はインストールしましょう。
僕はこちらの記事を参考にしました。

再びサーバーにコピー

$ scp -r -P[ポート番号] [ダウンロードしたいローカルのディレクトリパス] ドメイン名@ssh.lolipop.jp:up

これでwebディレクトリと同じ階層に、cpディレクトリが配置されました。

あとはwebディレクトリを削除し、cpディレクトリをwebにリネームすれば完了です。

$ mv web web2 (一応web2というディレクトリを作って今までのプロジェクトを保存しておく)
$ rm web
$ mv up web

これで一応完了なのですが、このあと画像をアップロードしたら画像がnot found(404)になるという事例が発生しました。

めちゃくちゃ焦りませした。。。

調べてみると、どうやらシンボリックを再作成する必要がありそうです。
ということで、

  • 一旦public/storageを削除
  • 再びシンボリックを作成

という処理をします。

# sshでログイン後・・・
$ cd web
$ cd public
$ rm storage
$ cd ../
$ php artisan storage:link

これで再びシンボリックが作成され、全ての工程が完了しました。。。

最後に・・・

きっともっと良い方法があるとは思うのですが(例えば手動でcomposer.jsonに追記して・・・とか)、僕の知識ではこれが一番安全でした。

そもそもレンタルサーバーでcomposerを使うのがいけないのかもしれませんね。

以上、Web初心者の苦労でした。

もっと良い方法あったらコメントお願いします!!!

  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

Laravel CRUD処理を使った投稿アプリを作成する その6 投稿編集機能

目的

  • アプリを作成する上で基本となるCRUD処理を有したLaravelアプリをチュートリアル的に作成する方法をまとめる

実施環境

  • ハードウェア環境
項目 情報
OS macOS Catalina(10.15.5)
ハードウェア MacBook Pro (13-inch, 2020, Four Thunderbolt 3 ports)
プロセッサ 2 GHz クアッドコアIntel Core i5
メモリ 32 GB 3733 MHz LPDDR4
グラフィックス Intel Iris Plus Graphics 1536 MB
  • ソフトウェア環境
項目 情報 備考
PHP バージョン 7.4.3 Homwbrewを用いて導入
Laravel バージョン 7.0.8 commposerを用いてこちらの方法で導入→Mac Laravelの環境構築を行う
MySQLバージョン 8.0.19 for osx10.13 on x86_64 Homwbrewを用いてこちらの方法で導入→Mac HomebrewでMySQLをインストールする

前提条件

前提情報

  • DockerやAWSなどは使用せずにMacのローカルに実施環境と同じLaravel開発環境を構築して実施する。
  • チュートリアルで実際に筆者が作成したソースコードをGitHubにて公開予定である。
  • CRUD処理の作成完了を最短目標にしてバリデーションなどは後々設定することとする。
  • 実施環境と同じ環境がDockerやAWSで用意できるなら都度読み替えていただければ実施が可能だと思う。
  • 公式ドキュメントと一冊の技術書を元に本記事を記載する。

この記事の読後感

  • 投稿内容を投稿後に編集することができる。

全ての記事(miriwo_laravelチュートリアル)を通した読後感

  • Laravelアプリでログインなどのユーザ認証付き投稿アプリの作成ができる。

概要

  1. ルーティングの記載
  2. コントローラの記載
  3. ビューファイルの修正
  4. 確認

概要

  1. ルーティングの記載

    1. laravel_crudディレクトリで下記コマンドを実行してルーティングファイルを開く。

      $ vi routes/web.php 
      
    2. 開いたファイルに下記の行を追記する。

      laravel_crud/routes/web.php
      Route::get('/edit', 'ContentController@edit')->name('edit');
      Route::post('/update', 'ContentController@update')->name('update');
      
  2. コントローラの記載

    1. laravel_crudディレクトリで下記コマンドを実行して作成したコントローラファイルを開く。

      $ vi app/Http/Controllers/ContentController.php
      
    2. 下記の内容をクラス内に追記する。

      laravel_crud/app/Http/Controllers/ContentController.php
      public function edit($content_id)
      {
          $contents_edit_query = Content::select('*');
          $contents_edit_query->where('id', $content_id);
          $edit_contents = $contents_edit_query->get();
          $edit_content = $edit_contents[0];
      
          return view('contents.edit', [
              'edit_content' => $edit_content,
          ]);
      }
      
      public function update(Request $request)
      {
          $contents_update_query = Content::select('*');
          $contents_update_query->where('id', $request['content_id']);
          $update_contents = $contents_update_query->get();
      
          $update_content = $update_contents[0];
          $update_content->content = $request['content'];
          $update_content->save();
      
          return redirect('/output');
      }
      
    3. 記載後のコントローラファイルの内容を下記に記載する。

      laravel_crud/app/Http/Controllers/ContentController.php
      <?php
      
      namespace App\Http\Controllers;
      
      use Illuminate\Http\Request;
      use App\Models\Content;
      
      class ContentController extends Controller
      {
          public function input()
          {
              return view('contents.input');
          }
      
          public function save(Request $request)
          {
              $input_content = new Content();
              $input_content->content = $request['content'];
              $input_content->save();
      
              return redirect('/output');
          }
      
          public function output()
          {
              $contents_get_query = Content::select('*');
              $all_contents = $contents_get_query->get();
      
              return view('contents.output', [
                  'all_contents' => $all_contents,
              ]);
          }
      
          public function delete(Request $request)
          {
              $contents_delete_query = Content::select('*');
              $contents_delete_query->where('id', $request['content_id']);
              $contents_delete_query->delete();
      
              return redirect('/output');
          }
      
          public function edit($content_id)
          {
              $contents_edit_query = Content::select('*');
              $contents_edit_query->where('id', $content_id);
              $edit_contents = $contents_edit_query->get();
              $edit_content = $edit_contents[0];
      
              return view('contents.edit', [
                  'edit_content' => $edit_content,
              ]);
          }
      
          public function update(Request $request)
          {
              $contents_update_query = Content::select('*');
              $contents_update_query->where('id', $request['content_id']);
              $update_contents = $contents_update_query->get();
      
              $update_content = $update_contents[0];
              $update_content->content = $request['content'];
              $update_content->save();
      
              return redirect('/output');
          }
      }
      
  3. ビューファイルの作成と修正

    1. laravel_crudディレクトリで下記コマンドを実行してビューファイルを作成する。

      vi resources/views/contents/edit.blade.php
      
    2. 作成して開いたビューファイルに下記の内容を追記する。

      laravel_crud/resources/views/contents/edit.blade.php
      <h1>edit</h1>
      
      <form action="{{route('update')}}" method="post">
          @csrf
          <textarea name="content" cols="30" rows="10">{{$edit_content['content']}}</textarea>
          <input type="hidden" name="content_id" value="{{$edit_content['id']}}">
          <input type="submit" value="送信">
      </form>
      
    3. laravel_crudディレクトリで下記コマンドを実行してビューファイルを開く。

      vi resources/views/contents/output.blade.php
      
    4. 開いたビューファイルに下記の内容を追記する。

      laravel_crud/resources/views/contents/output.blade.php
      <h1>output</h1>
      
      @foreach ($all_contents as $item)
          <hr>
          <p>{{$item['content']}}</p>
          <form action="{{route('delete')}}" method="post">
              @csrf
              <input type="hidden" name="content_id" value="{{$item['id']}}">
              <input type="submit" value="削除">
          </form>
          <a href="{{route('edit', ['content_id' => $item['id']])}}">
              <button>編集</button>
          </a>
      @endforeach
      
  4. 確認

    1. laravel_crudディレクトリで下記コマンドを実行してローカルサーバを起動する。

      $ php artisan serve
      
    2. ブラウザで下記にアクセスする。

    3. 「編集」ボタンをクリックする。

      127_0_0_1_8000_output.png

    4. 下記の様に先に投稿した内容がすでに記載されているテキストボックスが出力される。

      127_0_0_1_8000_edit_1.png

    5. 内容を任意の物に変更し、「送信」ボタンをクリックする。

      127_0_0_1_8000_edit_1.png

    6. 下記ページにリダイレクトして、投稿内容が変更されていれば本記事の内容は完了である。

      127_0_0_1_8000_output.png

  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

PHP-数値を3桁ごとにカンマを付与する関数

number_format関数

数字を千位毎にグループ化してフォーマットする

<?php
  echo number_fornmat(1234567); //1,234,567

laravelで使うときは下記のような感じで使う

$price = [1000, 2000, 3000,];
foreach ($price as $value){
<td>¥{{ number_format($value->price) }}</td>
}

結果
¥1,000
¥2,000
¥3,000

余談ですが、勝手に小数点を含む数値」を四捨五入するので、第二引数に桁数を指定すれば小数点以下も表示できます。

<?php
  echo number_format(1234.567,2); // 1,234.57
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む