繁体   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