noblemfd

noblemfd

Member Since 10 Months Ago

Experience Points
29,360
Total
Experience

640 experience to go until the next level!

In case you were wondering, you earn Laracasts experience when you:

  • Complete a lesson — 100pts
  • Create a forum thread — 50pts
  • Reply to a thread — 10pts
  • Leave a reply that is liked — 50pts
  • Receive a "Best Reply" award — 500pts
Lessons Completed
1
Lessons
Completed
Best Reply Awards
0
Best Reply
Awards
  • start your engines Created with Sketch.

    Start Your Engines

    Earned once you have completed your first Laracasts lesson.

  • first-thousand Created with Sketch.

    First Thousand

    Earned once you have earned your first 1000 experience points.

  • 1-year Created with Sketch.

    One Year Member

    Earned when you have been with Laracasts for 1 year.

  • 2-years Created with Sketch.

    Two Year Member

    Earned when you have been with Laracasts for 2 years.

  • 3-years Created with Sketch.

    Three Year Member

    Earned when you have been with Laracasts for 3 years.

  • 4-years Created with Sketch.

    Four Year Member

    Earned when you have been with Laracasts for 4 years.

  • 5-years Created with Sketch.

    Five Year Member

    Earned when you have been with Laracasts for 5 years.

  • school-in-session Created with Sketch.

    School In Session

    Earned when at least one Laracasts series has been fully completed.

  • welcome-newcomer Created with Sketch.

    Welcome To The Community

    Earned after your first post on the Laracasts forum.

  • full-time-student Created with Sketch.

    Full Time Learner

    Earned once 100 Laracasts lessons have been completed.

  • pay-it-forward Created with Sketch.

    Pay It Forward

    Earned once you receive your first "Best Reply" award on the Laracasts forum.

  • subscriber Created with Sketch.

    Subscriber

    Earned if you are a paying Laracasts subscriber.

  • lifer Created with Sketch.

    Lifer

    Earned if you have a lifetime subscription to Laracasts.

  • evangelist Created with Sketch.

    Laracasts Evangelist

    Earned if you share a link to Laracasts on social media. Please email [email protected] with your username and post URL to be awarded this badge.

  • chatty-cathy Created with Sketch.

    Chatty Cathy

    Earned once you have achieved 500 forum replies.

  • lara-veteran Created with Sketch.

    Laracasts Veteran

    Earned once your experience points passes 100,000.

  • 10k-strong Created with Sketch.

    Ten Thousand Strong

    Earned once your experience points hits 10,000.

  • lara-master Created with Sketch.

    Laracasts Master

    Earned once 1000 Laracasts lessons have been completed.

  • laracasts-tutor Created with Sketch.

    Laracasts Tutor

    Earned once your "Best Reply" award count is 100 or more.

  • laracasts-sensei Created with Sketch.

    Laracasts Sensei

    Earned once your experience points passes 1 million.

  • top-50 Created with Sketch.

    Top 50

    Earned once your experience points ranks in the top 50 of all Laracasts users.

Level 6
29,360 XP
Oct
23
2 days ago
Activity icon

Replied to How To Prevent A Final Score From Exceeding Rating Limit

@snapey - I don't understand what you mean

Activity icon

Started a new Conversation How To Prevent A Final Score From Exceeding Rating Limit

In my Laravel-5.8, I have three models:

  1. GoalType

  2. RatingLimit

  3. Goal

     class GoalType extends Model
     {
       protected $table = 'goal_types';
       protected $primaryKey = 'id';
       protected $fillable = [
               'name',
           ];
    
          return $this->hasMany('App\Models\Goal');
       }
     }
    
    class RatingLimit extends Model
    {
        protected $table = 'rating_limits';
        protected $primaryKey = 'id';
        protected $fillable = [
               'max_rating_percent',
               'goal_type_id',
           ];
    
       public function goaltype()
       {
           return $this->belongsTo('App\Models\lGoalType','goal_type_id');
       }
     }
    
    class Goal extends Model
    {
       protected $table = 'goals';
       protected $fillable = [
                   'id',
                   'goal_type_id',
                   'inititial_score',
                    'final_score',
               ]; 
    
       public function goaltype()
       {
           return $this->belongsTo('App\Models\GoalType','goal_type_id');
       }  
    }
    

At setting, the admin set max_rating_percent (it has integer value) RatingLimit for each GoalType

Each GoalType will have one RatingLimit. One GoalType can have Many Goal, but a Goal can only have one goal Type.

Controller

public function index()
{
    $employeeId = Auth::user()->employee_id;
    $goals = Goal::where('employee_id', $employeeId)->get();
    return view('goals.index')->with('goals', $goals);
}

 public function updateWeight(Request $request, $id)
 {

           $goal                           = Goal::find($id);  
    
            $goal->finalscore    = $request->final_score;             
            $goal->save();

            Session::flash('success', 'Comment is Successfully Updated');
            return redirect()->back();                                               
  }

index.blade

        <table class=" table table-bordered table-striped">
            <thead>
                <tr>
                    <th>
                        Goal Type
                    </th>
                    <th>
                        Initial Score
                    </th>
                </tr>
            </thead>
            <tbody>                    
                @foreach($goals as $key => $goal)
                <tr>
                        <td>
                            {{$goal->goaltype->name ?? '' }}
                        </td>    
                        <td>
                            {{$goal->initial_score ?? '' }}
                        </td>  
                        <td>
                                <a class="btn btn-xs btn-warning" data-toggle="modal" data-target="#final_score_emp{{ $goal->id }}" data-original-title="Comment"> 
                                   <i class="fas text-white">Add Final Score</i>
                                </a>
                       </td>
                </tr>
              @endforeach
        </tbody>
          </table>

modal

                        <div class="modal fade" id="final_score_emp{{ $goal->id }}" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
                            <div class="modal-dialog">
                                <div class="modal-content">
                                <form action="{{route('appraisal.appraisal_mid_year_setups.employee_mid_year_comment',['id'=>$goal->id])}}" method="post" enctype="multipart/form-data" id="review_comment-form">
                                {{ csrf_field() }}
                                <div class="modal-header">
                                    Self-Review Comment
                                </div>
                                <div class="col-md-12">
                                    <div class="form-group">
                                        <label class="control-label">Comment:<span style="color:red;">*</span></label>
                                          <input type="text" name="final_score" placeholder="Enter score" class="form-control comment">
                                    </div>
                                </div>                                 
                                <div class="modal-footer">
                                    <button  type="submit" id="review_comment_btn-submit" class="btn btn-success btn-ok">Save</button>
                                </div>
                                </form>
                                </div>
                            </div>
                        </div>

When the employee clicks Add Score on the index view blade, it displays a modal form. In the modal form is a text input for score.

What I want to achieve is that on keypress or keyup when the user is typing score, the system should check if the score is more than the max_rating_percent for that goal_type_id, it should display a message or alert that you cannot exceed the max_rating_percent. Considering goal_type_id

final_score <= initial_score + (initial_score * max_rating_percent/100)

How do I achieve this?

Thanks

Activity icon

Replied to Eloquent Query Not Giving Correct Result

Thanks so much everyone. Problem solved

Activity icon

Started a new Conversation Eloquent Query Not Giving Correct Result

I have this query:

        $companyId                = Auth::user()->company_id;
        $userId                     = Auth::user()->id;
        $employeeId               = Auth::user()->employee_id;
        $employeeCode               = Auth::user()->employee_code;
        $identities                 = DB::table('appraisal_identity')->select('id')->where('company_id', $companyId)->where('is_current', 1)->first();

This is the query that should yield final result:

$goals                      = Goal::where('employee_id', $employeeId)->where('appraisal_identity_id', $identities->id)->where('is_approved', 3)->orWhere('is_visible', 0)->whereNull('deleted_at')->orderBy('goal_type_id')->get();

I want to display the goals dor the logged in empoyee (current user). In the goals table, for the employee, is_approved = 3 or is_visible =0.

I mean

$goals                      = Goal::where('employee_id', $employeeId)->where('appraisal_identity_id', $identities->id)->where('is_approved', 3)->orWhere('is_visible', 0)->whereNull('deleted_at')->orderBy('goal_type_id')->get();

is not giving the desired result But I see from the result that the query bypassed where('employee_id', $employeeId) and display the result for all the employees and not just the logged in user.

How do I correct this?

Thanks

Activity icon

Replied to How To Disable Weekend In Datepicker

@dhanjay_bhardwaj - I now use jquery-ui datepicker for my Laravel

          <div class="col-sm-4">
            <div class="form-group">
                <label>Holiday Date:<span style="color:red;">*</span></label>
                <div class="input-group">
                <div class="input-group-prepend">
                  <span class="input-group-text"><i class="far fa-calendar-alt"></i></span>
                </div>                        
                    <input type="text" class="form-control holiday_date" placeholder="dd/mm/yyyy" readonly autocomplete="off" name="holiday_date" value="{{old('holiday_date')}}" >
                </div>

            </div>
          </div>    

Jquery

<script type="text/javascript">
        $(function () {
            $( '.holiday_date' ).datepicker({
                dateFormat: 'dd-mm-yy',
                changeMonth: true,
                changeYear: true,     
                showAnim: 'slideDown',
                duration: 'fast',   
                yearRange: new Date().getFullYear() + ':' + new Date().getFullYear(),
                beforeShowDay: $.datepicker.noWeekends
            });

    });
</script> 	

This works for me. But you must have jquery-ui.js

Oct
22
3 days ago
Activity icon

Replied to How To Resolve Invalid Argument Supplied For Foreach()

@sinnbeck - If I want to get id, name, parent_instead of just id. How do I change:

$ids  = GoalType::where('company_id', $userCompany)->pluck('id');

to achieve that?

Activity icon

Replied to How To Resolve Invalid Argument Supplied For Foreach()

@michaloravec - I will get better with time. Thanks

Activity icon

Replied to How To Resolve Invalid Argument Supplied For Foreach()

@sinnbeck - You are correct. There could be more than one record with $userCompany

Activity icon

Replied to How To Resolve Invalid Argument Supplied For Foreach()

@michaloravec - There are several issues I have resolved through the documentations

Activity icon

Replied to How To Resolve Invalid Argument Supplied For Foreach()

@sinnbeck - How? Please I dont understand

Activity icon

Replied to Leave Resumption A Href Not Responding

@automica - Thanks so much. I dd('hello'); in several places and found that it skipped where a condition is not fulfilled. Thanks

Activity icon

Replied to Leave Resumption A Href Not Responding

@automica - I did. I omitted it. See the complete code:

public function activate_leave_resumption()
{
   $userCompany = Auth::user()->company_id;
   $userEmployee = Auth::user()->employee_id;    
   $userId = Auth::user()->id;
    $leaverequest                                   = HrLeaveRequest::where('employee_id', $userEmployee)->where('is_resumption_activated', 0)->where('leave_status', 4)->where('resumption_date', '<=', Carbon::now()->toDateString())->orderBy('created_at', 'DESC')->first();
    $leaverequest->is_resumption_activated          = 1;
    $leaverequest->resumption_activation_date       = date("Y-m-d H:i:s");
    $leaverequest->save();

            Session::flash('success', 'Leave Resumption is Successfully Activated');
            return redirect()->back();
}

view

<div class="panel-heading clearfix">
    <div class="container-fluid">
        <div style="margin-bottom: 10px;" class="row">
            <div class="col-lg-12">
                <a class="btn btn-info float-right"  href ="{{ route('service.leave_requests.activateLeaveResumption')}}">
                    Resumption Activation
                </a>
            </div>
        </div>
    </div>
</div>  

route:

Route::group(['prefix' => 'service', 'as' => 'service.', 'namespace' => 'Service', 'middleware' => ['auth']], function () {
    Route::get('service/leave_requests/activate_leave_resumption', '[email protected]_leave_resumption')->name('leave_requests.activateLeaveResumption');
       

});

When I dd('hello');

I got:

"hello"
Activity icon

Started a new Conversation Leave Resumption A Href Not Responding

I gave this code:

Controller

public function activate_leave_resumption()
{
   $userCompany = Auth::user()->company_id;
   $userEmployee = Auth::user()->employee_id;    
   $userId = Auth::user()->id;
    $leaverequest                                   = HrLeaveRequest::where('employee_id', $userEmployee)->where('is_resumption_activated', 0)->where('leave_status', 4)->where('resumption_date', '<=', Carbon::now()->toDateString())->orderBy('created_at', 'DESC')->first();
    $leaverequest->is_resumption_activated          = 1;
    $leaverequest->resumption_activation_date       = date("Y-m-d H:i:s");
    $leaverequest->save();

            Session::flash('success', 'Leave Resumption is Successfully Activated');
            return redirect()->back();
}

view

<div class="panel-heading clearfix">
    <div class="container-fluid">
        <div style="margin-bottom: 10px;" class="row">
            <div class="col-lg-12">
                <a class="btn btn-info float-right"  href ="{{ route('service.leave_requests.activateLeaveResumption')}}">
                    Resumption Activation
                </a>
            </div>
        </div>
    </div>
</div>  

route:

Route::group(['prefix' => 'service', 'as' => 'service.', 'namespace' => 'Service', 'middleware' => ['auth']], function () {
    Route::get('service/leave_requests/activate_leave_resumption', '[email protected]_leave_resumption')->name('leave_requests.activateLeaveResumption');
       

});

