noblemfd

noblemfd

Member Since 2 Months Ago

Experience Points
6,140
Total
Experience

3,860 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
0
Lessons
Completed
Best Reply Awards
0
Best Reply
Awards
  • start-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-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-token Created with Sketch.

    Subscriber

    Earned if you are a paying Laracasts subscriber.

  • lifer-token Created with Sketch.

    Lifer

    Earned if you have a lifetime subscription to Laracasts.

  • lara-evanghelist 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 2
6,140 XP
Feb
25
20 hours ago
Activity icon

Replied to Load And Populate 2 Textboxes Based On Dropdown Selection

Sorry to bother you once more. If I have the fields like this:

  <input type="text" value="max_score" class="form-control" >
  <input type="text" value="total_weighted_score" class="form-control">

These are the url:

appraisal_goals/maxScore
appraisal_goals/empScore

How do I represent each in the jQuery you have written?

Thanks

Activity icon

Started a new Conversation Load And Populate 2 Textboxes Based On Dropdown Selection

It's not so long that I started Laravel. I just want to ask how I can populate two (2) textboxes when i select a data in a dropdown.

I have two tables: goal_types and goals

Model: GoalType

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\Models\GoalType', 'parent_id');
}

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

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

Model: Goal

class Goal extends Model
{
   protected $table = 'goals';

   protected $fillable = [
              'id',
              'goal_type_id',
              'employee_id',
              'company_id',
              'weighted_score',
              'goal_title',
          ];

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

goal_types has a foreign key goal_type_id in goals. This is used to generate the dropdown in goal.create view blade

GoalController

public function create()
{
    $userCompany = Auth::user()->company_id;
    $userEmployee = Auth::user()->employee_id;
    
     $goaltypes = AppraisalGoalType::with('children')->where('company_id', $userCompany)->whereNull('parent_id')->get();
    
    return view('goals.create')
            ->with('goaltypes', $goaltypes)
}

public function store(StoreAppraisalGoalRequest $request)
{      
    $userCompany = Auth::user()->company_id;
    $employeeId = Auth::user()->employee_id;

    try {
        $goal = new AppraisalGoal();
        $goal->goal_type_id             = $request->goal_type_id;
        $goal->employee_id              = $employeeId; 
        $goal->weighted_score           = $request->weighted_score;
        $goal->goal_title               = $request->goal_title;                   
        $goal->save();
         }
         
            Session::flash('success', 'Goal is created successfully');
            return redirect()->route('goals.index');
    } catch (Exception $exception) {
                 Session::flash('danger', 'Goal creation failed!');
            return redirect()->route('goals.index');
    }
}

goals: create.blade

 <form  action="{{route('goals.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-6">
            <div class="form-group">
              <label class="control-label"> Goal Type:<span style="color:red;">*</span></label>
              <select id="goal_type" class="form-control" name="goal_type_id">
                <option value="">Select Goal Type</option>

                @foreach ($goaltypes as $goaltype)
                  <option hidden value="{{ $goaltype->id }}" {{ $goaltype->id == old('goaltype_id') ? 'selected' : '' }}>{{ $goaltype->name }}</option>

                  @if ($goaltype->children)
                    @foreach ($goaltype->children as $child)
                      <option value="{{ $child->id }}" {{ $child->id == old('category_id') ? 'selected' : '' }}>&nbsp;&nbsp;{{ $child->name }}</option
                    @endforeach
                  @endif
                @endforeach
              </select>
            </div>
          </div>    
          <div class="col-12 col-sm-6">
            <div class="form-group">
              <label class="control-label"> Goal Title:<span style="color:red;">*</span></label>
              <input  type="text" name="goal_title" placeholder="Enter goal title here" class="form-control">
            </div>
          </div>
            
          <div class="col-sm-12">
            <div class="form-group">
                <label>Goal Description</label>
                <textarea rows="2" name="goal_description" class="form-control" placeholder="Enter Goal Description here ..."></textarea>
            </div>
          </div>
          <div class="col-12 col-sm-6">
            <div class="form-group">
              <label class="control-label"> Weight(%):<span style="color:red;">*</span></label>
              <input  type="number" name="weighted_score" placeholder="Enter weighted score here" class="form-control" max="120">
            </div>
          </div>  

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

Once the user select data from the group_type_id, I want the application to do two things:

  1. It should load max_score from goal_types table based on the selected goal_type_id and load it into a textbox called max_score.

  2. It should sum all the weighted_score in goals table based on goal_type_id selected and load it into a textbox called employee_score.

These two textboxes should be hidden and not to be saved in the database.

How do I achieve this?

Thank you

Feb
24
1 day ago
Activity icon

Replied to How To Only Display <a> When A Field Is Not NULL

It works. There was a typo error

Activity icon

Replied to How To Only Display <a> When A Field Is Not NULL

It is longtext, and it is NULL by default

Activity icon

Replied to How To Only Display <a> When A Field Is Not NULL

It displays everything (both the manager_employee_goal_comment fields that have value and the one that are null).

Feb
21
4 days ago
Activity icon

Started a new Conversation Rule Request Validation Error

I have this Project in Laravel-5.8 that validates:

goal_type_id, appraisal_identity_id, employee_id as unique in appraisal_goals using Rule Request.

goal_type_id, appraisal_identity_id, employee_id are foreign keys

Model

protected $fillable = [
              'id',
              'goal_type_id',
              'appraisal_identity_id',
              'employee_id',
              'company_id',
          ];

StoreAppraisalGoalReques

public function rules()
{
    return [
        'goal_type_id' => [
            'required',              
            Rule::unique('appraisal_goals', 'goal_type_id', 'appraisal_identity_id', 'employee_id')
        ],       
       
    ];
} 

public function messages()
{
    return [
        'goal_type_id.required'                 => 'Please enter the Goal Type!',
        'goal_type_id.unique'                   => 'Goal Type already exists. Please enter a unique Goal Type.!',
    ];
}

Controller

public function store(StoreAppraisalGoalRequest $request)
{

    $userCompany = Auth::user()->company_id;
    $employeeId = Auth::user()->employee_id;
      $identities = DB::table('appraisal_identity')->select('id','appraisal_name')->where('company_id', $userCompany)->where('is_current', 1)->first();
    try {
        $goal = new AppraisalGoal();
        $goal->goal_type_id             = $request->goal_type_id;
        $goal->appraisal_identity_id    = $request->appraisal_identity_id;
        $goal->employee_id              = $employeeId;  
        $goal->is_active                = 1;               
        $goal->save();

        foreach ( $request->activity as $key => $activity){

            $goaldetail = new AppraisalGoalDetail();

            $goaldetail->kpi_description            = $request->kpi_description[$key];
            $goaldetail->appraisal_doc              = $request->application_doc[$key];
            $goaldetail->activity                   = $request->activity[$key];  
            $goaldetail->start_date                 = $startDate ->toDateTimeString();
            $goaldetail->end_date                   = $endDate->toDateTimeString();                 
            $goaldetail->save();
         }
         
            Session::flash('success', 'Appraisal Goal is created successfully');
            return redirect()->route('appraisal.appraisal_goals.index');
    } catch (Exception $exception) {
            Session::flash('danger', 'Appraisal Goal creation failed!');
            return redirect()->route('appraisal.appraisal_goals.index');
    }
}

An employee can only have one goal_type_id relating to appraisal_identity_id and employee_id in the appraisal_goals table.

Employee a successfully did this. But when another employee logs in and submit, I got this error:

Goal Type already exists. Please enter a unique Goal Type.!

Note this doesn't exist.

as shown in the rules validation custom message:

How do I resolve this?

Thank you.

Activity icon

Started a new Conversation How To Prevent Parent Id Of A Foreign Key From Being Deleted

I have a project on Laravel

product_id is a foreign key in invoice.

  1. How do I prevent product from being deleted if the product_id is being referenced in invoice.

  2. Also how do I display a message to inform the user on this?

Product Controller

public function destroy($id)
{
    $product = Product::find($id);
    $product->delete();
    return redirect()->back();
}
Activity icon

Started a new Conversation How To Use Soft Delete In Dynamic Form Input

I am working dynamic form input in Laravel-5.8

Invoice Controller

public function store(Request $request)
{
    $request->validate([

        'customer_id' => 'required',
        'product_id' => 'required',
        'qty' => 'required',
        'price' => 'required',
        'dis' => 'required',
        'amount' => 'required',
    ]);

    $invoice = new Invoice();
    $invoice->customer_id = $request->customer_id;
     $invoice->save();

    foreach ( $request->product_id as $key => $product_id){
        $sale = new Sale();
        $sale->qty = $request->qty[$key];
        $sale->price = $request->price[$key];
        $sale->dis = $request->dis[$key];
        $sale->amount = $request->amount[$key];
        $sale->product_id = $request->product_id[$key];
        $sale->invoice_id = $invoice->id;
        $sale->save();
     }

     return redirect('invoice/'.$invoice->id)->with('message','invoice created Successfully');
}

public function destroy($id)
{
    $invoice = Invoice::findOrFail($id);
    $invoice->delete();
    return redirect()->back();
}

I have this question:

How do I do soft delete on both invoice and invoicedetail in the invoice Controller. And how do I restore back.

Thank you.

Activity icon

Started a new Conversation How To Download Attached File

Using Laravel-5.8, I want to download the attached file to my local disc on a click.

When I click on it in the view blade:

   <div class="col-md-4">
                                
       Attached File: <a  target="_blank" href="{{ URL::to('/') }}/public/storage/documents/appraisal_goal/{{ $goal->appraisal_doc }}">{{ $goal->appraisal_doc }}</a>
    </div> 

It redirected me to another page instaed of downloading it.

How do I resolve it?

Thanks

Activity icon

Started a new Conversation Syntax Error, Unexpected '')); ?>"> '

In my Laravel-5.8, I got this error:

syntax error, unexpected '')); ?>"> ' (T_CONSTANT_ENCAPSED_STRING), expecting ')'

And it underlines this:

          <h4>
               <i class="fa fa-globe"></i> {{ config('app.name') }}
               <small class="float-right">Date: {{ date('l, d-M-Y h:i:s A') }}</small>
          </h4>

Where did I get it wrong?

Activity icon

Replied to View [appraisal.appraisal_goals.view_all_goal_print] Not Found

Thanks, wrongly typed l in front of view in viewl_all_goal_print.blade.php.

Thanks

Activity icon

Started a new Conversation View [appraisal.appraisal_goals.view_all_goal_print] Not Found

I have this Controller:

public function index()
{
    $userCompany = Auth::user()->company_id;
    $userEmployee = Auth::user()->employee_id;
    $identities = DB::table('appraisal_identity')->select('id')->where('company_id', $userCompany)->where('is_current', 1)->first();
    
    $goals = AppraisalGoal::where('employee_id', $userEmployee)->where('appraisal_identity_id', $identities->id)->get();

    return view('appraisal.appraisal_goals.index')->with('goals', $goals);
}

and the view view below belongs to it:

           <div class="row no-print">
            <div class="col-12">
              <a href="{{ route('appraisal.appraisal_goals.view_all_goal_print')}}" target="_blank" class="btn btn-success" style="margin-right: 5px;">
                <i class="fa fa-print"></i> View All Goals
              </a>                  
          </div>   

When a href is clicked it should render this:

public function view_all_goal_print()
{
    $userCompany = Auth::user()->company_id;
    $userEmployee = Auth::user()->employee_id;
    $identities = DB::table('appraisal_identity')->select('id')->where('company_id', $userCompany)->where('is_current', 1)->first();
    $goals = AppraisalGoal::where('employee_id', $userEmployee)->where('appraisal_identity_id', $identities->id)->get();

    return view('appraisal.appraisal_goals.view_all_goal_print')->with('goals', $goals);
} 

web.php

Route::get('appraisal_goals/view_all_goal_print', 'Appraisal\[email protected]_all_goal_print')->name('appraisal.appraisal_goals.view_all_goal_print');

But I got this error:

InvalidArgumentException View [appraisal.appraisal_goals.view_all_goal_print] not found.

What do I do.

Feb
20
5 days ago
Activity icon

Replied to How To Make Lesson Aggregate Score Not More Than Course Max Score

  1. It needs to sum all the score of a particular student for a particular score.
  2. Am I writing the code before or after the ->save()
Activity icon

Replied to How To Pass Parameter To Redirect

from my code what should be in param1 and first

Activity icon

Started a new Conversation How To Pass Parameter To Redirect

In my Laravel-5.8, I have:

public function manager_employee_goal_list($id)
{
    $goal           =       AppraisalGoal::findOrFail($id);
    $goaldetails    = AppraisalGoalDetail::where('appraisal_goal_id', $id)->get();
    return view('appraisal.appraisal_goals.manager_employee_goal_list')
                ->with('goal', $goal)
                ->with('goaldetails', $goaldetails);       
} 

public function manager_employee_goal_approve(Request $request, $id)
{
    $goal                           = AppraisalGoal::find($id);
    $goal->is_approved              = 3;
    $goal->line_manager_comment     = $request->line_manager_comment;
    $goal->save();

            Session::flash('success', 'Goal is approved');
            return redirect()->route('appraisal.appraisal_goals.manager_employee_goal_list');        
} 

view : manager_employee_goal_list

<a class="btn btn-xs btn-info" data-toggle="modal" data-target="#approve{{ $goal->id }}"   data-original-title="Approve"> Approve</a>

                                    <div class="modal fade" id="approve{{ $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_goals.manager_employee_goal_approve',['id'=>$goal->id])}}" method="post">
                                                    {{ csrf_field() }}
                                                    <div class="modal-header">
                                                        Approve Goal
                                                    </div>
                                                    <div class="col-md-12">
                                                        <div class="form-group">
                                                            <label class="control-label">Comment</label>
                                                            <textarea rows="2" name="line_manager_comment" class="form-control" placeholder="Enter Comment here" value="{{old('line_manager_comment')}}" required data-validation-required-message="This field is required"></textarea> 
                                                        </div>
                                                    </div>
                                                    <div class="modal-footer">
                                                        <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
                                                        <button  type="submit" class="btn btn-success btn-ok">Approve Goal</button>
                                                    </div>
                                                </form>
                                            </div>
                                        </div>
                                    </div>

route/web.php

Route::get('appraisal_goals/manager_employee_goal_list/{id?}', 'Appraisal\[email protected]_employee_goal_list')->name('appraisal.appraisal_goals.manager_employee_goal_list');
Route::post('appraisal_goals/manager_employee_goal_approve/{id?}', 'Appraisal\[email protected]_employee_goal_approve')->name('appraisal.appraisal_goals.manager_employee_goal_approve');

When I submit on the modal form, it saves but couldn't redirect to:

return redirect()->route('appraisal.appraisal_goals.manager_employee_goal_list');

It displays this error

Too few arguments to function App\Http\Controllers\Appraisal\AppraisalGoalsController::manager_employee_goal_list(), 0 passed and exactly 1 expected

How do I resolve it?

Thanks

Activity icon

Replied to Missing Required Parameters For [Route: Appraisal.appraisal_goals.manager_employee_goal]

I changed

'id' => $goal->id

to

'id' => $goal->id?

and it works.

Thank you

Activity icon

Replied to Missing Required Parameters For [Route: Appraisal.appraisal_goals.manager_employee_goal]

The problem still persists and not resolved. What do I do next?

Activity icon

Replied to Missing Required Parameters For [Route: Appraisal.appraisal_goals.manager_employee_goal]

Before I added appraisal.appraisal_goals.manager_employee_goal_list, appraisal.appraisal_goals.manager_employee_goal was working perfectly. It got its own from

   <a href="{{ route('appraisal.appraisal_goals.manager_employee_goal', [$employee->id]) }}" class="btn btn-sm btn-primary">
      <i class="fas fa-user"></i> View Goal
  </a>

Then from appraisal.appraisal_goals.manager_employee_goal I passed $goalid to appraisal.appraisal_goals.manager_employee_goal_list.

     <a class="btn btn-xs btn-primary" href="{{ route('appraisal.appraisal_goals.manager_employee_goal_list', ['goalid'=>$goal->id]) }}">
          {{ trans('global.view') }}
     </a> 

I don't understand this:

route is not used in above code, so the error comes from the other place

What do I do

Activity icon

Started a new Conversation Missing Required Parameters For [Route: Appraisal.appraisal_goals.manager_employee_goal]

With Laravel-5.8, I tried to route from:

public function manager_employee_goal($id)
{
    if (! Gate::allows('appraisal_goal_review')) {
        return abort(401);
    }        
    
    $userCompany = Auth::user()->company_id;
    $userEmployee = Auth::user()->employee_id;
    $identities = DB::table('appraisal_identity')->select('id')->where('company_id', $userCompany)->where('is_current', 1)->first();
    $linemanager = DB::table('hr_employees')->select('line_manager_id')->where('id', $userEmployee)->first();
    $linemanageremployee = DB::table('hr_employees')->select('id')->where('line_manager_id', $linemanager->line_manager_id)->pluck('id');
   $appraisedemployees = HrEmployee::select('id', 'employee_code', 'first_name', 'last_name')->where('id', $id)->get();    

    $goals = AppraisalGoal::where('employee_id', $id)->where('appraisal_identity_id', $identities->id)->where('id', '!=', $linemanager->line_manager_id)->get();
    
    return view('appraisal.appraisal_goals.manager_employee_goal')->with('goals', $goals)->with('appraisedemployees', $appraisedemployees);        
}

view: manager_employee_goal.blade

  <a class="btn btn-xs btn-primary" href="{{ route('appraisal.appraisal_goals.manager_employee_goal_list', ['goalid'=>$goal->id]) }}">
           {{ trans('global.view') }}
  </a> 

to this route:

public function manager_employee_goal_list($goalid)
{
        $goal           =       AppraisalGoal::findOrFail($goalid);
    $goaldetails    = AppraisalGoalDetail::where('appraisal_goal_id', $goalid)->get();
    return view('appraisal.appraisal_goals.manager_employee_goal_list')
                ->with('goal', $goal)
                ->with('goaldetails', $goaldetails);       
}    

using

Route::get('appraisal_goals/manager_employee_goal/{id}', 'Appraisal\[email protected]_employee_goal')->name('appraisal.appraisal_goals.manager_employee_goal');
Route::get('appraisal_goals/manager_employee_goal_list/{goalid}', 'Appraisal\[email protected]_employee_goal_list')->name('appraisal.appraisal_goals.manager_employee_goal_list');

But I got this error:

Missing required parameters for [Route: appraisal.appraisal_goals.manager_employee_goal] [URI: appraisal_goals/manager_employee_goal/{id}]. (View: C:\xampp\htdocs\peopleedge\resources\views\appraisal\appraisal_goals\manager_employee_goal_list.blade.php)

How do I get it resolved?

Thank you

Activity icon

Replied to How To Pass Parameter In Laravel

it works. Thanks

Activity icon

Replied to How To Pass Parameter In Laravel

I did that but got another error Error 404. Page Not Found. The page is there!

Activity icon

Started a new Conversation How To Pass Parameter In Laravel

Using Laravel-5.8, I have this code:

public function manager_employee_list(Request $request)
{
    
    $employees = HrEmployee::paginate(6);
 
    return view('appraisal.appraisal_goals.manager_employee_list')->with('employees', $employees);
}

And it render this view: manager_employee_list

      <div class="row d-flex align-items-stretch">
          @if (count($employees))
          @foreach($employees as $key => $employee)
        <div class="col-12 col-sm-6 col-md-4 d-flex align-items-stretch">
          <div class="card bg-light">
            <div class="card-header text-muted border-bottom-0">
              {{isset($employee->designation) ? $employee->designation->designation_name : ''}}
            </div>
            <div class="card-body pt-0">
              <div class="row">
                <div class="col-7">
                  <h2 class="lead"><b>Staff ID: {{$employee->employee_code}}</b></h2>
                  <h2 class="lead"><b>{{$employee->first_name}} {{$employee->last_name}}</b></h2>

                  <h6 class="lead"><b>Employee Department: </b>{{isset($employee->department) ? $employee->department->dept_name : ''}}</h6>
                </div>
                <div class="col-5 text-center">
                            @if($employee->emp_image != '')
                                <img src="{{ URL::to('/') }}/public/storage/employees/image/{{ $employee->emp_image }}" class="img-circle img-fluid" />

                            @else
                                <img class="profile-user-img img-fluid img-circle" src="{{asset('theme/adminlte3/dist/img/default.png')}}" alt="" class="img-circle img-fluid">
                            @endif
                </div>
              </div>
            </div>
            <div class="card-footer">
              <div class="text-right">
                <a href="{{ route('appraisal.appraisal_goals.manager_employee_goal', ['id'=>$employee->id]) }}" class="btn btn-sm btn-primary">
                  <i class="fas fa-user"></i> View Goal
                </a>
              </div>
            </div>
          </div>
        </div>
        @endforeach 
        @else
        <h4 style="text-align:center;">No matching records found</h4>
        @endif           
      </div>

I want to pass the parameter

['id'=>$employee->id]

from above to another controller action:

public function manager_employee_goal($id)
{

    $goals = AppraisalGoal::where('employee_id', $id)->get();
    
    return view('appraisal.appraisal_goals.manager_employee_goal')->with('goals', $goals);        
}

It utilizes it here:

$goals = AppraisalGoal::where('employee_id', $id)->get();

When I clicked on

                <a href="{{ route('appraisal.appraisal_goals.manager_employee_goal', ['id'=>$employee->id]) }}" class="btn btn-sm btn-primary">
                  <i class="fas fa-user"></i> View Goal
                </a>

I got this error:

Too few arguments to function App\Http\Controllers\Appraisal\AppraisalGoalsController::manager_employee_goal(), 0 passed and exactly 1 expected

and this is underlined:

public function manager_employee_goal($id)

route/web.php

 Route::get('appraisal_goals/manager_employee_list', 'Appraisal\[email protected]_employee_list')->name('appraisal.appraisal_goals.manager_employee_list');
Route::get('appraisal_goals/manager_employee_goal', 'Appraisal\Appr[email protected]_employee_goal')->name('appraisal.appraisal_goals.manager_employee_goal');

How do I resolve it?

Thank you.

Activity icon

Replied to How To Use A Single Textbox For Global Search

How do I write the search text in the view

Activity icon

Started a new Conversation How To Use A Single Textbox For Global Search

I have this Laravel-5.8 code whereby users can search using different control fields to search for employee_code, designation and department.

class HrEmployee extends Model
{
  protected $table = 'hr_employees';

  protected $primaryKey = 'id';

  protected $fillable = [
              'id',
              'employee_code',
              'address',
              'email',
              'employee_designation_id',
              'first_name',
              'emp_image',
              'last_name',
              'other_name',
              'department_id',
          ];

protected $appends = ['full_name'];

 public function user()
 {
    return $this->belongsTo('App\User');
 }

 public function designation()
 {
    return $this->belongsTo('App\Models\Hr\HrDesignation','employee_designation_id');
 }

 public function department()
 {
    return $this->belongsTo('App\Models\Hr\HrDepartment','department_id');
 }   
}

Controller

public function index(Request $request)
{
    $userCompany = Auth::user()->company_id;
    $render=[];  
        $employees = HrEmployee::where('company_id', $userCompany);
    $employees=$employees->with('department','designation');
    if(isset($request->employee_code))
    {
        $employees=$employees->where('employee_code','like','%'.$request->employee_code.'%');
        $render['employee_code']=$request->employee_code;
    }     
    if(isset($request->employee_designation_id))
    {
        $employees=$employees->where('employee_designation_id',$request->employee_designation_id);
        $render['employee_designation_id']=$request->employee_designation_id;
    }         
    if(isset($request->department_id))
    {
        $employees=$employees->where('department_id',$request->department_id);
        $render['department_id']=$request->department_id;
    }        
    $employees= $employees->paginate(6);
    $employees= $employees->appends($render);
    $data['employees'] = $employees;  
    $data['departments']= HrDepartment::where('company_id', $userCompany)->pluck('dept_name','id');
    $data['designations']= HrDesignation::where('company_id', $userCompany)->pluck('designation_name','id');
        
    return view('hr.employees.index',$data);
}

view

{{ Form::model(request(),['method'=>'get']) }}

    <div orm-group class="col-sm-3">
        {{Form::label('employee_code', 'Employee No.')}}
        {{ Form::text('employee_code',null,['class'=>'form-control','placeholder'=>'Employee Code']) }}
         
    </div>
    <div class="col-sm-4">
        {{Form::label('department_id', 'Department')}}
        {{ Form::select('department_id',$departments,null,['class'=>'form-control select2bs4','placeholder'=>'Select Department']) }}
    </div>        
    <div class="col-sm-4">
        {{Form::label('employee_designation_id', 'Designation')}}
        {{ Form::select('employee_designation_id',$designations,null,['class'=>'form-control select2bs4','placeholder'=>'Select Designation']) }}
    </div>                 
    
    <div class="col-xs-3">
        <br>
        {{ Form::submit('Search',['class'=>'btn btn-warning']) }}

    </div>
    {{ Form::close() }}
</div>
<br>
  <!-- Default box -->
  <div class="card card-solid">
    <div class="card-body pb-0">
      <div class="row d-flex align-items-stretch">
          @if (count($employees))
          @foreach($employees as $key => $employee)
        <div class="col-12 col-sm-6 col-md-4 d-flex align-items-stretch">
          <div class="card bg-light">
            <div class="card-header text-muted border-bottom-0">
              {{isset($employee->designation) ? $employee->designation->designation_name : ''}}
            </div>
            <div class="card-body pt-0">
              <div class="row">
                <div class="col-7">
                  <h2 class="lead"><b>Staff ID: {{$employee->employee_code}}</b></h2>
                  <h2 class="lead"><b>{{$employee->first_name}} {{$employee->last_name}}</b></h2>

                  <h6 class="lead"><b>Employee Department: </b>{{isset($employee->department) ? $employee->department->dept_name : ''}}</h6>
                  <h6 class="lead"><b>Employment Date: </b>{{$employee->employment_date ? Carbon\Carbon::parse($employee->employment_date)->format('d-m-Y') : 'N/A' }}</h6>
                  <ul class="ml-4 mb-0 fa-ul text-muted">
                    <li class="small"><span class="fa-li"><i class="fas fa-lg fa-envelope"></i></span> Email: {{$employee->email}}</li>
                    <li class="small"><span class="fa-li"><i class="fas fa-lg fa-phone"></i></span> Phone #: {{isset($employee->phone) ? $employee->phone : 'N/A'}}</li>
                  </ul>
                </div>
                <div class="col-5 text-center">
                            @if($employee->emp_image != '')
                                <img src="{{ URL::to('/') }}/public/storage/employees/image/{{ $employee->emp_image }}" class="img-circle img-fluid" />

                            @else
                                <img class="profile-user-img img-fluid img-circle" src="{{asset('theme/adminlte3/dist/img/default.png')}}" alt="" class="img-circle img-fluid">
                            @endif
                </div>
              </div>
            </div>
            <div class="card-footer">
              <div class="text-right">
                @can('employee_show')
                <a href="{{ route('hr.employees.show', ['id'=>$employee->id]) }}" class="btn btn-sm btn-primary">
                  <i class="fas fa-user"></i> View Detail
                </a>
                @endcan
              </div>
            </div>
          </div>
        </div>
        @endforeach 
        @else
        <h4 style="text-align:center;">No matching records found</h4>
        @endif           
      </div>
    </div>

    <!-- /.card-body -->
    <div class="card-footer align-items-center d-flex justify-content-center">
        {{ $employees->links() }}
    <!-- /.card-footer -->
  </div>
  <!-- /.card -->

</div>

Instead of searching for each field one by one using different control fields. How do I use a sing textbox to search for employee_code, first_name, last_name, department and designation?

Thank you

Activity icon

Started a new Conversation How To Make Lesson Aggregate Score Not More Than Course Max Score

I am developing a web application on Student Course Management using Laravel-5.8

Models

class Lesson extends Model
{
      protected $table = 'Lessons';
      protected $fillable = [
              'lesson_name',
          'course_id',
          'student_id',
              'score_obtained',
          ];

   public function gradelevel()
    {
        return $this->belongsTo('App\Models\Course','course_id');
    }
    public function student()
    {
        return $this->belongsTo('App\Models\Student','student_id');
    }

}

class Course extends Model
{
  protected $table = 'courses';
  protected $fillable = [
              'course_code',
              'course_name',
              'max_score',
          ];
}  

Controller

class LessonController extends Controller
{
    public function create()
    {
      $courses = Course::all();
      $students = Student::all();
      return view('lessons.create')->with('courses', $courses)->with('students', $students);
    }

    public function store(StoreLessonRequest $request)
    {
     try {
            $lesson = Lesson::create([
                'lesson_name'       => $request->lesson_name,
                'course_id'             => $request->course_id,
                'lesson_id'             => $request->lesson_id,
                'score_obtained'            => $request->score_obtained,
            ]);
            Session::flash('success', 'Lesson is created successfully');
            return redirect()->route('lessons.index');
    } catch (Exception $exception) {
            Session::flash('danger', 'Lesson creation failed!');
            return redirect()->route('lessons.index');
    }
 }
}

create.blade

   <form  action="{{route('lessons.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-sm-6">
            <div class="form-group">
                <label>Course</label>
                <select class="form-control select2bs4" data-placeholder="Choose Course" tabindex="1" name="course_id" style="width: 100%;">>
                    <option value="">Select Course</option>
                    @if($courses->count() > 0)
                        @foreach($courses as $course)
                            <option value="{{$course->id}}">{{$course->course_name}}</option>
                        @endforeach
                    @endif
                </select>
            </div>
          </div>

          <div class="col-sm-6">
            <div class="form-group">
                <label>Student</label>
                <select class="form-control select2bs4" data-placeholder="Choose Course" tabindex="1" name="student_id" style="width: 100%;">>
                    <option value="">Select Student</option>
                    @if($students->count() > 0)
                        @foreach($students as $student)
                            <option value="{{$student->id}}">{{$student->student_name}}</option>
                        @endforeach
                    @endif
                </select>
            </div>
          </div>
            
          <div class="col-sm-6">
            <div class="form-group">
                <label>Lesson<span style="color:red;">*</span></label>
               <input  type="text" name="lesson_name" placeholder="Enter lesson here" class="form-control" value="{{old('lesson_name')}}">
            </div>
          </div>
                            
          <div class="col-sm-6">
            <div class="form-group">
                <label>Obtained Score<span style="color:red;">*</span></label>
               <input  type="text" name="score_obtained" placeholder="Enter score obtained here" class="form-control" value="{{old('score_obtained')}}">
            </div>
          </div>

       </div>
     </div>
    </div>          
    <!-- /.card-body -->
    <div class="card-footer">
            <button type="submit" id="submit_create" class="btn btn-primary">Score</button>
    </div>           
       
    </form>

Each core have maximum score allocated and this is done at the setting. For each course, students have lesson and scores are obtained for each lesson.

What I want to achieve is that on the lesson create form, what student score_obtained are being entered the application should sum up all the scores (from the lesson table and the just entered one) the student obtained for that particular course including the one in the textbox, if its more that what is in the max_score in the courses table for that particular course the application should display a message and shouldn't allow the user to submit.

How do I achieve this?

Thank you.

Feb
19
6 days ago
Activity icon

Replied to Resolving Object Of Class StdClass Could Not Be Converted To String

No, it was a mistake. This the the actual code:

$goals = AppraisalGoal::where('employee_id', $linemanageremployee)->where('appraisal_identity_id', $identities->id)->get();
return view('appraisal.appraisal_goals.manager_employee_list')->with('goals', $goals);
Activity icon

Replied to Resolving Object Of Class StdClass Could Not Be Converted To String

The error is still there. I think the issue is how to place

$linemanageremployee = DB::table('hr_employees')->where('line_manager_id', $linemanager->line_manager_id)->get('id');

in

$goals = AppraisalGoal::where('employee_id', $linemanageremployee)->where('appraisal_identity_id', $identities->id)->get();

Activity icon

Started a new Conversation Resolving Object Of Class StdClass Could Not Be Converted To String

When I run this code:

   public function manager_employee_list()
   {
       $userCompany = Auth::user()->company_id;
       $userEmployee = Auth::user()->employee_id;
       $identities = DB::table('appraisal_identity')->select('id')->where('company_id', $userCompany)->where('is_current', 1)->first();
    
       $linemanager = DB::table('hr_employees')->select('line_manager_id')->where('id', $userEmployee)->first();
       $linemanageremployee = DB::table('hr_employees')->select('id')->where('line_manager_id', $linemanager->line_manager_id)->get();  
       $goals = AppraisalGoal::where('employee_id', $linemanageremployee)->where('appraisal_identity_id', 
       return view('appraisal.appraisal_goals.manager_employee_list')->with('goals', $goals);        
}

I got this error:

Object of class stdClass could not be converted to string

When I did:

dd($linemanageremployee);

I got:

Illuminate\Support\Collection {#880 ▼
  #items: array:3 [▼
    0 => {#2312 ▼
  +"id": 2
}
1 => {#2326 ▼
  +"id": 3
}
2 => {#2313 ▼
  +"id": 6
    }
  ]
}

How do I resolve it?

Thank you.

Activity icon

Replied to How To Resolve Page Not Found. No Query Results For Model []

It's error 404. No code bug on the error page. Only states that:

Page not found. No query results for model [App\Models\Appraisal\AppraisalGoal] goal_review

Activity icon

Started a new Conversation How To Resolve Page Not Found. No Query Results For Model []

I have this controller:

public function goal_review()
{

    $userCompany = Auth::user()->company_id;
    $userEmployee = Auth::user()->employee_id;
    $identities = DB::table('appraisal_identity')->select('id')->where('company_id', $userCompany)->where('is_current', 1)->first();
    
    $goals = AppraisalGoal::where('employee_id', $userEmployee)->where('appraisal_identity_id', $identities->id)->get();

    return view('appraisal.appraisal_goals.goal_review')->with('goals', $goals);
}

route/web.php

Route::group(['prefix' => 'appraisal', 'as' => 'appraisal.', 'namespace' => 'Appraisal', 'middleware' => ['auth']], function () {
    Route::get('appraisal_goals/goal_review', '[email protected]_review')->name('appraisal_goals.goal_review');
});

When I tried to render it with:

             <li class="nav-item">
               <a href="{{ route("appraisal.appraisal_goals.goal_review") }}" class="nav-link {{ request()->is('appraisal.appraisal_goals') || request()->is('appraisal.appraisal_goals/*') ? 'active' : '' }}">
                 <i class="nav-icon fas fa-balance-scale"></i>
                 <p>
                   <span>Goals Review</span>
                 </p>
               </a>
             </li>

I got this error:

Page not found. No query results for model [App\Models\Appraisal\AppraisalGoal] goal_review

How do I resolve this?

Activity icon

Replied to How To Approve All The Posts Of A Particular Employee

I have updated the index view blade with this:

    <form action="{{route('admin.post.approve', $post->id)}}" method="POST" enctype="multipart/form-data">
        @csrf
        @method('PUT')
     <div>
        <button type="submit" class="btn btn-primary"><i class="fas fa-arrow-right"></i>Approve</button>
    </div> 
   </form> 

But that's not the way. I need guidance.

Activity icon

Started a new Conversation How To Approve All The Posts Of A Particular Employee

I have written a code for post of employees and it is working perfectly:

Controller

public function index()
{
    $userEmployee = Auth::user()->employee_id;
    $posts = Post::latest()->where('employee_id', $userEmployee)->get();
    return view('admin.post.index', compact('posts'));
}

And it generates this view shown below. The view loads all the unapproved posts for a particular employee:

 <table class="table table-bordered table-striped table-hover dataTable js-exportable">
        <thead>
                        <tr>
                            <th>ID</th>
                            <th>Title</th>
                            <th>Author</th>
                            <th><i class="material-icons">visibility</i></th>
                            <th>Is Approved</th>
                            <th>Status</th>
                            <th>Action</th>

                        </tr>
                        </thead>
                        <tfoot>
                        <tr>
                            <th>ID</th>
                            <th>Title</th>
                            <th>Author</th>
                            <th><i class="material-icons">visibility</i></th>
                            <th>Is Approved</th>
                            <th>Status</th>
                            <th>Action</th>

                        </tr>
                        </tfoot>
                        <tbody>
                        @foreach($posts as $key=>$post)
                        <tr>
                            <td>{{ $key + 1 }}</td>
                            <td>{{ str_limit($post->title,'10') }}</td>
                            <td>{{ $post->user->name }}</td>
                            <td>{{ $post->view_count }}</td>
                            <td>
                                @if($post->is_approved == true)
                                    <span class="badge bg-blue">Approved</span>
                                @else
                                    <span class="badge bg-pink">Pending</span>
                                @endif
                            </td>
                            <td>
                                @if($post->status == true)
                                    <span class="badge bg-blue">Published</span>
                                @else
                                    <span class="badge bg-pink">Pending</span>
                                @endif
                            </td>
                         </tr>
                        @endforeach

           </tbody>
  </table>

    <form action="{{route('admin.post.approve', $post->id)}}" method="POST" enctype="multipart/form-data">
        @csrf
        @method('PUT')
     <div>
        <button type="submit" class="btn btn-primary"><i class="fas fa-arrow-right"></i>Approve</button>
    </div> 
   </form> 

I want to add a submit button to the view called approve. Once the button is clicked, it checks where is_approved is = 0 for the loaded employee and turns all the is_approved that relates to the employee (the loaded) data to 1.

I have written this function in the same controller, but I see that it will only work for a selected row:

public function approve($id){

    $post = Post::find($id);
    if ($post->is_approved == false){
        $post->is_approved = true;
        $post->save();
        $post->user->notify(new AuthorPostApprove($post));

        Toastr::success('Post Successfully Approved');
    }else{
        Toastr::info('Post is already Approved');
    }

    return redirect()->back();
}

and have this route/web.php

Route::get('posts/', '[email protected]')->name('post.index');
Route::put('/post/{id}/approve', '[email protected]')->name('post.approve');

How do I re-write my Controller, view and route to achieve this?

Thank you.

Feb
18
1 week ago
Activity icon

Started a new Conversation How To Perform Batch Update On Based On Condition

I am using Laravel-5.8 for my web application. I have these lines of code:

Model

class AppraisalGoal extends Model
{
   protected $table = 'appraisal_goals';

   protected $fillable = [
          'goal_type_id',
          'appraisal_identity_id',
          'employee_id',
          'company_id',
          'is_published',
          'is_approved',
          'weighted_score',
          'employee_comment',
          'line_manager_comment',
          'goal_title',
          'appraisal_doc',
          'appraisal_start_date',
          'appraisal_end_date',
      ];

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


  public function appraisalgoaldetail(){
     return $this->hasMany('App\Models\Appraisal\AppraisalGoalDetail');
  }
}

class AppraisalGoalDetail extends Model
{  
    protected $table = 'appraisal_goal_details';
    protected $fillable = [
          'name',
          'company_id',
          'appraisal_goal_id',
          'kpi_description',
          'appraisal_doc',
          'activity',
          'start_date',
          'end_date',
      ];

 public function appraisalgoal()
 {
     return $this->belongsTo('App\Models\Appraisal\AppraisalGoal');
 }    
}

Controller

public function index()
{
    $userCompany = Auth::user()->company_id;
    $userEmployee = Auth::user()->employee_id;
    $identities = DB::table('appraisal_identity')->select('id')->where('company_id', $userCompany)->where('is_current', 1)->first();
    $linemanager = DB::table('hr_employees')->select('line_manager_id')->where('employee_id', $userEmployee)->first();
    $linemanageremail = DB::table('hr_employees')->select('email')->where('id', $userEmployee)->first();
    $goals = AppraisalGoal::where('employee_id', $userEmployee)->where('appraisal_identity_id', $identities->id)->get();
}

view

<div class="card-body">
    <div class="table-responsive">
        <table class=" table table-bordered table-striped table-hover datatable">
            <thead>
                <tr>
                    <th width="10%">
                        Goal Type
                    </th>
                    <th width="20%">
                        Goal Title & Description
                    </th>
                    <th class="text-center" width="40%">
                        Activities & KPIs
                    </th>
                    <th width="11%">
                        Start Date - End Date
                    </th>
                    <th>
                        Weight
                    </th>  
                    <th>
                        Status
                    </th>  
                    <th>
                        &nbsp;
                    </th>
                </tr>
            </thead>
            <tbody>
                @foreach($goals as $key => $goal)
                        <td>
                            <!--{{ $goal->goaltype ? $goal->goaltype->name : 'Uncategorized' }}-->
                            {{$goal->goaltype->name ?? '' }}
                        </td>
                        <td>
                            <b>{{$goal->goal_title ?? '' }}</b>
                            <br><br>
                            {!! Str::words($goal->goal_description, 20, '') !!}
                            @if(str_word_count($goal->goal_description) > 20)
                              <a class="btn btn-xs btn-info" href="{{ route('appraisal.appraisal_goals.show', $goal->id) }}"> Show more </a>
                            @endif                                 
                        </td>                          
                        <td>
                                        <table class="table">
                                            <thead>
                                            <tr>
                                                <th width="50%">
                                                    Activity
                                                </th>
                                                <th width="50%">
                                                    KPIs
                                                </th>
                                            </tr>
                                            </thead>
                                            <tbody>
                                            @foreach($goal->appraisalgoaldetail as $key => $appraisalgoaldetail)
                                                <tr>
                                                    <td>
                                                        {{$key+1}}. {{$appraisalgoaldetail->activity}}
                                                    </td>

                                                    <td>
                                                        {{$appraisalgoaldetail->kpi_description}}
                                                    </td>
                                                </tr>
                                            @endforeach
                                            </tbody>
                                        </table>
                        </td>

                        <td>
                           
                            {{Carbon\Carbon::parse($goal->appraisal_start_date)->format('M d, Y') ?? '' }} - {{Carbon\Carbon::parse($goal->appraisal_end_date)->format('M d, Y') ?? '' }}
                        </td>  
                        <td>
                            {{$goal->weighted_score ?? '' }}
                        </td>                            
                        <td>
                            @if ($goal->is_approved == 2)
                                <span class="badge bg-success" >Approved</span>
                            @elseif ($goal->is_approved == 1)
                                <span class="badge bg-info">Awaiting Approval</span>
                            @else
                                <span class="badge bg-danger">Draft</span>                                    
                            @endif
                        </td>
                        <td>                               
                            @can('appraisal_goal_show')
                                <div class="btn-group">
                                    <a title={{ trans('global.detail') }}  href="{{ route('appraisal.appraisal_goals.show', $goal->id) }}"  class="btn btn-primary btn-sm"><i class="fa fa-eye"></i>
                                    </a>
                                </div>                                 
                            @endcan
                            @can('appraisal_goal_edit')
                                <div class="btn-group">
                                    <a title={{ trans('global.edit') }} href="{{ route('appraisal.appraisal_goals.edit', ['id'=>$goal->id]) }}" class="btn btn-info btn-sm"><i class="fa fa-edit"></i></a>
                                </div> 
                            @endcan
                            @can('appraisal_goal_delete')
                                <div class="btn-group">
                                <a title={{ trans('global.delete') }} class="btn btn-danger btn-sm" data-toggle="modal" data-target="#confirm-delete{{ $goal->id }}" data-original-title="Close"> 
                                    <span style="color:white;"><i class="fa fa-fw fa-trash"></i></span>
                                </a>
                                </div>                                 
                            @endcan   
                             
                        </td>
                                           
                </tr>
                @endforeach 
            </tbody>
        </table>
    </div>
         <div>
            <button type="submit" class="btn btn-primary"><i class="fas fa-arrow-right"></i> {{ trans('global.submit') }}</button>
        </div>           
</div>

https://i.stack.imgur.com/LPyUy.png

When I click on submit button:

  1. I want the application to check appraisal_goals table based on the current record in index Controller. Where is_published is 0, it should change it 1

  2. Send notifications to $linemanageremail that $userEmployee has published $goal->goal_title (each of it) for $identities.

How do I modify my Controller and View to achieve these?

Thank you.

Activity icon

Started a new Conversation Object Of Class StdClass Could Not Be Converted To String

I have this controller:

public function index()
{
    $userCompany = Auth::user()->company_id;
    $userEmployee = Auth::user()->employee_id;
    $identities = DB::table('appraisal_identity')->select('id')->where('company_id', $userCompany)->where('is_current', 1)->first();
    $goals = AppraisalGoal::where('employee_id', $userEmployee)->where('appraisal_identity_id', $identities)->get();

    return view('appraisal.appraisal_goals.index')->with('goals', $goals);
}

When I tried to render it, I got this error:

Object of class stdClass could not be converted to string

and it points to line 45.

$goals = AppraisalGoal::where('employee_id', $userEmployee)->where('appraisal_identity_id', $identities)->get();

When I ran this:

die(var_dump($identities));

I got:

object(stdClass)#2295 (1) { ["id"]=> int(8) }

How do I resolve it?

Thank you.

Activity icon

Replied to Error: Property [kpi_description] Does Not Exist On This Collection Instance

Kindly pardon me. Can you give me a sample based on my code

Activity icon

Replied to Error: Property [kpi_description] Does Not Exist On This Collection Instance

If I'm using rowspan, it means I've known the number of rows. But I don't know the numbers of rows. I want it to divide each sub row with lines. I want something like this:

https://i.stack.imgur.com/B9ZtX.png

Activity icon

Started a new Conversation Max Word Length As 20

In my Laravel-5.8, I used this for max character length as 20:

    {{str_limit($goal->goal_description, $limit = 20, $end = '')}}
        @if(strlen($goal->goal_description) > 20)
            <a class="btn btn-xs btn-info" href="{{ route('appraisal.appraisal_goals.show', $goal->id) }}"> Show more </a>
       @endif  

and it works fine. However, instead of character length as 20 I want to change it to max word length as 20. I started like this:

{!! Str::words($goal->goal_description, 20, '') !!}

but I don't know how to put the condition for max word length as 20 as I did in max character/string length as 20.

How do I achieve this?

Thank you.

Activity icon

Replied to Error: Property [kpi_description] Does Not Exist On This Collection Instance

Thanks a lot it works.

This is what I got:

kpi description1 kpi description2 kpi description3

It just moddle everything together as 1 row. It could be 2, 3 or more rows. How do I make it like this:

https://i.stack.imgur.com/B9ZtX.png

That is, divide it into rows and number it, like

  1. kpi description1

  2. kpi description2

  3. kpi description3

Activity icon

Started a new Conversation Error: Property [kpi_description] Does Not Exist On This Collection Instance

In my Laravel-5.8 project, I have this code

Controller

public function index()
{
  $userEmployee = Auth::user()->employee_id;
  $goals = AppraisalGoal::where('employee_id', $userEmployee)->get();

  return view('appraisal.appraisal_goals.index')->with('goals', $goals);
}

model

class AppraisalGoal extends Model
{
  protected $table = 'appraisal_goals';
  protected $primaryKey = 'id';

  protected $fillable = [
              'weighted_score',
              'employee_comment',
              'goal_title',
          ];

  public function appraisalgoaldetail(){
    return $this->hasMany('App\Models\Appraisal\AppraisalGoalDetail');
  }
}

class AppraisalGoalDetail extends Model
{
 protected $table = 'appraisal_goal_details';
 protected $fillable = [
              'kpi_description',
          ];

 public function appraisalgoal()
 {
    return $this->belongsTo('App\Models\Appraisal\AppraisalGoal');
}     
}

the function appraisalgoaldetail() is hasMany relationtionship.

view

                @foreach($goals as $key => $goal)
                        <td>
                            {{$key+1}}
                        </td>
                        <td>
                            {{$goal->appraisalgoaldetail->kpi_description ?? '' }}
                        </td>                            
                        <td>
                            {{$goal->goal_title ?? '' }}
                        </td>
              @endforeach 

When I ran the code, I got this error:

Property [kpi_description] does not exist on this collection instance. (View: C:\xampp\htdocs\accly\resources\views\appraisal_goals\index.blade.php)

How do I resolve it?

Thank you

Activity icon

Replied to Customize Datatable For Index View Blade

Please can you give me a little example based on my code

Feb
17
1 week ago
Activity icon

Started a new Conversation Customize Datatable For Index View Blade

I am using Laravel-5.8 for my web application. In it I have a index view blade made with datatable which is derived from these two tables of dynamic input:

class AppraisalGoal extends Model
{
  protected $table = 'appraisal_goals';
  protected $primaryKey = 'id';

  protected $fillable = [
              'goal_type_id',
              'appraisal_identity_id',
              'employee_id',
              'company_id',
              'is_published',
              'is_approved',
              'weighted_score',
              'employee_comment',
              'line_manager_comment',
              'goal_title',
              'appraisal_doc',
              'appraisal_start_date',
              'appraisal_end_date',
          ];

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

public function employee()
{
    return $this->belongsTo('App\Models\Hr\HrEmployee','employee_id');
}

public function appraisalidentity()
{
    return $this->belongsTo('App\Models\Appraisal\AppraisalIdentity','appraisal_identity_id');
}

public function appraisalgoaldetail(){
    return $this->hasMany('App\Models\Appraisal\AppraisalGoalDetail');
}

}

class AppraisalGoalDetail extends Model
{  
  protected $table = 'appraisal_goal_details';
  protected $fillable = [
              'name',
              'company_id',
              'appraisal_goal_id',
              'kpi_description',
              'appraisal_doc',
              'activity',
              'start_date',
              'end_date',
          ];

 public function appraisalgoal()
 {
     return $this->belongsTo('App\Models\Appraisal\AppraisalGoal');
 }    
}

Controller

public function index()
{
  $userEmployee = Auth::user()->employee_id;
  $goals = AppraisalGoal::where('employee_id', $userEmployee)->get();

  return view('appraisal.appraisal_goals.index')->with('goals', $goals);
}

Currently, I have this index view blade:

https://i.stack.imgur.com/uphRu.png

which is derived from:

<div class="card-body">
    <div class="table-responsive">
        <table class=" table table-bordered table-striped table-hover datatable">
            <thead>
                <tr>
                    <th width="10">
                        #
                    </th>
                    <th>
                        Goal Type
                    </th>
                    <th>
                        Goal Title
                    </th>
                    <th>
                        Goal Description
                    </th>
                    <th>
                        Weight
                    </th>
                    <th>
                        Published
                    </th>
                    <th>
                        Approved
                    </th>
                    <th>
                        Line Manager's Comments
                    </th>  
                    <th>
                        Start Date
                    </th>  
                    <th>
                        End Date
                    </th>
                    <th>
                        Date Added
                    </th>
                    <th>
                        &nbsp;
                    </th>
                </tr>
            </thead>
            <tbody>
                @foreach($goals as $key => $goal)
                        <td>
                            {{$key+1}}
                        </td>
                        <td>
                            {{$goal->goaltype->name ?? '' }}
                        </td>
                        <td>
                            {{$goal->goal_title ?? '' }}
                        </td>
                        <td>
                            {{$goal->goal_description ?? '' }}
                        </td>
                        <td>
                            {{$goal->weighted_score ?? '' }}
                        </td>
                        <td>
                            @if ($goal->is_published)
                                <span class="badge bg-success">Published</span>
                            @else
                                <span class="badge bg-danger">Pending</span>
                            </a>
                            @endif
                        </td>
                        <td>
                            @if ($goal->is_approved)
                                <span class="badge bg-success" >Approved</span>
                            @else
                                <span class="badge bg-danger">Pending</span>
                            @endif
                        </td>
                        <td>
                            {{$goal->line_manager_comment ?? '' }}
                        </td>
                        <td>
                            {{Carbon\Carbon::parse($goal->start_date)->format('d-m-Y') ?? '' }}
                        </td>
                        <td>
                            {{Carbon\Carbon::parse($goal->end_date)->format('d-m-Y') ?? '' }}
                        </td>
                        <td>
                            {{Carbon\Carbon::parse($goal->created_at)->format('d-m-Y') ?? '' }}
                        </td>
                        <td>
                                @if($goal->is_published == 0)
                                <a class="btn btn-xs btn-success" data-toggle="modal" data-target="#confirm-publish{{ $goal->id }}" data-original-title="Close"> 
                                    <span style="color:white;">Publish</span>
                                </a>                                     
                                @else
                                    <span class="badge bg-danger">Published</span>
                                @endif                                
                            @can('appraisal_goal_show')
                                <a class="btn btn-xs btn-primary" href="{{ route('appraisal.appraisal_goals.show', $goal->id) }}">
                                    {{ trans('global.view') }}
                                </a>                            
                            @endcan
                            @can('appraisal_goal_edit')
                                <a class="btn btn-xs btn-info" href="{{ route('appraisal.appraisal_goals.edit', ['id'=>$goal->id]) }}">
                                    {{ trans('global.edit') }}
                                </a>
                            @endcan
                            @can('appraisal_goal_delete')
                                <a class="btn btn-xs btn-danger" data-toggle="modal" data-target="#confirm-delete{{ $goal->id }}" data-original-title="Close"> 
                                    <span style="color:white;">{{ trans('global.delete') }}</span>
                                </a>
                            @endcan   
                        </td>                                               
                </tr>
                @endforeach 
            </tbody>
        </table>
    </div>
</div> 

datatable script

<script>
    $(function() {
  let copyButtonTrans = '{{ trans('global.datatables.copy') }}'
  let csvButtonTrans = '{{ trans('global.datatables.csv') }}'
  let excelButtonTrans = '{{ trans('global.datatables.excel') }}'
  let pdfButtonTrans = '{{ trans('global.datatables.pdf') }}'
  let printButtonTrans = '{{ trans('global.datatables.print') }}'
  let colvisButtonTrans = '{{ trans('global.datatables.colvis') }}'

  let languages = {
    'en': 'https://cdn.datatables.net/plug-ins/1.10.19/i18n/English.json'
  };

  $.extend(true, $.fn.dataTable.Buttons.defaults.dom.button, { className: 'btn' })
  $.extend(true, $.fn.dataTable.defaults, {
    language: {
      url: languages.{{ app()->getLocale() }}
    },
    columnDefs: [

    {
        orderable: false,
        searchable: false,
        targets: -1
    }],
    select: {
      style:    'multi+shift',
      selector: 'td:first-child'
    },
    order: [],
    scrollX: true,
    pageLength: 100,
    dom: 'lBfrtip<"actions">',
    buttons: [

    ]
  });

  $.fn.dataTable.ext.classes.sPageButton = '';
});

</script>

How do I re-write my code to make the index view blade look like the one shown below:

https://i.stack.imgur.com/B9ZtX.png

Thanks

Activity icon

Started a new Conversation Update Dynamic Input By Adding Comment

I have used Laravel-5.8 for web application. In the application I used dynamic input.

I have these tables:

class AppraisalGoal extends Model
{
  protected $table = 'appraisal_goals';
  protected $primaryKey = 'id';

  protected $fillable = [
              'goal_type_id',
              'appraisal_identity_id',
              'employee_id',
              'company_id',
              'is_published',
              'is_approved',
              'weighted_score',
              'employee_comment',
              'line_manager_comment',
              'goal_title',
              'appraisal_doc',
              'appraisal_start_date',
              'appraisal_end_date',
          ];

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

  public function employee()
  {
      return $this->belongsTo('App\Models\Hr\HrEmployee','employee_id');
  }

  public function appraisalidentity()
  {
      return $this->belongsTo('App\Models\Appraisal\AppraisalIdentity','appraisal_identity_id');
  }

  public function appraisalgoaldetail(){
    return $this->hasMany('App\Models\Appraisal\AppraisalGoalDetail');
  }
}

class AppraisalGoalDetail extends Model
{
  protected $table = 'appraisal_goal_details';
  protected $fillable = [
              'name',
              'company_id',
              'appraisal_goal_id',
              'kpi_description',
              'appraisal_doc',
              'activity',
              'start_date',
              'end_date',
          ];

  public function appraisalgoal()
  {
      return $this->belongsTo('App\Models\Appraisal\AppraisalGoal');
  }    
}

I have successfully saved it to database using this controller:

AppisalGoalController

public function create()
{
$userCompany = Auth::user()->company_id;

$identities = DB::table('appraisal_identity')->select('id','appraisal_name')->where('company_id', $userCompany)->where('is_current', 1)->first();

$goaltypes   =       AppraisalGoalType::where('company_id', $userCompany)->get(); 
 $categories = AppraisalGoalType::with('children')->where('company_id', $userCompany)->whereNull('parent_id')->get();

return view('appraisal.appraisal_goals.create')
        ->with('goaltypes', $goaltypes)
        ->with('categories', $categories)
        ->with('identities', $identities);
}

public function store(StoreAppraisalGoalRequest $request)
{
$validated = $request->validated();     
$appraisalStartDate = Carbon::parse($request->appraisal_start_date);
$appraisalEndDate = Carbon::parse($request->appraisal_end_date);        
$userCompany = Auth::user()->company_id;
$employeeId = Auth::user()->employee_id;
  $identities = DB::table('appraisal_identity')->select('id','appraisal_name')->where('company_id', $userCompany)->where('is_current', 1)->first();
try {
    $goal = new AppraisalGoal();
    $goal->goal_type_id             = $request->goal_type_id;
    $goal->appraisal_identity_id    = $request->appraisal_identity_id;
    $goal->employee_id              = $employeeId;
    $goal->weighted_score           = $request->weighted_score;
    $goal->goal_title               = $request->goal_title;
    $goal->goal_description         = $request->goal_description;

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

    foreach ( $request->activity as $key => $activity){
        $startDate = Carbon::parse($request->start_date[$key]);
        $endDate = Carbon::parse($request->end_date[$key]);

        $goaldetail = new AppraisalGoalDetail();

        $goaldetail->kpi_description            = $request->kpi_description[$key];
        $goaldetail->appraisal_doc              = $request->application_doc[$key];
        $goaldetail->activity                   = $request->activity[$key];  
        $goaldetail->start_date                 = $startDate ->toDateTimeString();
        $goaldetail->end_date                   = $endDate->toDateTimeString();                  
        $goaldetail->appraisal_goal_id          = $goal->id;
        $goaldetail->save();
     }
    $min_date = AppraisalGoalDetail::select('start_date')->where('appraisal_goal_id', $goal->id)->min('start_date');
    $max_date = AppraisalGoalDetail::select('end_date')->where('appraisal_goal_id', $goal->id)->max('end_date');             

     $goal->update([
         'appraisal_start_date' => $min_date,
         'appraisal_end_date'   => $max_date
             ]);
        Session::flash('success', 'Appraisal Goal is created successfully');
        return redirect()->route('appraisal.appraisal_goals.index');
} catch (Exception $exception) {
        Session::flash('danger', 'Appraisal Goal creation failed!');
        return redirect()->route('appraisal.appraisal_goals.index');
}
}

and this is my create screen:

https://i.stack.imgur.com/DoFd4.png

This is successfully saved to the database.

Now the issue I have is this, I want to update the saved records by just adding comment and status as shown in the diagram below:

https://i.stack.imgur.com/Qr5rQ.png

When I click on submit, it should updated the record with comment and approve/deny

This is my indexController

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

How do I write the controller and view to achieve this?

Thank you.

Activity icon

Replied to Customized Ellipsis In Laravel

See what I have

 testingtestingtestin<button class="show-more"> ...</button>

When I applied this

{{str_limit($announcement->description, $limit = 20, $end = '<button class="show-more"> ...</button>')}}

