简体   繁体   中英

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

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

 $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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM