在我的 laravel vue 專案中,在從 laravel 后端獲取資料期間,我沒有從 api 獲取影像。除了影像外,所有其他資料都出現了。
JSON:
[
{
"id": 1,
"name": "Tanjib",
"destination": "Sweden",
"adult": 4,
"children": 2,
"flight_on_date": "2021-12-17",
"image": "1638790776.png",
"created_at": "2021-12-06T11:39:36.000000Z",
"updated_at": "2021-12-06T11:39:36.000000Z"
}
]
我的代碼:
<div v-for="(data, index) in bookingList" :key="index">
<table class="table">
<tr>
<th>Name</th>
<th>Destination</th>
<th>Adult</th>
<th>Children</th>
<th>Flight Date</th>
<th>Image</th>
</tr>
<tr>
<td>{{data.name}}</td>
<td>{{data.destination}}</td>
<td>{{data.adult}}</td>
<td>{{data.children}}</td>
<td>{{data.flight_on_date}}</td>
<td><img :src="data.image" alt=""> </td>
</tr>
</table>
</div>
我還需要做什么嗎?
由于我是 laravel 的新手,請盡量提供盡可能詳細的解決方案。我的后端代碼如下:
我的后端控制器:
public function store(Request $request)
{
// dd($request);
$request->validate([
// 'image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
]);
try {
$imageName = null;
if ($request->hasFile('image')) {
$images = $request->file('image');
$imageName = time() . '.' . $images->extension();
$path = $request->file('image')->storeAs(
'public/images',
$imageName
);
}
$sql= Booking::create([
'name' => $request['name'],
'destination' => $request['destination'],
'adult' => $request['adult'],
'children' => $request['children'],
'flight_on_date' => $request['flight_on_date'],
// 'image' => $imageName,
'image' => $path,
]);
if($sql){
return "Success";
}else{
return "Fail";
}
} catch (\Exception $e) {
}
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show()
{
$bookings = Booking::all();
return $bookings;
}
uj5u.com熱心網友回復:
將影像名稱直接傳遞給src元素是不夠的。您可以在模型上使用訪問器。讓我解釋。Product我的專案中有一個模型,該products表包含以下列:
- 姓名
- 描述
- 單價
- 拇指
該thumb列包含類似的值51237594231582362140298002369.png,我將這些影像保存在storage/products目錄中。然后在我的Product模型中,我有一個訪問器,如下所示:
/**
* Get the product's thumbnail.
*
* @param string $value
* @return string
*/
public function getThumbAttribute($value)
{
return asset('storage/products/' . $value);
}
此訪問器訪問thumb列中的值并附https://my-awesome-store.com/storage/products/加到縮略圖名稱。我使用它作為src我的影像元素。順便說一下,我將我的storage目錄鏈接到該public目錄。
進一步閱讀 -
- 訪問器和修改器
asset()輔助方法- 公共磁盤
希望能幫助到你。如果您需要幫助,請隨時與我們聯系。
uj5u.com熱心網友回復:
您需要提供影像的完整地址src,我建議您從服務器發送完整地址。像這樣:https://www.your_domain.com/images/1638790776.png
只需檢查您的影像的存盤路徑,例如,您的影像可能在您的public/images檔案夾中。那么您的完整圖片網址將如我上面所說。
您可以使用 laravel 模型中的訪問器創建這個完整的 url。打開您的Booking.php模型檔案并將此代碼放入其中:
public function getImageAttribute($value){
return 'your_domain.com/images/'.$value;
}
只需替換your_domain.com為您的真實域(如http://mysite.local或http://127.0.0.1:8000/)
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/377018.html