Its showing the code

Activity icon

Started a new Conversation Customized Ellipsis In Laravel

I used HTML text editor in Laravel-5.8

Controller

public function create()
{
    return view('organization.announcements.create');
}

public function store(StoreAnnouncementRequest $request)
{
    try {
        $announcement = new OrgAnnouncement();
        $announcement->title                    = $request->title;
        $announcement->description              = $request->description;
        
              
        $announcement->save();                               
            
            Session::flash('success', 'Announcement is created successfully');
            return redirect()->route('organization.announcements.index');
    } catch (Exception $exception) {
            Session::flash('danger', 'Announcement creation failed!');
            return redirect()->route('organization.announcements.index');
    }
}

View

        <table class=" table table-bordered table-striped table-hover datatable">
            <thead>
                <tr>

                    <th width="10">
                        #
                    </th>
                    <th>
                        Announcement Title
                    </th> 
                    <th>
                        Description
                    </th>                        
                    <th>
                        &nbsp;
                    </th>
                </tr>
            </thead>
            <tbody>
                @foreach($announcements as $key => $announcement)
                        <td>
                            {{$key+1}}
                        </td>
                        <td>
                            {{$announcement->title ?? '' }}
                        </td>
                        <td>
                            {{str_limit($announcement->description, $limit = 20, $end = ' ...')}}
                        </td>                            
                        <td>
                            @can('announcement_show')
                                <a class="btn btn-xs btn-primary" href="{{ route('organization.announcements.show', $announcement->id) }}">
                                    {{ trans('global.view') }}
                                </a>                            
                            @endcan
                            @can('announcement_edit')
                                <a class="btn btn-xs btn-info" href="{{ route('organization.announcements.edit', ['id'=>$announcement->id]) }}">
                                    {{ trans('global.edit') }}
                                </a>
                            @endcan
                            @can('announcement_delete')
                                <a class="btn btn-xs btn-danger" data-toggle="modal" data-target="#confirm-delete{{ $announcement->id }}" data-original-title="Close"> 
                                    <span style="color:white;">{{ trans('global.delete') }}</span>
                                </a>
                            @endcan
                            
                        <div class="modal fade" id="confirm-delete{{ $announcement->id }}" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
                          <div class="modal-dialog">
                            <div class="modal-content">
                              <div class="modal-header">
                                <h4 class="modal-title">Delete Announcement</h4>
                                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                  <span aria-hidden="true">&times;</span>
                                </button>
                              </div>
                              <div class="modal-body">
                                <form action="{{route('organization.announcements.destroy',$announcement->id)}}" method="post">
                                    {{ csrf_field() }}
                                    <p>Are you sure you want to delete this Announcement?</p>
                                    <div class="modal-header">
                                        <h4>{{ $announcement->title }}</h4>
                                    </div>
                                </form>
                              </div>
                              <div class="modal-footer justify-content-between">
                                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                                <button type="submit" class="btn btn-danger">Delete</button>
                              </div>
                            </div>
                            <!-- /.modal-content -->
                          </div>
                          <!-- /.modal-dialog -->
                        </div>
                        <!-- /.modal -->  
                        </td>
                                           
                </tr>
                @endforeach 
            </tbody>
        </table>

The field description is the text editor. On the view blade, I truncated to 20 characters and ... will be displayed as shown in my field.

However, what I want to achieve is that I want to replace the ... with a button that will have view more. Then it is clicked, it will show the full content in a modal form of redirect to another page.

How do I achieve this?

Thank you

Feb
16
1 week ago
Activity icon

Started a new Conversation How To Make Dropdownlist Onchange To Populate Textboxes

I am using Laravel-5.8 for a web application project as shown below:

Model Classes

class AppraisalGoalType extends Model
{
    protected $table = 'appraisal_goal_types';

    protected $fillable = [
              'name',
              'company_id',
              'parent_id',
              'max_score',
          ];

    public function children()
    {
      return $this->hasMany('App\Models\Appraisal\AppraisalGoalType', 'parent_id');
    }

    public function appraisalgoals()
    {
       return $this->hasMany('App\Models\Appraisal\AppraisalGoal');
    }
 }

    class AppraisalGoal extends Model
    {
        protected $table = 'appraisal_goals';

        protected $fillable = [
              'goal_type_id',
              'appraisal_identity_id',
              'employee_id',
              'company_id',
              'weighted_score',
          'employee_max_score',
              'total_weighted_score',
              'employee_comment',
              'goal_title',
              'appraisal_doc',
          ];

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

  public function employee()
  {
    return $this->belongsTo('App\Models\Hr\HrEmployee','employee_id');
  }

  public function appraisalidentity()
  {
    return $this->belongsTo('App\Models\Appraisal\AppraisalIdentity','appraisal_identity_id');
  }  
}

Controller

public function create()
{
    $userCompany = Auth::user()->company_id;

    $identities = DB::table('appraisal_identity')->select('id','appraisal_name')->where('company_id', $userCompany)->where('is_current', 1)->first();
    
    $goaltypes   =       AppraisalGoalType::where('company_id', $userCompany)->get(); 
     $categories = AppraisalGoalType::with('children')->where('company_id', $userCompany)->whereNull('parent_id')->get();
    
    return view('appraisal.appraisal_goals.create')
            ->with('goaltypes', $goaltypes)
            ->with('categories', $categories)
            ->with('identities', $identities);
}

public function store(StoreAppraisalGoalRequest $request)
{
    $validated = $request->validated();       
    $appraisalStartDate = Carbon::parse($request->appraisal_start_date);
    $appraisalEndDate = Carbon::parse($request->appraisal_end_date);        
    $userCompany = Auth::user()->company_id;
    $employeeId = Auth::user()->employee_id;
      $identities = DB::table('appraisal_identity')->select('id','appraisal_name')->where('company_id', $userCompany)->where('is_current', 1)->first();
    try {
        $goal = new AppraisalGoal();
        $goal->goal_type_id             = $request->goal_type_id;
        $goal->appraisal_identity_id    = $request->appraisal_identity_id;
        $goal->employee_id              = $employeeId;
        $goal->weighted_score           = $request->weighted_score;
        $goal->goal_title               = $request->goal_title;
        
             if ($request->appraisal_doc != "") {
                 $appraisal_doc = $request->file('appraisal_doc');
                 $new_name = rand() . '.' . $appraisal_doc->getClientOriginalExtension();
                 $appraisal_doc->move(public_path('storage/documents/appraisal_goal'), $new_name);
                 $goal->appraisal_doc = $new_name;
            }                       
        $goal->save();
         
         $goal->update([
             'appraisal_start_date' => $min_date,
             'appraisal_end_date'   => $max_date
                 ]);
         
            Session::flash('success', 'Appraisal Goal is created successfully');
            return redirect()->route('appraisal.appraisal_goals.index');
    } catch (Exception $exception) {
            Session::flash('danger', 'Appraisal Goal creation failed!');
            return redirect()->route('appraisal.appraisal_goals.index');
    }
}

View

   <form  action="{{route('appraisal.appraisal_goals.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-6">
            <div class="form-group">
              <label class="control-label"> Goal Type:<span style="color:red;">*</span></label>
              <select id="goal_type" class="form-control" name="goal_type_id">
                <option value="">Select Goal Type</option>

                @foreach ($categories as $category)
                @unless($category->name === 'Job Fundamentals')
                  <option hidden value="{{ $category->id }}" {{ $category->id == old('category_id') ? 'selected' : '' }}>{{ $category->name }}</option>

                  @if ($category->children)
                    @foreach ($category->children as $child)
                    @unless($child->name === 'Job Fundamentals')
                      <option value="{{ $child->id }}" {{ $child->id == old('category_id') ? 'selected' : '' }}>&nbsp;&nbsp;{{ $child->name }}</option>
                    @endunless
                    @endforeach
                  @endif
                  @endunless
                @endforeach
              </select>
            </div>
          </div>    
            <input type="hidden" name="appraisal_identity_id" value="{{$identities->id}}">
          <div class="col-12 col-sm-6">
            <div class="form-group">
              <label class="control-label"> Goal Title:<span style="color:red;">*</span></label>
              <input  type="text" name="goal_title" placeholder="Enter goal title here" class="form-control">
            </div>
          </div>

          <div class="col-12 col-sm-6">
            <div class="form-group">
              <label class="control-label"> Weight:<span style="color:red;">*</span></label>
              <input  type="number" name="weighted_score" placeholder="Enter weighted score here" class="form-control">
            </div>
          </div>  

          <div class="col-12 col-sm-6">
            <div class="form-group">
              <label class="control-label"> Employee Max. Score:</label>
              <input  type="number" name="employee_max_score" class="form-control" disabled>
            </div>
          </div> 

          <div class="col-12 col-sm-6">
            <div class="form-group">
              <label class="control-label"> Total Weighted Score:</label>
              <input  type="number" name="total_weighted_score" class="form-control" disabled>
            </div>
          </div> 

          <div class="col-12 col-sm-6">
            <div class="form-group">
                <label class="control-label"> Attachment:</label>
                    <div class="custom-file">
                        <input type="file" name="appraisal_doc" class="custom-file-input" id="customFile">
                        <label class="custom-file-label" for="exampleInputFile">Choose file</label>
                    </div>
            </div>
          </div>

       </div>
     </div>
    </div>          

    <div class="card-footer">
      <button type="submit" class="btn btn-primary">{{ trans('global.save') }}</button>
      <button type="button" onclick="window.location.href='{{route('appraisal.appraisal_goals.index')}}'" class="btn btn-default">Cancel</button>
    </div>                  
    </form>

What I want to achieve is this:

When Dropdown for goal_type_id (goal_type) is onChange

  1. it should search appraisal_goals and load weighted_score into textbox where employee_id = $employeeId, appraisal_identity_id = $identities and goal_type_id = $categories. This is total_weighted_score

  2. it should search appraisal_goal_types and load max_score into textbox where parent_id = $categories. This is employee_max_score

Feb
14
1 week ago
Activity icon

Replied to How To Ensure That Order Price Is Not Less Than Product Price

Please can you give me a sample

Activity icon

Started a new Conversation How To Ensure That Order Price Is Not Less Than Product Price

I am working on dynamic input field using Laravel-5.8. The project is based on Sales Order.

Model

class Product extends Model
{
  protected $table = 'products';
  protected $fillable = [
          'name',
          'rate',
          'vat',
      ];
}

class Order extends Model
{
  protected $table = 'orders';
  protected $fillable = [
          'date',
          'customer_id',
          'workOrder_id',
          'details',
          'product_id',
          'rate',
          'vat',
          'quantity',
          'remaining',
      'amount',
      ];

  public function customer(){
    return $this->belongsTo(Customer::class, 'customer_id');
  }

  public function product(){
      return $this->belongsTo(Product::class, 'product_id');
  }
}

product_id in products is a foreign key to orders

Controller

public function create()
{
    $order = null;
    $products = Product::all('id','name');
    $customers = Customer::all('id','name');
    return view('pages.order.create', compact('order','products','customers'));
}

public function store(Request $request)
{
    $request->validate([
        'date'      => 'required',
        'customer_id'  => ['required', Rule::notIn(['','0'])],
        'workOrder_id'     => 'required|unique:orders',
    ]);

    for ($i=0; $i < count($request->product_id) ; $i++) { 

        $order =  new Order;

        $order->date = $request->date;
        $order->customer_id = $request->customer_id;
        $order->workOrder_id = $request->workOrder_id;
        $order->details = $request->details;
        $order->product_id = $request->product_id[$i];
        $order->rate = $request->rate[$i];
        $order->vat = $request->vat[$i];
        $order->quantity = $request->quantity[$i];
        $order->remaining = $request->quantity[$i];
        $order->amount = $request->quantity[$i] * $request->rate[$i];

        $order->save();
    }

    return redirect()
                ->route('order.index')
                ->with('success', 'Added Successfully');
}

In an order, a customer can have several products

view

<section class="content">
    <div class="container-fluid">
        <div class="card card-warning">
            <div class="card-body">
                <form method="POST" action="{{ route('order.store') }}">
                    @csrf
                    {{-- Date --}}
                    <div class="form-group">
                        <label for="date">
                            Date
                        </label>

                        <input type="text" class="form-control{{ $errors->has('date') ? ' is-invalid' : '' }}" name="date" id="date" value="{{ old('date', optional($order)->date) }}">

                        @if ($errors->has('date'))
                        <span class="invalid-feedback">
                            <strong>{{ $errors->first('date') }}</strong>
                        </span>
                        @endif
                    </div>

                    {{-- customer --}}
                    <div class="form-group">
                        <label for="customer_id">Customer</label>
                        <select name="customer_id" class="form-control{{ $errors->has('customer_id') ? ' is-invalid' : '' }}" id="customer_id">
                            <option value="">Select</option>
                            @foreach($customers as $customer)
                            <option value="{{ $customer->id }}" {{old('customer_id', optional($order)->customer_id) == $customer->id ? 'selected':''}}>{{ $customer->name }}</option>
                            @endforeach
                        </select>
                        @if ($errors->has('customer_id'))
                        <span class="invalid-feedback">
                            <strong>{{ $errors->first('customer_id') }}</strong>
                        </span>
                        @endif
                    </div>

                    <div class="row">
                        <div class="col-md-1">
                            <button id="add_more" class="btn btn-info mt-4"><i class="fa fa-plus" title="Add More Product"></i></button>
                        </div>
                        <div class="col-md-11">
                            <div id="more_product">
                                <div class="row">
                                    <div class="col-md-3">
                                        {{-- Product --}}
                                        <div class="form-group">
                                            <label for="product_id">Select Product</label>
                                            <select name="product_id[]" class="form-control" id="product_id" required="required">
                                                <option value="">Select Product</option>
                                                @forelse($products as $product)
                                                <option value="{{ $product->id }}" >
                                                    {{ $product->name }}
                                                </option>
                                                @empty
                                                <option value="">No Product Found</option>
                                                @endforelse
                                            </select>
                                        </div>
                                    </div>
                                    <div class="col-md-3">
                                        {{-- Rate --}}
                                        <div class="form-group">
                                            <label for="rate">
                                                Rate
                                            </label>
                                            <input type="number" min="0" step="any" class="form-control" name="rate[]" id="rate" required="required">
                                        </div>
                                    </div>

                                    <div class="col-md-3">
                                        {{-- Quantity --}}
                                        <div class="form-group">
                                            <label for="vat">
                                                Vat
                                            </label>

                                            <input type="number" min="0" step="any" class="form-control" name="vat[]" id="vat" required="required">
                                        </div>
                                    </div>
                                    <div class="col-md-3">
                                        {{-- Quantity --}}
                                        <div class="form-group">
                                            <label for="quantity">
                                                Quantity
                                            </label>

                                            <input type="number" min="0" class="form-control" name="quantity[]" id="quantity" required="required">
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    {{-- workOrder_id --}}
                    <div class="form-group">
                        <label for="workOrder_id">Work Order No</label>
                        <input type="text" class="form-control{{ $errors->has('workOrder_id') ? ' is-invalid' : '' }}" name="workOrder_id" id="workOrder_id" value="{{ old('workOrder_id', optional($order)->workOrder_id) }}">

                        @if ($errors->has('workOrder_id'))
                        <span class="invalid-feedback">
                            <strong>{{ $errors->first('workOrder_id') }}</strong>
                        </span>
                        @endif
                    </div>

                    {{-- Payment Type --}}

            {{-- <div class="form-group">
                <label for="payment">Payment</label>
                <select name="payment" class="form-control{{ $errors->has('payment') ? ' is-invalid' : '' }}" id="payment">
                    <option value="">Select Payment</option>
                    <option value="1">Cash</option>
                    <option value="2">Due</option>
                </select>
                @if ($errors->has('payment'))
                <span class="invalid-feedback">
                    <strong>{{ $errors->first('payment') }}</strong>
                </span>
                @endif
            </div> --}}


            {{-- Details --}}
            <div class="form-group">
                <label for="details">
                    Remarks
                </label>

                <textarea name="details" class="form-control {{ $errors->has('details') ? ' is-invalid' : '' }}" id="details" cols="30" rows="5">{{ old('details', optional($order)->details) }}</textarea>

                @if( $errors->has('details'))
                <span class="invalid-feedback">
                    <strong>{{ $errors->first('details') }}</strong>
                </span>
                @endif
            </div>

            {{-- Save --}}
            <div class="form-group row mb-0">
                <div class="col-md-12">
                    <button type="submit" class="btn btn-primary">
                        {{ __('Save') }}
                    </button>
                </div>
            </div>
        </form>
    </div>
</div>
</div>
</section>

Javascript

<script>
{{-- jquery datepicker --}}
$( function() {
    $( "#date" ).datepicker({
        dateFormat: 'yy-mm-dd',
        changeMonth: true,
        changeYear: true,
    });
});


$('#customer_id').select2({
    placeholder: 'Select Customer',

    ajax: {
        url: '{!!URL::route('customer-autocomplete-search')!!}',
        dataType: 'json',
        delay: 250,
        processResults: function (data) {
            return {
                results: data
            };
        },
        cache: true
    },
    theme: "bootstrap"
});

$('#product_id').select2({
    placeholder: 'Select Product',

    ajax: {
        url: '{!!URL::route('product-autocomplete-search')!!}',
        dataType: 'json',
        delay: 250,
        processResults: function (data) {
            return {
                results: data
            };
        },
        cache: true
    },
    theme: "bootstrap"
});

$(document).ready(function() {
    var max_fields      = 150;
    var wrapper         = $("#more_product");
    var add_button      = $("#add_more");

    var x = 1;
    $(add_button).click(function(e){
        e.preventDefault();
        if(x < max_fields){
            x++;
            $(wrapper).append('<div class="row"><div class="col-md-3">{{-- Product --}}<div class="form-group"><label for="product_id">Select Product</label><select name="product_id[]" class="form-control product_id" id="product_id" required="required"><option value="">Select Product</option>@forelse($products as $product)<option value="{{ $product->id }}" >{{ $product->name }}</option>@empty<option value="">No Product Found</option>@endforelse </select></div></div><div class="col-md-3">{{-- Rate --}}<div class="form-group"><label for="rate">Rate</label><input type="number" min="0" step="any" class="form-control" name="rate[]" id="rate" required="required"></div></div><div class="col-md-2">{{-- vat --}}<div class="form-group"><label for="vat">Vat</label><input type="number" min="0" step="any" class="form-control" name="vat[]" id="vat" required="required"></div></div><div class="col-md-3">{{-- Quantity --}}<div class="form-group"><label for="quantity">Quantity</label><input type="number" min="0" class="form-control" name="quantity[]" id="quantity" required="required"></div></div><div class="col-sm-1"><a href="#" class="remove_field"><button style="margin-top: 30px;" class="btn btn-info"><i class="fa fa-minus" title="Remove Item"></i></button></a></div></div>');

            $('.product_id').select2({
                placeholder: 'Select Product',

                ajax: {
                    url: '{!!URL::route('product-autocomplete-search')!!}',
                    dataType: 'json',
                    delay: 250,
                    processResults: function (data) {
                        return {
                            results: data
                        };
                    },
                    cache: true
                },
                theme: "bootstrap"
            });
        }
    });

    $(wrapper).on("click",".remove_field", function(e){
        e.preventDefault(); 
        $(this).parent().parent('div').remove(); 
        x--;
    })
});
</script>

I have been on this for days. What I want to achieve is that as the User enter the rate on order on a particular product, the system should compare it with the rate in products.

If the rate on order is less than that in product, the system should display an error message to the user explaining the problem.

How do I achieve this?

Thank you

Feb
12
1 week ago
Activity icon

Replied to How To Make Students Not To Score Beyond The Max Mark

I think I'm getting some some clue from what you posted. The only thing is that the max score is not fixed. Based on my question the application will validate all the scores of the student (obtained score) based on the subject_group score with the subject_group score (obtainable score) in the database.