When Resumption Activation "ahref" is submitted, nothing is happening.

No error in the Log and the browser console

How do I rectify this?

Thanks

Oct
21
4 days ago
Activity icon

Replied to How To Resolve Invalid Argument Supplied For Foreach()

Resolved. I used get()->toArray().

Thanks

Activity icon

Started a new Conversation How To Resolve Invalid Argument Supplied For Foreach()

I have this code in Laravel-5.8 controller:

     $goaltypes                  = GoalType::where('company_id', $userCompany)->get();
     foreach($goaltypes as $goaltype){
         $goaltypedetails            = Goal::whereIn('goal_type_id', [$goaltype->id])->where('employee_id', $userEmployee)->get();
     }

I got this error:

Invalid argument supplied for foreach()

and it points at:

foreach($goaltypes as $goaltype){

dd($goaltypes); gives me:

  #original: array:14 [▼
    "id" => 8
    "name" => "Employee Targets"
    "updated_by" => 2
    "created_at" => "2020-01-22 13:23:26"
    "updated_at" => "2020-02-25 14:12:30"
    "is_active" => 1
  ]

How do I get this resolved?

Thanks

Activity icon

Replied to How To Automatically Insert Data While Trying To Render A View Blade

@snapey - I'm just stuck now. Is there any other way out of this?

Oct
20
5 days ago
Activity icon

Replied to How To Automatically Insert Data While Trying To Render A View Blade

@snapey - users have already entered data, so it will be difficult for me to do that now. I just need to find a way out

Activity icon

Replied to How To Automatically Insert Data While Trying To Render A View Blade

@snapey - What happened is that at the beginning of the year goals are setup in Goals model except where is_visible = 1. So towards the end of the year, when the employee wants to view the setup goals, the remaining ones where is_visible =1 should automatically be added to it's goals.

That's why I'm looking for a way to add:

     $goaltypes                   = GoalType::where('is_visible', 1)->pluck('id');
     $goaldetails                      = Goal::whereIn('id', $goaltypes)->where('employee_id', $userEmployee)->get();
     if($goaldetails){
         foreach($goaltypes as $goaltype){
              $data = new Goal();

             $data->goal_type_id                     = $goaltype;                
             $data->employee_id          		 = $userEmployee;
             $data->save();
     	}     
     }

to :

public function index()
{
    $userID                     = Auth::user()->id;
    $userEmployee               = Auth::user()->employee_id;    

        $goals                  = Goal::where('employee_id', $userEmployee)->get();   

    return view('inde')
                ->with('goals', $goals)
                ->with('goaltypes', $goaltypes);                     
}
Activity icon

Replied to How To Automatically Insert Data While Trying To Render A View Blade

@tykus - Anytime somebody visits:

             <li class="nav-item">
               <a href="{{ route("goals.index") }}" class="nav-link {{ request()->is('goals') || request()->is('goals/*') ? 'active' : '' }}">
                 <i class="far fa-circle nav-icon"></i>
                 <p>
                   <span>Goals</span>
                 </p>
               </a>
             </li>	

Which is:

public function index(){
}
Activity icon

Replied to How To Automatically Insert Data While Trying To Render A View Blade

@tykus - No. Is there a better way to do it. I just want to check if the condition is fulfilled, then it inserts before it renders the view else it just render the view like that.

Thank

Activity icon

Started a new Conversation How To Automatically Insert Data While Trying To Render A View Blade

I have this controller :

public function index()
{
    $userID                     = Auth::user()->id;
    $userEmployee               = Auth::user()->employee_id;    

        $goals                  = Goal::where('employee_id', $userEmployee)->get();   

    return view('inde')
                ->with('goals', $goals)
                ->with('goaltypes', $goaltypes);                     
}

This is rendered as get method into the view page and it's working fine.

But I want to insert some data based on condition into the same model (Goal) before the page is rendered using the same model.

If the condition is fulfilled it inserts and render

$goals = Goal::where('employee_id', $userEmployee)->get();

if its not fulfilled, it just renders:

$goals = Goal::where('employee_id', $userEmployee)->get();

This is the insert I want to add to the controller:

     $goaltypes                   = GoalType::where('is_visible', 1)->pluck('id');
     $goaldetails                      = Goal::whereIn('id', $goaltypes)->where('employee_id', $userEmployee)->get();
     if($goaldetails){
         foreach($goaltypes as $goaltype){
              $data = new Goal();

             $data->goal_type_id                     = $goaltype;                
             $data->employee_id          		 = $userEmployee;
             $data->save();
     	}     
     }

How do I achieve it?

