簡體   English   中英

如何使用laravel像August2020一樣獲取日期的月份和年份?

[英]how get month and year of date now like August2020 using laravel?

我想在文件夾中添加圖像public\\storage\\annonces\\August2020和紐帶annonces\\August2020\\annonces.jpg的數據庫,但它創建一個文件夾名82020在賽車public\\storage\\annonces\\82020 ,但對我來說,我想創建一個文件夾將 Monthnow2020 命名為August2020

AnnoncesController.php

public function store(Request $request)
    {
       $Annonce = new Annonce($request->all());
       $jdate = Carbon::now();
       if($request->hasFile('image'))
       {
        $image = $request->file('image');
        $image->storeAs("public\annonces\ ".$jdate->month.$jdate->year,'annonces'.".".$image->extension());
        $Annonce->image = "annonces\ ".$jdate->month.$jdate->year."annonces" .".".$image->extension(); 
        }
        $Annonce->save();
        return Redirect::to("annonces")
        ->withSuccess('Great! file has been successfully uploaded.');
    }

只需將\\創建新文件夾並使用 date now()->format('F').now()->format('Y')函數

 $dateFromat = now()->format('F').now()->format('Y');
 $image->storeAs("public\annonces\ ".$dateFromat.'\annonces'.".".$image->extension());
 $Annonce->image = "annonces\ ".$dateFromat."\annonces" .".".$image->extension(); 

像上面一樣

您可以使用 Carbon 的englishMonth函數來獲取月份名稱。

$image->storeAs("public\annonces\ ".$jdate->englishMonth() . $jdate->year,'annonces'.".".$image->extension());
$Annonce->image = "annonces\ ".$jdate->englishMonth().$jdate->year."annonces" .".".$image->extension();

來源:碳文檔

可以以更簡潔的方式完成更好的重構,並以這種方式實現您想要的目標。

/**
 * Store a newly created resource in storage.
 *
 * @param  \Illuminate\Http\Request  $request
 * @return \Illuminate\Http\Response
 */
public function store(Request $request)
{
    $Annonce = new Annonce($request->all());

    if ($request->hasFile('image')) {
        $path = $request->file('avatar')->storeAs(
            "annonces" . \Carbon\Carbon::now()->format('F\Y'), 'annonces'
        );
        $Annonce->image = $path;
    }
    
    $Annonce->save();

    return Redirect::to('annonces')
        ->withSuccess('Great! file has been successfully uploaded.');
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM