简体   繁体   English

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

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

i want to add images in folder public\\storage\\annonces\\August2020 and link annonces\\August2020\\annonces.jpg in database but it create a folder name 82020 in racing public\\storage\\annonces\\82020 ,but for me i want create a folder name Monthnow2020 like August2020我想在文件夹中添加图像public\\storage\\annonces\\August2020和纽带annonces\\August2020\\annonces.jpg的数据库,但它创建一个文件夹名82020在赛车public\\storage\\annonces\\82020 ,但对我来说,我想创建一个文件夹将 Monthnow2020 命名为August2020

AnnoncesController.php 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.');
    }

just put \\ to create new folder and use date now()->format('F').now()->format('Y') function只需将\\创建新文件夹并使用 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(); 

like above像上面一样

You can use Carbon's englishMonth function to get the month name.您可以使用 Carbon 的englishMonth函数来获取月份名称。

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

Source: Carbon documentation来源:碳文档

A much better refactoring could be done in a cleaner way and achieve the goal you want in this way.可以以更简洁的方式完成更好的重构,并以这种方式实现您想要的目标。

/**
 * 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