Thanks

Activity icon

Replied to How To Retrieve Uploaded File In Edit View Blade

@automica - When I made it as:

$filePath = storage_path().\documents\mid_year\.$goal->employee_mid_year_attachment;  

I got this error:

syntax error, unexpected '.', expecting identifier (T_STRING)

Activity icon

Replied to How To Retrieve Uploaded File In Edit View Blade

@automica - I have added the slash:

 $filePath = storage_path().'\documents\mid_year\'.$goal->employee_mid_year_attachment;

and the error is still there. See the the error:

unexpected: identifier after: String ''\documents\mid_year'.$goal->employee_mid_year_attachment;

Activity icon

Replied to How To Retrieve Uploaded File In Edit View Blade

@automica - The slash is there, I don't know why I didn't include it. See it

$filePath = storage_path().'\documents\mid_year'.$goal->employee_mid_year_attachment;

Activity icon

Replied to How To Retrieve Uploaded File In Edit View Blade

@automica - How do you mean. @automica said I should change it to :

$filePath = storage_path().'\documents\mid_year\'.$goal->employee_mid_year_attachment;
Activity icon

Replied to How To Retrieve Uploaded File In Edit View Blade

@a4ashraf - Error occur.

Unexpected identifier after '\documents\mid_year'.$goal->employee_mid_year_attachment;

Activity icon

Replied to How To Retrieve Uploaded File In Edit View Blade

@a4ashraf - dd($filePath); gives:

"C:\xampp\htdocs\staffapp\storage/documents/mid_year/1469860112.PNG"

"C:\xampp\htdocs\staffapp\storage/documents/mid_year/1469860112.PNG"
Activity icon

Replied to How To Retrieve Uploaded File In Edit View Blade

@a4ashraf - Mine is:

/public/storage/documents/mid_year/.$goal->employee_mid_year_attachment
Oct
19
6 days ago
Activity icon

Replied to How To Retrieve Uploaded File In Edit View Blade

@a4ashraf - I got this error:

Undefined index: extension

and this is highlighted:

$fileType = $info['extension'];

Activity icon

Started a new Conversation How To Retrieve Uploaded File In Edit View Blade

I ham uploading files like excel and images.

I have successfully inserted it. I saved the file name in the table and the file itself in a directly. Where I have a problem is how to retrieve the file in the edit view blade.

Controller

public function update_employee_mid_year_comment(UpdateSelfReviewRequest $request, $id) {
    $goal = Goal::find($id);  

    $goal->employee_mid_year_comment = $request->employee_mid_year_comment;

    if ($request->employee_mid_year_attachment != "") {
        $employee_mid_year_attachment = $request->file('employee_mid_year_attachment');
        $new_name = rand() . '.' . $employee_mid_year_attachment->getClientOriginalExtension();
        $employee_mid_year_attachment->move(public_path('storage/documents/mid_year'), $new_name);
        $goal->employee_mid_year_attachment = $new_name;
    }
    $goal->save();

    DB::commit();

    Session::flash('success', 'Comment is Successfully Updated');
    return redirect()->back();
}

I am using a modal form:

edit.blade


<div class="modal fade" id="edit{{ $goal->id }}" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog">
    <div class="modal-content">
        <form action="{{route('mid_year_setups.update_employee_mid_year_comment',['id'=>$goal->id])}}" method="post" enctype="multipart/form-data" id="edit_comment-form">
        {{ csrf_field() }}
        <div class="modal-header">
            Update Self-Review Comment
        </div>
        <div class="col-md-12">
            <div class="form-group">
            <label class="control-label">Comment:<span style="color:red;">*</span></label>
            <textarea rows="2" name="employee_mid_year_comment" class="form-control" placeholder="Enter Comment here" value="{{old('employee_mid_year_comment',$goal->employee_mid_year_comment)}})}}" required data-validation-required-message="This field is required">{{old('employee_mid_year_comment',$goal->employee_mid_year_comment)}}</textarea>
            </div>
        </div>
        <div class="col-md-12">
            <div class="form-group">
            <label class="control-label"> Attachment:</label>
            <div class="custom-file">
                <div class="custom-file">
                <input value="{{old('employee_mid_year_attachment',$goal->employee_mid_year_attachment)}}" type="file" name="employee_mid_year_attachment" class="custom-file-input" id="customFile">
                <label class="custom-file-label" for="exampleInputFile">Choose file</label>
                </div>
            </div>
            </div>
        </div>
        <div class="modal-footer">
            <button type="submit" id="edit_comment_btn-submit" class="btn btn-success btn-ok">Save</button>
        </div>
        </form>
    </div>
    </div>
