Skip to main content

快取指令

laravel官方文件

安裝laravel

php & composer
sudo apt install php composer php-cli php-common php-mbstring php-xml php-zip php-mysql php-json php-bcmath php-curl php-gd php-tokenizer php8.1-xml php-fpm mariadb-server nginx

這裡要是需要或習慣安裝apache or nginx,nginx需要使用php-fpm

php -v
sudo apt install curl php-cli php-mbstring git unzip
curl -sS https://getcomposer.org/installer | sudo php -- --install-dir=/usr/local/bin --filename=composer
composer --version
install laravel
composer create-project --prefer-dist laravel/laravel your-project-name
cd your-project-name

install apache2 or nginx

apache
sudo vi /etc/apache2/sites-available/your-project-name.conf
<VirtualHost *:80>
    ServerName your-domain-or-ip
    DocumentRoot /var/www/html/your-project-name/public
    <Directory /var/www/html/your-project-name>
        AllowOverride All
    </Directory>
</VirtualHost>
sudo a2enmod rewrite

Enable the virtual host:

sudo a2ensite your-project-name.conf

Restart Apache for the changes to take effect:

sudo systemctl restart apache2
nginx
sudo vi /etc/nginx/sites-available/your-project-name
server {
    listen 80 default_server;
    server_name your-domain-or-ip;
    return 301 https://$server_name$request_uri;
    }

server {
    listen 443 ssl default_server;
    server_name your-domain-or-ip;

    include snippets/ssl;
    include snippets/ssl;

    root /var/www/html/your-project-name/public;
    index index.php;

    location / {
 #       try_files $uri $uri/ /index.php?$query_string;
    try_files $uri $uri/ /index.php?$args;
    }

    error_page 404 /404.html;
    error_page 500 502 503 504 /50x.html;
    location = /50x.html {
    root /var/www/html;
    }
    
        location ~ \.php$ {
               include snippets/fastcgi-php.conf;
        #      With php-fpm (or other unix sockets):
                fastcgi_pass unix:/var/run/php/php8.1-fpm.sock;
                fastcgi_index index.php;
                fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
                include fastcgi_params;
        #       # With php-cgi (or other tcp sockets):
        #       fastcgi_pass 127.0.0.1:9000;
        }
        # deny access to .htaccess files, if Apache's document root
        # concurs with nginx's one
        #

        add_header X-XSS-Protection "1; mode=block";
#       add_header 'Access-Control-Allow-Origin' *;
#       add_header 'Access-Control-Allow-Credentials' true;
#       add_header Strict-Transport-Security "max-age=31536000; includeSubdomains; preload";
#       add_header Content-Security-Policy "default-src 'self' http: https: data: blob: 'unsafe-inline'" always;

        location ~*  \.(jpg|jpeg|gif|png|svg)$ {
                expires 365d;
        }

        location ~*  \.(pdf|css|html|js|swf)$ {
                expires 2d;
        }

        location ~ /\.ht {
                deny all;
        }

        location ~ ^/\.user\.ini {
                deny all;
        }

       location ~ /.well-known/acme-challenge {
        root /var/www/html;
               allow all;
        }

        location ~ /\.ht {
                deny all;
        }
}

Replace your-domain-or-ip with your actual domain name or server IP address.
Enable the Nginx server block:

sudo ln -s /etc/nginx/sites-available/your-project-name /etc/nginx/sites-enabled/

Test the Nginx configuration for any syntax errors:

sudo nginx -t

Restart Nginx for the changes to take effect:

sudo systemctl restart nginx

MariaDB 資料庫

在安裝好 MariaDB 資料庫後,使用前建議先調整一下安全性的設定:

MariaDB/MySQL 資料庫安全性設定

sudo mysql_secure_installation

使用 root 登入 MariaDB/MySQL 資料庫

sudo mysql -u root -p

建立 laravel 資料庫

CREATE DATABASE laravel;
CREATE USER `user`@`localhost` IDENTIFIED BY 'yourpassword';
GRANT ALL ON laravel.* TO `user`@`localhost`;
FLUSH PRIVILEGES;

編輯 Laravel 專案目錄中的 .env 設定檔,將資料庫的相關資訊填入其中:

