Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

syntaxerron's avatar

Laravel Validation

Any tips on validating a record that can be reused on other classes?

Example:

public function approve($id) {
	$record = Record::findOrFail($id);

	if($record->cancelled_at != null) {
		abort(422);
	}

	if($record->submitted_at == null) {
		abort(422);
	}

	if($record->approved_at != null) {
		abort(422);
	}

	$record->approved_at = now();
	$record->save();
}

I am thinking on creating custom helper function, but, is there any best practices without reusing code for validation on other classes?

0 likes
5 replies
MarianoMoreyra's avatar
Level 25

Hi @erron

As suggested before, you could create a Trait with that code inside. You could even call that Trait HasApproval or something like that.

As that Trait will be assigned to a Model, you won't need to fetch it from DB as it will be already done, so you would end up with something like:

<?php

namespace App\Traits;

trait HasApproval
{
    public function approve()
    {
        if($this->cancelled_at != null) {
		abort(422);
	}

	if($this->submitted_at == null) {
		abort(422);
	}

	if($this->approved_at != null) {
		abort(422);
	}

	$this->approved_at = now();
	$this->save();
    }
}

then at the Models where you want to apply this, you would just do:

<?php

namespace App\Models;

use App\Traits\HasApproval;

class SomeModel extends Model
{
     use HasApproval;

     // your model code here....
}

So now you can call the approve() method on that Model and it will validate and save or abort with 422 code.

Hope this works for you!

1 like
assoft's avatar

Maybe like this;

public function approve($id) 
{
	abort_if(!is_null($this->cancelled_at), 422);
	abort_if(!is_null($this->submitted_at), 422);
	abort_if(!is_null($this->approved_at), 422);
	
	$this->approved_at = now();
	$this->save();
}
1 like
MarianoMoreyra's avatar

You are welcome @erron

If this finally works for you, please consider marking the question as solved to help others find the solution too.

Please or to participate in this conversation.