James Riady James Riady - 3 years ago 199
PHP Question

Laravel store data auto increment

class PostController extends Controller{
public $grupID = 1;
public function store(Request $request)
{
$post = new Post();
$post->GroupID = 'POST-' . $this->grupID;
$post->save();
return response()->json($post);
$this->grupID++;
}
}


Database Structur

public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->increments('id');
$table->integer('PostTypeID');
$table->string('GroupID', 100)->nullable();
$table->timestamps();
});
}


I want to make the groupID auto increment, but it always return 'POST-1'.

Answer Source
class PostController extends Controller{
   public function store(Request $request)
   {
      $lastValue = DB::table('posts')->orderBy('GroupID', 'desc')->first();
      if(count($lastValue) < 1){
        $post->GroupID = 'POST-' . 1;    
      }else{
        $last = substr($lastValue->GroupID, strrpos($lastValue->GroupID, '0') + 1);
        $post->GroupID = 'POST-' . $last + 1;
      }
      $gid = $post->GroupID;
      $post->save();
      return response()->json($post);
   }
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download