</div>

The file name is employee_mid_year_attachment while the file path is: storage/documents/mid_year

When I rendered the edit view blade, it didn't retrieve the attached document. How do I achieve this?

Thanks

Oct
17
1 week ago
Activity icon

Replied to How To Prevent The Delete Of Table Row That Has It's Id In Another Table

@tray2 - I know about, but I was trying to prevent the use of constraints

Activity icon

Started a new Conversation How To Prevent The Delete Of Table Row That Has It's Id In Another Table

I have these models:

class GoalType extends Model
{
    protected $table = 'goal_type';
    protected $primaryKey = 'id';
    protected $fillable = [
              'name',
          ];

    public function goals()
    {
       return $this->hasMany('App\Goal');
    }
}

class Goal extends Model
{
    protected $table = 'goals';
    protected $fillable = [
              'id',
              'goal_type_id',
              'goal_title',
       ];

    public function goaltype()
    {
        return $this->belongsTo('App\GoalType','goal_type_id');
    }
}

Controller: GoalType

public function destroy(Request $request, $id)
{
    DB::beginTransaction(); 
    try{
        $goaltype = GoalType::find($id);
        $goaltype->delete();
        Session::flash('success', Goal deleted successfully.');
        return redirect()->route('goal_types.index');
  }          
    catch (Exception $exception) 
    { 
        Log::error($exception); 
        DB::rollback();
        Session::flash('error', 'Action failed! Please try again');
        return redirect()->route('goal_types.index'); 
    }              
}

The model GoalType has it's foreign key in Goal. The code above for delete is working. But without using DB foreign key relationship, if id (goal_type_id) is being used in Goal, it should prevent delete and display a message.

How do I achieve this?

Oct
16
1 week ago
Activity icon

Replied to Custom Validation Is Not Working For Update

@tykus - I got this error:

Trying to get property 'id' of non-object

How do I do this:

You could modify the rule above to accept a model instance instead of the id if you prefer

Activity icon

Replied to Custom Validation Is Not Working For Update

@tykus - I got this error:

unexpected =>

and it underlines this:

->when($this->ignoredId, fn ($builder) => $builder->where('id', '<>', $this->ignoredId))
Activity icon

Replied to Custom Validation Is Not Working For Update

@a4ashraf - The one I've used is not having issue. But when I want to update the same data then I got the validation error. It works fine with create (insert)

Activity icon

Started a new Conversation Custom Validation Is Not Working For Update

I have this custom validation:

namespace App\Rules;

use App\Models\Rating;
use Illuminate\Contracts\Validation\Rule;

class AllowedGrade implements Rule
{
    public function __construct()
    {
        //
    }

    public function passes($attribute, $value)
    {
        return Rating::where('mark_from', '<=', $value)
            ->where('mark_to', '>=', $value)
            ->doesntExist();
    }

    public function message()
    {
        return 'The :attribute as score range is used.';
    }
}

Then I called it in Request Rules:

use App\Rules\AllowedGrade;

class UpdateRatingRequest extends FormRequest
{
    public function authorize()
    {
        return \Gate::allows('rating_edit');
    }

    public function rules()
    {
            'rating_description' => [
                'required',
                'string',
                'min:2',
                'max:50',               
                Rule::unique('appraisal_ratings', 'rating_description', 'company_id')->ignore($this->rating)
            ],
            'mark_from' => [
                'required',
                'numeric',
                'min:0',
                'max:500', 
                new AllowedGrade,
                Rule::unique('appraisal_ratings', 'mark_from', 'company_id')->ignore($this->rating)
            ], 
            'mark_to' => [
                'required',
                'numeric',
                'min:1',
                'max:500',   
                'gt:mark_from',
                 new AllowedGrade,
                Rule::unique('appraisal_ratings', 'mark_to', 'company_id')->ignore($this->appraisal_rating)
            ],             
        ];        
    }

    public function attributes()
    {
        return [
            'rating_description'                => 'Rating Text (Name)',
            'mark_from'                         => 'Min. Score',
            'mark_to'                           => 'Max. Score',                                           
        ];
    }     
}

I used this for route url: ->ignore($this->rating)

It works fine for create, but when I tried to update, I got the validation message:

The Min. Score as score range is used.
The Max. Score as score range is used.

which is quoted from here:

return 'The :attribute as score range is used.';

How do I make it work for update also?

Thanks

Activity icon

Replied to Data Did Not Submit Into The Dababase

@tykus - How do I do lessons in Laracast?

Activity icon

Replied to Data Did Not Submit Into The Dababase

@tykus - Thanks so much. I forgot to commit the transaction

Activity icon

Replied to Data Did Not Submit Into The Dababase

@sinnbeck - The same database, and all other things are going fine

Activity icon

Replied to Data Did Not Submit Into The Dababase

@tykus - Yes, correct connection. I can render other views and also the view from that same table

Activity icon

Replied to Data Did Not Submit Into The Dababase

@tykus - Yes:

  #table: "ratings"
  #primaryKey: "id"
  #fillable: array:12 [▼
    2 => "rating_value"
    3 => "mark_from"
    4 => "mark_to"
    5 => "is_highest"
    6 => "rating_description"
  ]

 #perPage: 15
 +exists: true
Activity icon

Started a new Conversation Data Did Not Submit Into The Dababase

In Laravel-5.8 project, I have these model:

class Rating extends Model
{
public $timestamps = false;
protected $table = 'ratings';

protected $primaryKey = 'id';
protected $fillable = [
              'mark_from',
              'mark_to',
              'is_highest',
              'rating_description',
          ];
}

Controller

public function store(StoreRatingRequest $request)
{
    $rating = Rating::create([
        'mark_from'                 => $request->mark_from,
        'mark_to'                   => $request->mark_to,
        'is_highest'                => $request->has('is_highest'),
        'rating_description'        => $request->rating_description,
    ]);          
}

I did the validation in Rules Request as shown above. The view blade is shown below:

view

           <form  action="{{route('ratings.store')}}" method="post" class="form-horizontal" enctype="multipart/form-data">
           {{csrf_field()}}
           <div class="card-body">
            <div class="form-body">
            <div class="row">                              
              <div class="col-12 col-sm-8">
                <div class="form-group">
                  <label class="control-label"> Rating Text (Name):<span style="color:red;">*</span></label>
                  <input  type="text" name="rating_description" placeholder="Enter rating text here: Under, Moderate, Good, ..." class="form-control" value="{{old('rating_description')}}">  
                </div>
              </div>
               <div class="col-12 col-sm-4">
                <div class="form-group">
                  <label class="control-label"> Min. Score (%):<span style="color:red;">*</span></label>
                  <input type="number" name="mark_from" placeholder="0,49,59, ..." class="form-control" value="{{old('mark_from')}}" min="0" max="500">  
                </div>
              </div>       
               <div class="col-12 col-sm-4">
                <div class="form-group">
                  <label class="control-label"> Max. Score (%):<span style="color:red;">*</span></label>
                  <input type="number" name="mark_to" placeholder="50,60,80, ..." class="form-control" value="{{old('mark_to')}}" min="1" max="500">  
                </div>
              </div>    
               <div class="col-12 col-sm-4">
                <div class="form-group">
                    <label class="control-label"> Highest Score?:</label><br>
                  <input type="checkbox" name="is_highest"  class="form-control" unchecked data-bootstrap-switch data-off-color="danger" data-on-color="success" data-off-text="NO" data-on-text="YES">
                </div>
              </div>                  


           </div>
         </div>
        </div>          
        <!-- /.card-body -->
        <div class="card-footer">
          <button type="submit" class="btn btn-primary">{{ trans('global.save') }}</button>
        </div>           
           
        </form>

When I submitted, nothing goes into the database. But when I dd($rating) in the controller after $rating = Rating::create, I got:

#attributes: array:11 [▼
  "mark_from" => "120"
  "mark_to" => "129"
  "is_highest" => false
  "rating_description" => "testings"
]

I also check console, but no error there.

How do I resolve this?

Thanks

Activity icon

Replied to Edit For Self Referencing ParentId Not Working As Expected

So sorry. I've resolved it. It suppose to be:

data-max_score and not data-max-score.

Thanks

Activity icon

Started a new Conversation Edit For Self Referencing ParentId Not Working As Expected

I have this self-referencing model in Laravel-5.8

I am using the same view blade for index, create and edit

class GoalType extends Model
{
  protected $table = 'goal_types';
  protected $primaryKey = 'id';
  protected $fillable = [
                'name',
                'company_id',
                'parent_id',
                'max_score',
            ];
  
  public function children()
  {
    return $this->hasMany('App\GoalType', 'parent_id');
  }
  
  public function parent()
  {
      return $this->hasOne(App\GoalType::class, 'id', 'parent_id');
  }

  public function company()
  {
      return $this->belongsTo('App\Models\Organization\OrgCompany','company_id');
  }
}

Controller

