iT邦幫忙

2025 iThome 鐵人賽

DAY 29
0
Modern Web

Laravel 是甚麼系列 第 29

有的四個網址

  • 分享至 

  • xImage
  •  

目前有的四個網址
http://127.0.0.1:8000/

點確認上品數量

點 通知

http://127.0.0.1:8000/contact-us

http://127.0.0.1:8000/admin/orders?page=1

http://127.0.0.1:8000/admin/products

資料表看:


第一個
http://127.0.0.1:8000/storage/images/2CeP1jTIXxIAywLQkfWektiezeDuQhUlunqb6VZX.jpg

第2個
http://127.0.0.1:8000/storage/images/gGzw2Y0y9fyype8tu0KXKrbjsDN9llWLz1hu6px8.png

後端看

相關的程式碼

程式碼

<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Models\Product;
use App\Http\Controllers\Controller;
use App\Notifications\ProductDelivery;

class ProductController extends Controller
{
    public function index(Request $request)
{

    $productCount = Product::count();
    $dataPerPage = 2;
    $productPages = ceil($productCount / $dataPerPage);
    $currentPage = isset($request->all()['page']) ? $request->all()['page'] : 1;
    $products = Product::orderBy('created_at','desc')
                   ->offset($dataPerPage * ($currentPage - 1))
                   ->limit($dataPerPage)
                   ->get();
    
    return view('admin.products.index',['products' => $products,
    'productCount' => $productCount,
    'productPages' => $productPages]);

}

public function uploadImage(Request $request)
{
    $request->validate([
        'product_id' => 'required|integer|exists:products,id',
        'product_image' => 'required|image|max:2048',
    ]);

    $product = Product::findOrFail($request->product_id);

    $path = $request->file('product_image')->store('images', 'public');
    $filename = basename($path);

    // Create a new image record in the images table instead of updating products table
    $product->images()->create([
        'path' => $path,
        'filename' => $filename,
        'attachable_type' => 'App\Models\Product',
        //'attachable_type' => Product::class, // Use ::class instead of string literal
        'attachable_id' => $product->id,
    ]);

    return redirect()->back()->with('success', '圖片上傳成功');
}

}

 
程式碼
```<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Image extends Model
{
    protected $guarded = [];

    public function attachable()
    {
        return $this->morphTo();
    }
}

 
程式碼

上一篇
上傳圖片
下一篇
安裝EXCEL套件
系列文
Laravel 是甚麼30
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言