DB_DATABASE=laravel
DB_USERNAME=user
DB_PASSWORD=yourpassword

除了 .env 的設定檔之外,也可以直接編輯 config/database.php 中的資料庫設定。

php artisan serve 伺服器   #開啟服務,預設8000
php artisan migrate       #建立使用資料庫
php artisan about         #快速瀏覽環境設定

Configure Laravel

cp .env.example .env

Generate a new application key

php artisan key:generate

Set the appropriate permissions on Laravel directories

sudo chown -R www-data:www-data /var/www/html/your-project-name/storage
sudo chmod -R 775 /var/www/html/your-project-name/storage
Laravel Breeze
composer require laravel/breeze --dev      # 安裝Breeze

安裝npm跟nodejs,請注意版本問題

sudo apt install npm
sudo apt install nodejs

ubuntu 系統函式庫的nodejs版本通常會太舊,可以用下方方式處理,請問注意版本 ,或可以從https://nodejs.org/en下載

curl -fsSL https://deb.nodesource.com/setup_18.x | sudo -E bash - 
sudo apt-get install -y nodejs
php artisan breeze:install
php artisan migrate
npm install

直接運作

npm run dev

php artisan用法

php artisan env:encrypt      #加密環境變數

備註:完成後會加密.env並更名成.env.encrypted,然後會輸出密碼,也可以用下方指令修改密碼。

php artisan env:encrypt --key=密碼
php artisan env:decrypt       #解密

備註:--key 解密密碼

php artisan env:decrypt --force

php artisan serve       #不使用webagent直接運作,預設8000port

php artisan serve       #不使用webagent直接運作,預設8000port
製作mode(database一起建立)

資料庫資料的建立與使用概略流程:

make:model->migrate->make:factory->make:seeder->db:seed->make:controller->create view->set route

php artisan make:model Movie -m
php artisan migrate     #資料庫創建
php artisan make:migration create_新table名稱_table     #建立新table
php artisan make:migration create_aboutme_photo — table=aboutme  
php artisan migrate:status     #資料庫建制狀態
php artisan migrate:rollback  #資料庫還原
php artisan migrate:refresh    #資料庫重鍵(資料會不見)
製作Factory資料夾
php artisan make:factory MovieFactory --model=Movie
製作seeder
php artisan make:seeder MovieSeeder
製作control
php artisan make:controller MovieController
 啟用維護模式
php artisan down

備註:
後方可以增加--refresh=(秒數) 來告訴伺服器多久要重新整理一次
--render="errors::503" 可以放置503網頁的view

關閉維護模式
php artisan up

使用密鑰繞過維護模式

php artisan down --secret="1630542a-246b-4b66-afa1-dd72a4c43515"  

 使用方式:https://example.com/1630542a-246b-4b66-afa1-dd72a4c43515

在app新增job類別
php artisan make:job

備註: 可使用php artisan make list 來檢查可以新增的類別

route列表
php artisan route:list

備註:

  1. --except-vendor是會顯示影藏在第三方的route
  2. --only-vendor 只顯示第三方套件
  3. -v 會顯示Route Middleware
  4. --path=api cjo4vu04g4eo32u/4
  5. 會顯示給URI開頭的Route
php artisan vendor:publish --tag=laravel-pagination

前台使用tailwindcss 而後台是 bootstrap
這個路徑就是 Laravel 內置的格式/排版 resources/views/vendor/pagination

清除cache
php artisan cache:clear
php artisan route:clear
php artisan view:clear

Route使用

Route::get($uri, $callback);
Route::post($uri, $callback);
Route::put($uri, $callback);
Route::patch($uri, $callback);
Route::delete($uri, $callback);
Route::options($uri, $callback);
Route::match(['get', 'post'], '/', function () {
 // ...
});
Route::any('/', function () {
 // ...
});
重新導向
Route::redirect('/here', '/there');
Route::redirect('/here', '/there', 301);
Route::permanentRedirect('/here', '/there');

 重導至路徑為 users/index 的位址

redirect()->to("users/index");

 使用全域輔助捷徑,有同樣的效果

redirect("users/index");

 使用靜態介面, 也有同樣的效果

Redirect::to("users/index"); 

 靜態介面捷徑