public function index()
{      
        $categories = GoalType::with('children')->where('company_id', $userCompany)->whereNull('parent_id')->get();
        return view('goal_types.index')->with('categories', $categories);      
}

view

index.blade

            <div class="card-body">
              <ul class="list-group">
                @foreach ($categories as $category)
                  <li class="list-group-item">
                    <div class="d-flex justify-content-between">
                      {{ $category->name }} 
                      <strong>{{ $category->max_score }}%</strong>
                      <div class="button-group d-flex">
                        <button type="button" class="btn btn-sm btn-primary mr-1 edit-category" data-toggle="modal" data-target="#editCategoryModal" data-id="{{ $category->id }}" data-name="{{ $category->name }}" data-max-score="{{ $category->max_score }}" data-parent-id="{{ $category->parent_id }}">Edit</button>
                      </div>
                    </div>

                    @if ($category->children)
                      <ul class="list-group mt-2">
                        @foreach ($category->children as $child)
                          <li class="list-group-item">
                            <div class="d-flex justify-content-between">
                                {{ $child->name }} 
                              <div class="button-group d-flex">
                               @can('goal_type_edit')
                                <button type="button" class="btn btn-sm btn-primary mr-1 edit-category" data-toggle="modal" data-target="#editCategoryModal" data-id="{{ $child->id }}" data-name="{{ $child->name }}">Edit</button>
                               @endcan
                              </div>
                            </div>
                          </li>
                        @endforeach
                      </ul>
                    @endif
                  </li>
                @endforeach
              </ul>
            </div>

edit.blade

              <form action="" method="POST">
                @csrf
                @method('PUT')
               <div class="modal-body">
                <div class="form-group">
                  <label class="control-label"> Parent Goal Type:</label>
                  <select class="form-control select2bs4" data-placeholder="Choose Parent Goal Type" tabindex="1" name="parent_id" style="width: 100%;">
                    <option value="">Select Parent Goal Type</option>
                    @foreach ($categories as $category)
                      <option value="{{ $category->id }}">{{ $category->name }}</option>
                    @endforeach
                  </select>
                </div>                  
                  <div class="form-group">
                     <label class="control-label"> Name:<span style="color:red;">*</span></label>
                    <input type="text" name="name" class="form-control" value="" placeholder="Category Name" required>
                  </div>
                <div class="form-group">
                    <label class="control-label"> Max. Weight (%):</label>
                  <input type="number" name="max_score" class="form-control" value="" step="0.01" placeholder="Enter maximum weight here: 15, 50, 75 etc" style="width: 100%;">
                </div>                       
               </div>

                <div class="modal-footer">
                  <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                  <button type="submit" class="btn btn-primary">Update</button>
                </div>
              </div>
              </form>

javascript

    <script type="text/javascript">
      $('.edit-category').on('click', function() {
        var id = $(this).data('id');
        var name = $(this).data('name');
        var parentId = $(this).data('parent_id');
        var max_score = $(this).data('max_score');
        var url = "{{ url('goal_types') }}/" + id;

        $('#editCategoryModal form').attr('action', url);
        $('#editCategoryModal form input[name="name"]').val(name);
        $('#editCategoryModal form select[parentId="parent_id"]').val(parentId).change();
        $('#editCategoryModal form input[name="max_score"]').val(max_score);
      });
    </script>

When I click on Edit button to load the Modal edit page, I observe that nothing is load in max_score. Yet there is data in the database.

Only

$('#editCategoryModal form input[name="name"]').val(name);

retrieve the data from the database.

How do I make:

$('#editCategoryModal form input[name="max_score"]').val(max_score);

to retrieve data from the database?

Thanks

Oct
14
1 week ago
Activity icon

Started a new Conversation How To Validate Grading System In Model And Controller

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';

    protected $fillable = [
        'point',
        'grade',
        'from_mark',
        'to_mark',
    ];
}  

Also my Controller is shown below:

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

The result is something similar to this:

Grade	Point	From_Mark	To_Marks
A+	5	80		100
A	4	70		79
A-	3.5	60		69
B	3	50		59
C	2	40		49
D	1	33		39
F	0	0		32

I know about the normal validation, whereby each column is unique. But I need something different. I want to perform a kind of validation between two fields. That is, between from_mark and to_mark. For instance, if in the first row I have from_mark: 80 and to_mark: 100, then from_mark or to_mark from any of the other rows should not be between what is already present in the database.

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.

Oct
13
1 week ago
Activity icon

Replied to Data Failed To Save Into The Database

@snapey - Okay, thanks. How will the Controller now insert it?