-2

I am developing A web Application using Laravel-5.8 framework. I have a Model Class as shown below:

<?php
namespace App;
use App\Model;
class Gradesystem extends Model
{
   protected $table = 'grade_systems';
}  

Also my Controller is shown below:

public function store(Request $request){
$request->validate([
  'grade_system_name' => 'required|string|max:255',
  'point' => 'required',
  'grade' => 'required',
  'from_mark' => 'required',
  'to_mark' => 'required',
]);
  $gpa = new Gradesystem;
  $gpa->grade_system_name = $request->grade_system_name;
  $gpa->point = $request->point;
  $gpa->grade = $request->grade;
  $gpa->from_mark = $request->from_mark;
  $gpa->to_mark = $request->to_mark;
  $gpa->save();
}

How do I validate, probably from the Model or the Controller between from_mark and to_mark. Also, from_mark should not be greater that or equal to to_mark. It must not allow a number that falls in the range of already existing value. For example if from_mark is 0 and to_mark is 49 are already in database. So, if a user enters from_mark or to_mark to be 30, it must not allow it.

How do I achieve this?

Thank you.

David
  • 166
  • 1
  • 10
ayobamilaye
  • 429
  • 2
  • 10
  • 25

2 Answers2

0

For custom Validations its better use Rule Objects, where you can implement the logic of your validation.

An Example:

<?php

namespace App\Rules;

use Illuminate\Contracts\Validation\Rule;

class Uppercase implements Rule
{
    /**
     * Determine if the validation rule passes.
     *
     * @param  string  $attribute
     * @param  mixed  $value
     * @return bool
     */
    public function passes($attribute, $value)
    {
        return strtoupper($value) === $value;
    }

    /**
     * Get the validation error message.
     *
     * @return string
     */
    public function message()
    {
        return 'The :attribute must be uppercase.';
    }
}

You can see the info in the Laravel documentation

Hope this can help you

David
  • 166
  • 1
  • 10
0

I did not understand entire validation you asked but this will help. With same way you can write any other validation on from_mark and to_mark.

 $validator = Validator::make($request->all(), [
 'grade_system_name' => 'required|string|max:255',
 'point' => 'required',
 'grade' => 'required',
 'from_mark' => 'required',
'to_mark' => 'required',
 ]);

if ($validator->fails()) {
 return redirect()->back()->withInput()->withErrors();
}

if ($request->get('from_mark') < $request->get('to_mark')) {
return redirect()->back()->withInput()->withErrors();  
}
Prashant Deshmukh.....
  • 2,244
  • 1
  • 9
  • 11