Redirect("users/index");
Route::view('/welcome', 'welcome');
Route::view('/welcome', 'welcome', ['name' => 'Taylor']);
to()
function to($to = null, $status = 302, $header = [], $secure = null)

$to : 有效的內部路徑
$status 是 HTTP 狀態
$header 是需要一併傳送的 HTTP 標頭
$secure : http vs. https 的預設選項

route()
function route($to = null, $parameters =[], $status = 302, $headers = [])

$to : 特定路由名稱
$parameters : 路由所需的參數

withInput()

把表單輸入的資料傳給目標頁面

redirect("users.edit")
    ->withInput()
    ->with(["success" => "update success", "id" => 2]);
env變數設定

設定取得所有變數

'debug' => env('APP_DEBUG', false),
修改時區

在.env

APP_TIMEZONE='America/New_York'

在app.php(下方三種方式擇1)

'timezone' => 'America/New_York',
'timezone' => env('APP_TIMEZONE', 'UTC'),

完成後可以使用php artisan config:clear 清除快取

問題處理

會出現游標過大的現象

<!DOCTYPE html>
<html>
<head>
    <title>Laravel 10 Eloquent Model Search Example - ItSolutionStuff.com</title>
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/5.0.1/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container">
    <div class="card">
      <div class="card-header">
        <h2>Laravel 10 Eloquent Model Search Example - ItSolutionStuff.com</h2>
      </div>
      <div class="card-body">
            <form class="row g-3" method="GET" action="{{ route('users.index') }}">
              <div class="col-auto">
                <label for="search" class="visually-hidden">Search</label>
                <input type="text" class="form-control" id="search" placeholder="Search" name="search"value="{{ request()->search }}">
              </div>
              <div class="col-auto">
                <button type="submit" class="btn btn-primary mb-3">Search</button>
              </div>
            </form>
            <table class="table table-striped">
                <tr>
                    <th>ID</th>
                    <th>Name</th>
                    <th>Email</th>
                </tr>
                @foreach ($users as $user)
                    <tr>
                        <td>{{ $user->id }}</td>
                        <td>{{ $user->name }}</td>
                        <td>{{ $user->email }}</td>
                    </tr>
                @endforeach
            </table>
            {{$users->links()}}
      </div>
    </div>
</div>
</body>
</html>

將          {{$users->links()}}
改成        {{$users->links('pagination::bootstrap-5')}}

可以顯示頁數跟上一頁

<!-- a Tag for previous page -->
<a href="{{$employees->previousPageUrl()}}">
    <!-- You can insert logo or text here -->
</a>
@for($i=0;$i<=$employees->lastPage();$i++)
    <!-- a Tag for another page -->
    <a href="{{$employees->url($i)}}">{{$i}}</a>
@endfor
<!-- a Tag for next page -->
<a href="{{$employees->nextPageUrl()}}">
    <!-- You can insert logo or text here -->
</a>

每次顯示頁數

$row = User::paginate(15);

帶上原本現有url 的query功能 withQueryString()

$row = User::where('name', 'LIKE', "%{$search}%")
      ->paginate(15)
      ->withQueryString();  #新增部份

這樣一來,你轉頁時得到的網址就是類似如下: 

xxx.com/user/keyword=xxx&page=2
fragment() 加上錨點
$row = User::where('name', 'LIKE', "%{$search}%")
    ->paginate(15)
    ->fragment('user_data')    #新增部份
    ->withQueryString();

這樣一來,你轉頁時得到的網址就是類似如下: 

xxx.com/user/keyword=xxx&page=2#user_data
預設樣式是 Tailwindcss, 你可手動改為 Bootstrap
//app/Providers/AppServiceProvider.php #路徑
use Illuminate\Pagination\Paginator;    #新增
    public function boot(){
        Paginator::useBootstrap();      #新增
    }
/**
 * Get the validation rules that apply to the request.
 *
 * @return array
 */
public function rules()
{
    return [
        'title' => 'required|unique:posts|max:255',
        'body' => 'required',
    ];
}

required(必須) unique: table名稱(唯一值)max:值最多255 min:值最少為
email(email格式) date(日期) nullable(可以空白)
mimes:png,jpg,jpeg,webp 檔案格式 decimal:0,2 數字 size:11 數子數量
備註:如果要使用到檔案需要在form新增enctype="multipart/form-data"

驗證規則

request()->validate([
    'password' => 'required|confirmed'
])

confirmed(密碼驗證
備註:另一個值需要是password_confirmation,如下

<div class="form-group row">
    <label for="password-confirm" class="col-md-4 col-form-label text-md-right">Confirm Password</label> 
    <div class="col-md-6">
        <input id="password-confirm" type="password" name="password_confirmation" required="required" class="form-control">
    </div>
</div>
Selects

從資料表中取得所有的資料列

$users = DB::table('users')->get();
foreach ($users as $user)
{
    var_dump($user->name);
}

從資料表中取得單一資料列

$user = DB::table('users')->where('name', 'John')->first();
var_dump($user->name);

取得單一欄位值的列表

$roles = DB::table('roles')->lists('title');

這個方法將會回傳資料表 role 的 title 欄位值的陣列。你也可以透過下面的方法,為回傳的陣列指定自訂鍵值。

$roles = DB::table('roles')->lists('title', 'name');

指定查詢子句 (Select Clause)

$users = DB::table('users')->select('name', 'email')->get();
$users = DB::table('users')->distinct()->get();
$users = DB::table('users')->select('name as user_name')->get();

增加查詢子句到既存的查詢中

$query = DB::table('users')->select('name');
$users = $query->addSelect('age')->get();

使用 where 及運算子

$users = DB::table('users')->where('votes', '>', 100)->get();
「or」語法
$users = DB::table('users')
                    ->where('votes', '>', 100)
                    ->orWhere('name', 'John')
                    ->get();
使用 Where Between
$users = DB::table('users')
                    ->whereBetween('votes', array(1, 100))->get();
使用 Where Not Between
$users = DB::table('users')
                    ->whereNotBetween('votes', array(1, 100))->get();
使用 Where In 與陣列
$users = DB::table('users')
                    ->whereIn('id', array(1, 2, 3))->get();

$users = DB::table('users')
                    ->whereNotIn('id', array(1, 2, 3))->get();
排序(Order By)、分群(Group By) 及 Having
$users = DB::table('users')
                    ->orderBy('name', 'desc')
                    ->groupBy('count')
                    ->having('count', '>', 100)
                    ->get();
偏移(Offset) 及 限制(Limit)
$users = DB::table('users')->skip(10)->take(5)->get();
Joins

查詢產生器也可以使用 join 語法,看看下面的範例:
基本的 Join 語法

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

Left Join 語法

DB::table('users')
        ->leftJoin('posts', 'users.id', '=', 'posts.user_id')
        ->get();

你也可以指定更進階的 join 子句

DB::table('users')
        ->join('contacts', function($join)
        {
            $join->on('users.id', '=', 'contacts.user_id')->orOn(...);
        })
        ->get();

如果你想在你的 join 中使用 where 型式的子句,你可以在 join 子句裡使用 where 或 orWhere 方法。下面的方法將會比較 contacts 資料表中的 user_id 的數值,而不是比較兩個欄位。

DB::table('users')
        ->join('contacts', function($join)
        {
            $join->on('users.id', '=', 'contacts.user_id')
                 ->where('contacts.user_id', '>', 5);
        })
        ->get();
進階 Where

群組化參數
有些時候你需要更進階的 where 子句,像是「where exists」或巢狀的群組化參數。Laravel 的查詢產生器也可以處理這樣的情況;

DB::table('users')
            ->where('name', '=', 'John')
            ->orWhere(function($query)
            {
                $query->where('votes', '>', 100)
                      ->where('title', '<>', 'Admin');
            })
            ->get();

上面的查詢語法會產生下方的 SQL:

select * from users
where exists (
    select 1 from orders where orders.user_id = users.id
)
聚合

查詢產生器也提供各式各樣的聚合方法,像是 count、max、min、avg 及 sum。
使用聚合方法

 

$users = DB::table('users')->count();
$price = DB::table('orders')->max('price');
$price = DB::table('orders')->min('price');
$price = DB::table('orders')->avg('price');
$total = DB::table('users')->sum('votes');