skip to Main Content

Is there a way to "return time" in a Laravel project? And set the date to be last month and then all records added to have a timestamp from last month?

2

Answers


  1. You can use Carbon, laravel has a helper built in

    now()->subMonth();
    

    Docs

    You can view all available Carbon functions in your project at the following path:

    vendor/nesbot/carbon/src/Carbon/Carbon.php

    Login or Signup to reply.
  2. To get last month. More Carbon options

    1. subMonth() => if month back

      Carbon::now()->subMonth(); # (returns 2023-04-05) 
      # This will print the month back from the current date.
      
    2. startOfMonth => If the start of the current month

      Carbon::now()->startOfMonth(); # (returns 2023-05-01) 
      # This will print the month's start date from the current date.
      
    3. subMonth()->startOfMonth() => If start of the last month

      Carbon::now()->subMonth()->startOfMonth(); # (returns 2023-04-01) 
      # This will print the month's start date from the current date. 
      

    To Update your model, update your $fillable, and simple update/create will work

    # Example if User update
    $user->created_at = $lastMonth;
    $user->updated_at = $lastMonth;
    $user->save();
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search