noblemfd

noblemfd

Member Since 4 Weeks Ago

Experience Points
2,270
Total
Experience

2,730 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 1
2,270 XP
Jan
17
22 hours ago
Activity icon

Replied to How To Set Role From Employee Controller

@snapey No, I am not assigning role from user but since role is directly linked to user I will need to know how to call role from user into employee. From the code above, I am assigning role from from Employee and I am also automatically assigning the value of employee email as user email and employee username to user username. The user controller will not function, but employee controller will take charge.

The default role should be Employee, but at update the Admin can assign other roles.

Thanks

Activity icon

Started a new Conversation How To Set Role From Employee Controller

I am using Laravel Spatie for User Role and Permission Management. Initially, I have set the Role from user Contoller and user view blade using

UserController

public function create()
{
    $roles = Role::get()->pluck('name', 'name');

    return view('admin.users.create', compact('roles'));
}

public function store(StoreUsersRequest $request)
{
    $user = User::create($request->all());
    $roles = $request->input('roles') ? $request->input('roles') : [];
    $user->assignRole($roles);

    return redirect()->route('admin.users.index');
}

User Model

class User extends Authenticatable
{
  use Notifiable;
  use HasRoles;

protected $fillable = ['name', 'employee_id','email', 'password', 'remember_token'];

public function setPasswordAttribute($input)
{
    if ($input)
        $this->attributes['password'] = app('hash')->needsRehash($input) ? Hash::make($input) : $input;
}


public function role()
{
    return $this->belongsToMany(Role::class, 'role_user');
}   
}

view

    <form action="{{ route("admin.users.store") }}" method="POST" enctype="multipart/form-data">
        @csrf
        <div class="form-group {{ $errors->has('name') ? 'has-error' : '' }}">
            <label for="name">{{ trans('cruds.user.fields.name') }}*</label>
            <input type="text" id="name" name="name" class="form-control" value="{{ old('name', isset($user) ? $user->name : '') }}" required>
            @if($errors->has('name'))
                <em class="invalid-feedback">
                    {{ $errors->first('name') }}
                </em>
            @endif
            <p class="helper-block">
                {{ trans('cruds.user.fields.name_helper') }}
            </p>
        </div>
        <div class="form-group {{ $errors->has('email') ? 'has-error' : '' }}">
            <label for="email">{{ trans('cruds.user.fields.email') }}*</label>
            <input type="email" id="email" name="email" class="form-control" value="{{ old('email', isset($user) ? $user->email : '') }}" required>
            @if($errors->has('email'))
                <em class="invalid-feedback">
                    {{ $errors->first('email') }}
                </em>
            @endif
            <p class="helper-block">
                {{ trans('cruds.user.fields.email_helper') }}
            </p>
        </div>
        <div class="form-group {{ $errors->has('password') ? 'has-error' : '' }}">
            <label for="password">{{ trans('cruds.user.fields.password') }}</label>
            <input type="password" id="password" name="password" class="form-control" required>
            @if($errors->has('password'))
                <em class="invalid-feedback">
                    {{ $errors->first('password') }}
                </em>
            @endif
            <p class="helper-block">
                {{ trans('cruds.user.fields.password_helper') }}
            </p>
        </div>
        <div class="form-group {{ $errors->has('roles') ? 'has-error' : '' }}">
            <label for="roles">{{ trans('cruds.user.fields.roles') }}*
                <span class="btn btn-info btn-xs select-all">{{ trans('global.select_all') }}</span>
                <span class="btn btn-info btn-xs deselect-all">{{ trans('global.deselect_all') }}</span></label>
            <select name="roles[]" id="roles" class="form-control select2" multiple="multiple" required>
                @foreach($roles as $id => $roles)
                    <option value="{{ $id }}" {{ (in_array($id, old('roles', [])) || isset($user) && $user->roles->contains($id)) ? 'selected' : '' }}>{{ $roles }}</option>
                @endforeach
            </select>
            @if($errors->has('roles'))
                <em class="invalid-feedback">
                    {{ $errors->first('roles') }}
                </em>
            @endif
            <p class="helper-block">
                {{ trans('cruds.user.fields.roles_helper') }}
            </p>
        </div>
        <div>
            <input class="btn btn-danger" type="submit" value="{{ trans('global.save') }}">
        </div>
    </form>

But now, I have another table called employee. And from there I want set the User Authentication and Role

class EmployeeController extends Controller
{
    public function create()
{
      return view('admin.employees.create');
    }

  public function store(StoreEmployee $request)
  {             
    $employee = Employee::create([
        'fname' => $request->fname,
        'lname' => $request->lname,
        'birth_date' => $request->birth_date,
        'hired_date' => $request->hired_date,
        'street' => $request->street,
        'town' => $request->town,
        'city' => $request->city,
        'country' => $request->country,
        'phone' => $request->phone,
        'gender' => $request->gender,   
        'email' => $request->email
    ]);
    
    $otp = str_random(10);
    $user= new User;
    $user->email = $employee->email;
    $user->password=bcrypt($otp);
    $user->employee_id = $employee->id;
    $user->save();

            $employee->update(['user_id' => $user->id]);

    Session::flash('success', 'New User created');
    return redirect()->route('employees.index');
}
}


class Employee extends Model
{
    use SoftDeletes;

protected $fillable = [
    'email','user_id','fname', 'lname', 'birth_date','gender','hired_date','phone',
    'street','town','city','country'
];

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

Employee View

<form action="{{ route('employees.store') }}" method="POST">
        {{ csrf_field() }}
    
    <div class="form-group col-md-6">
        <label for="fname">First Name: </label>
        <input type="text" name="fname" class="form-control">       
    </div>
    
    <div class="form-group col-md-6">
        <label for="lname">Last Name: </label>
        <input type="text" name="lname" class="form-control">       
    </div>
    
    <div class="form-group col-md-12">
        <label for="email">Email: </label>
        <input type="email" name="email" class="form-control">      
    </div>
    
    <div class="form-group col-md-4">
        <label for="birth_date">Date of Birth: </label>
        <input type="date" name="birth_date" class="form-control">      
    </div>
    
    <div class="form-group col-md-4">
        <label for="hired_date">Hired Date: </label>
        <input type="date" name="hired_date" class="form-control">      
    </div>
    
    <div class="form-group col-md-4">
        <label for="phone">Contact Phone: </label>
        <input type="text" name="phone" class="form-control">       
    </div>
    
    <div class="form-group col-md-12">
        <label for="street">Street: </label>
        <input type="text" name="street" class="form-control">      
    </div>
    
    <div class="form-group col-md-2">
        <label for="country">Country: </label>
        <input type="text" name="country" class="form-control">     
    </div>

    <div class="text-center">
        <button class="btn btn-success" type="submit" >Create</button>
    </div>
</form>

I got stuck in the Employee Controller, and View.

How do I now re-write EmployeeController, Model and View to be able to Add Roles from there.

Thank you.

Jan
16
1 day ago
Activity icon

Replied to How To Re-write Checkbox Form Action

Thanks

How do I now change the one for edit/update as shown below:

<div class="col-xs-12 col-sm-12 col-md-12">
    <div class="form-group">
        <strong>Permission:</strong>
        <br/>
        @foreach($permission as $value)
            <label>{{ Form::checkbox('permission[]', $value->id, in_array($value->id, $rolePermissions) ? true : false, array('class' => 'name')) }}
            {{ $value->name }}</label>
        <br/>
        @endforeach
    </div>
</div>
Activity icon

Started a new Conversation How To Re-write Checkbox Form Action

Initially I have this view blade:

{!! Form::open(array('route' => 'roles.store','method'=>'POST')) !!}
<div class="row">
<div class="col-xs-12 col-sm-12 col-md-12">
    <div class="form-group">
        <strong>Name:</strong>
        {!! Form::text('name', null, array('placeholder' => 'Name','class' => 'form-control')) !!}
    </div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12">
    <div class="form-group">
        <strong>Permission:</strong>
        <br/>
        @foreach($permission as $value)
            <label>{{ Form::checkbox('permission[]', $value->id, false, array('class' => 'name')) }}
            {{ $value->name }}</label>
        <br/>
        @endforeach
    </div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12 text-center">
    <button type="submit" class="btn btn-primary">Submit</button>
</div>
</div>
{!! Form::close() !!}

Now I changed the code to this:

    <form action="{{ route("admin.roles.store") }}" method="POST" enctype="multipart/form-data">
        @csrf
        <div class="form-group {{ $errors->has('name') ? 'has-error' : '' }}">
            <label for="title">{{ trans('global.role.fields.title') }}*</label>
            <input type="text" id="title" name="name" class="form-control" value="{{ old('name', isset($role) ? $role->name : '') }}">
            @if($errors->has('title'))
                <p class="help-block">
                    {{ $errors->first('name') }}
                </p>
            @endif
            <p class="helper-block">
                {{ trans('global.role.fields.title_helper') }}
            </p>
        </div>
  <input type="checkbox" id="checkAll" > Check All
   <hr />
  <div class="col-xs-12">
   <div class="row">
    <div class="col-xs-12">
       <strong>Permission:</strong>
    </div>
   </div>
  <div class="row">

  @foreach($permission as $value)
     <div class="form-group col-md-4">
        <label>
           {{ Form::checkbox('permission[]', $value->id, false, array('class' => 'name')) }}
           {{ $value->name }}
        </label>
     </div>
  @endforeach
 </div>
</div>
        <div>
            <input class="btn btn-primary" type="submit" value="{{ trans('global.save') }}">
        </div>
    </form>

Now the challenge I have is that I don't know how to re-write

           {{ Form::checkbox('permission[]', $value->id, false, array('class' => 'name')) }}
           {{ $value->name }}

in

  @foreach($permission as $value)
     <div class="form-group col-md-4">
        <label>
           {{ Form::checkbox('permission[]', $value->id, false, array('class' => 'name')) }}
           {{ $value->name }}
        </label>
     </div>
  @endforeach

to suite

<form action="{{ route("admin.roles.store") }}" method="POST" enctype="multipart/form-data">

instead of

{!! Form::open(array('route' => 'roles.store','method'=>'POST')) !!}

How do I achieve this?

Jan
14
3 days ago
Activity icon

Started a new Conversation Laravel Application With Spatie For Roles And Permissions

I am developing an Human Resource Applications that will use Spatie for roles & permissions. And authorized user should be able to Assign Roles and Permissions on their own.

The Menu and Views should implement @can

What are the best practices to follow when such application development?

Is there any documentation, videos, tutorials that are recommended?

Activity icon

Started a new Conversation How To Style Role View To Three Columns

I am using Laravel-5.8 for Spatie role based. I have no problem with the Spatie, but the only thing is that the Role Permission Checkbox is only on column and its too long.

<div class="col-xs-12 col-sm-12 col-md-12">
    <div class="form-group">
        <strong>Permission:</strong>
        <br/>
        @foreach($permission as $value)
            <label>{{ Form::checkbox('permission[]', $value->id, false, array('class' => 'name')) }}
            {{ $value->name }}</label>
        <br/>
        @endforeach
    </div>
</div>

How do I style it that it will be three (3) column like col-md-4 into order to allow it spread, look more attractive and occupy less space.

Thank you

Jan
12
5 days ago
Activity icon

Replied to How To Validate And Show A Message For Wrong Username And Password

The issue is that its not showing anything when its wrong. It just remain like that. I want to make it interactive.

Activity icon

Started a new Conversation How To Validate And Show A Message For Wrong Username And Password

I have this controller and view

class LoginController extends Controller
{
   protected $redirectTo = '/dashboard';

   public function __construct()
  {
     $this->middleware('guest')->except('logout');
  }
}

View

       <form action="{{ route('login') }}" method="POST">
            {{ csrf_field() }}
            
            <div class="input-group mb-3">
                <input id="email" type="email" class="form-control{{ $errors->has('email') ? ' is-invalid' : '' }}" name="email" placeholder="Username or Email" value="{{ old('email') }}" required autofocus>
                <div class="input-group-append">
                    <!--<span class="fa fa-envelope input-group-text"></span>--> 
                <div class="input-group-text">
                    <span class="fas fa-user"></span>
                </div>
                    @if ($errors->has('email'))
                    <span class="invalid-feedback" role="alert">
                       <strong>{{ $errors->first('email') }}</strong>
                    </span> 
                    @endif
                </div>
            </div>

            <div class="input-group mb-3">
                <input id="password" type="password" class="form-control{{ $errors->has('password') ? ' is-invalid' : '' }}" placeholder="Password" name="password" required>
                <div class="input-group-append">
                <div class="input-group-append">
                  <div class="input-group-text">
                    <span class="fas fa-lock"></span>
                  </div>
                </div>
                    @if ($errors->has('password'))
                    <span class="invalid-feedback" role="alert">
                        <strong>{{ $errors->first('password') }}</strong>
                    </span> @endif
                </div>
            </div>

            <div class="row">
                <div class="col-8">
                    <input type="checkbox" name="remember"> {{ trans('global.remember_me') }}
                </div>
                <!-- /.col -->
                <div class="col-4">
                    <button type="submit" class="btn btn-primary btn-block btn-flat">{{ trans('global.login') }}</button>
                </div>
                <!-- /.col -->
            </div>
        </form>

At Login, I want the application to show a message whenever the user entered wrong username or password. What's it's only doing now is when its not an email.

How do I achieve this?

Thank you

Jan
10
1 week ago
Activity icon

Started a new Conversation Laravel Azure AD Authentication Redirect Me Back To Login Page

I am using Laravel-5.8 for User Azure AD Authentication. I installed this package:

composer require socialiteproviders/microsoft-azure
"socialiteproviders/microsoft-azure": "^3.0",

I also did the configuration. The regular Login from database is working perfecting, but I have issues with the Laravel microsoft-azure integration.

Login Controller

<?php

namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;
use Socialite;

class LoginController extends Controller 
{ 
  use AuthenticatesUsers;
  protected $redirectTo = '/dashboard';

  public function __construct()
  {
    $this->middleware('guest')->except('logout');
  }

  public function redirectToProvider()
  {
   return Socialite::with('azure')->redirect();
  }

  public function handleProviderCallback()
  {
    $user = Socialite::with('azure')->user();
  }

login.blade

<form class="login-form" method="POST" action="{{ route('login') }}">
{{ csrf_field() }}

<div class=" w3l-form-group{{ $errors->has('email') ? ' has-error' : '' }}">
    <label>Username:</label>
    <div class="group">
        <i class="fas fa-user"></i>
        <input id="email" type="text" class="form-control" name="email" placeholder="Email" required autofocus>
    <div>
    </div>
    </div>
</div>
<div>
    @if ($errors->has('email'))
        <span class="help-block" style="color: red">
            <strong>{{ $errors->first('email') }}</strong>
        </span>
    @endif
</div>

<div class=" w3l-form-group{{ $errors->has('password') ? ' has-error' : '' }}">
    <label>Password:</label>
    <div class="group">
        <i class="fas fa-unlock"></i>
        <input id="password" type="password" class="form-control" name="password" placeholder="Password"  required>
        @if ($errors->has('password'))
            <span class="help-block">
                <strong>{{ $errors->first('password') }}</strong>
            </span>
        @endif
    </div>
</div>
<button type="submit">Login</button>
<a href="{{ route('azure.login') }}" class="btn btn-primary"> Azure Login</a>
</form>

route/web.php

Route::get('login/azure', 'Auth\[email protected]')->name('azure.login');
Route::get('login/azure/callback', 'Auth\Lo[email protected]');
Route::get('/dashboard', '[email protected]')->name('dashboard');

config/services

'azure' => [
  'client_id' => env('AZURE_KEY'),
  'client_secret' => env('AZURE_SECRET'),
  'redirect' => env('AZURE_REDIRECT_URI')
],

.env

AZURE_KEY= something
AZURE_SECRET= something
AZURE_REDIRECT_URI= http://localhost:8888/salesportal/dashboard

config/app

\SocialiteProviders\Manager\ServiceProvider::class,

For the Redirect URI, In Azure portal->App registrations->find your application->Authentication

I have

http://localhost:8888/salesportal/dashboard

When I clicked on Azure Login button, it redirected me back to Login page:

  http://localhost:8888/salesportal/login

How do I resolve this?

Thank you.

Activity icon

Started a new Conversation Specify Dynamic Input Fields Based On Condition

I am using Laravel-5.8 to add dynamic input fields to an invoice. Already, I have written this code:

Controller

public function create()
{
    $customers = Customer::all();
    $products = Product::all();
    return view('invoice.create', compact('customers','products'));
}

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->total = 1000;
    $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');
}

invoice.blade

    <form  method="POST" action="{{route('invoice.store')}}">
    @csrf
       <div class="form-group col-md-3">
         <label class="control-label">Customer Name</label>
         <select name="customer_id" class="form-control">
         <option>Select Customer</option>
         @foreach($customers as $customer)
              <option name="customer_id" value="{{$customer->id}}">{{$customer->name}} </option>
         @endforeach
         </select>                            
      </div>
      <div class="form-group col-md-3">
         <label class="control-label">Date</label>
         <input name="date"  class="form-control datepicker"  value="<?php echo date('Y-m-d')?>" type="date" placeholder="Enter your email">
      </div>

      <table class="table table-bordered">
        <thead>
           <tr>
               <th scope="col">Product Name</th>
               <th scope="col">Qty</th>
               <th scope="col">Price</th>
               <th scope="col">Discount</th>
               <th scope="col">Amount</th>
               <th scope="col"><a class="addRow"><i class="fa fa-plus"></i></a></th>
             </tr>
           </thead>
           <tbody>
               <tr>
                 <td><select name="product_id[]" class="form-control productname" >
                    <option>Select Product</option>
                  @foreach($products as $product)
                       <option name="product_id[]" value="{{$product->id}}">{{$product->name}}</option>
                  @endforeach
                         </select></td>
                <td><input type="text" name="qty[]" class="form-control qty" ></td>
                <td><input type="text" name="price[]" class="form-control price" ></td>
                <td><input type="text" name="dis[]" class="form-control dis" ></td>
               <td><input type="text" name="amount[]" class="form-control amount" ></td>
               <td><a   class="btn btn-danger remove"> <i class="fa fa-remove"></i></a></td>
             </tr>
           </tbody>
           <tfoot>
            <tr>
             <td></td>
             <td></td>
             <td></td>
             <td><b>Total</b></td>
             <td><b class="total"></b></td>
             <td></td>
            </tr>
           </tfoot>

        </table>
        <div >
           <button class="btn btn-primary" type="submit">Submit</button>
        </div>
    </form>

javascript

<script type="text/javascript">
    $(document).ready(function(){
        $('tbody').delegate('.productname', 'change', function () {
            var  tr = $(this).parent().parent();
            tr.find('.qty').focus();
        })
        $('tbody').delegate('.productname', 'change', function () {
            var tr =$(this).parent().parent();
            var id = tr.find('.productname').val();
            var dataId = {'id':id};
            $.ajax({
                type    : 'GET',
                url     :'{!! URL::route('findPrice') !!}',
                dataType: 'json',
                data: {"_token": $('meta[name="csrf-token"]').attr('content'), 'id':id},
                success:function (data) {
                    tr.find('.price').val(data.sales_price);
                }
            });
        });
        $('tbody').delegate('.qty,.price,.dis', 'keyup', function () {
            var tr = $(this).parent().parent();
            var qty = tr.find('.qty').val();
            var price = tr.find('.price').val();
            var dis = tr.find('.dis').val();
            var amount = (qty * price)-(qty * price * dis)/100;
            tr.find('.amount').val(amount);
            total();
        });
        function total(){
            var total = 0;
            $('.amount').each(function (i,e) {
                var amount =$(this).val()-0;
                total += amount;
            })
            $('.total').html(total);
        }
        $('.addRow').on('click', function () {
            addRow();
        });
        function addRow() {
            var addRow = '<tr>\n' +
                '         <td><select name="product_id[]" class="form-control productname " >\n' +
                '         <option value="0" selected="true" disabled="true">Select Product</option>\n' +
'                                        @foreach($products as $product)\n' +
'                                            <option value="{{$product->id}}">{{$product->name}}</option>\n' +
'                                        @endforeach\n' +
                '               </select></td>\n' +
'                                <td><input type="text" name="qty[]" class="form-control qty" ></td>\n' +
'                                <td><input type="text" name="price[]" class="form-control price" ></td>\n' +
'                                <td><input type="text" name="dis[]" class="form-control dis" ></td>\n' +
'                                <td><input type="text" name="amount[]" class="form-control amount" ></td>\n' +
'                                <td><a   class="btn btn-danger remove"> <i class="fa fa-remove"></i></a></td>\n' +
'                             </tr>';
            $('tbody').append(addRow);
        };
        $('.remove').live('click', function () {
            var l =$('tbody tr').length;
            if(l==1){
                alert('you cant delete last one')
            }else{
                $(this).parent().parent().remove();
            }
        });
    });
</script>

At the moment, when I click the '+' button three times I should have something link this in the diagram:

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

Now, what I want to achieve is this>

  1. if(Auth::user()->is_hod == '0'), the number of rows for the dynamic input fields should not be more than three (3) as shown in the diagram.

  2. if(Auth::user()->is_hod == '1'), The number of rows for or the dynamic input fields can be more than three (3)

  3. If customer name from the the dropdownlist is David, the total quantity from Qty should not be more than 10

How do I adjust my code to achieve this.

Thank you.

Activity icon

Replied to No Reply Address Is Registered For The Application In Socialite Azure AD Login

When I applied that, I got another error- Page not found as shown in the link: https://i.stack.imgur.com/5ixi7.png

Jan
09
1 week ago
Activity icon

Started a new Conversation No Reply Address Is Registered For The Application In Socialite Azure AD Login

I am using Laravel-5.8 for User Azure AD Authentication. I installed this package:

"socialiteproviders/microsoft-azure": "^3.0",

composer require socialiteproviders/microsoft-azure

I also did the configuration. The regular Login from database is working perfecting, but I have issues with the Laravel microsoft-azure integration.

Login Controller

<?php

namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;
use Socialite;

class LoginController extends Controller 
{ 
  use AuthenticatesUsers;
  protected $redirectTo = '/dashboard';

public function __construct()
{
    $this->middleware('guest')->except('logout');
}

public function redirectToProvider()
{
    return Socialite::with('azure')->redirect();
}

public function handleProviderCallback()
{
    $user = Socialite::with('azure')->user();
}

login.blade

<form class="login-form" method="POST" action="{{ route('login') }}">
    {{ csrf_field() }}

    <div class=" w3l-form-group{{ $errors->has('email') ? ' has-error' : '' }}">
        <label>Username:</label>
        <div class="group">
            <i class="fas fa-user"></i>
            <input id="email" type="text" class="form-control" name="email" placeholder="Email" required autofocus>
        <div>
        </div>
        </div>
    </div>
    <div>
        @if ($errors->has('email'))
            <span class="help-block" style="color: red">
                <strong>{{ $errors->first('email') }}</strong>
            </span>
        @endif
    </div>

    <div class=" w3l-form-group{{ $errors->has('password') ? ' has-error' : '' }}">
        <label>Password:</label>
        <div class="group">
            <i class="fas fa-unlock"></i>
            <input id="password" type="password" class="form-control" name="password" placeholder="Password"  required>
            @if ($errors->has('password'))
                <span class="help-block">
                    <strong>{{ $errors->first('password') }}</strong>
                </span>
            @endif
        </div>
    </div>
    <button type="submit">Login</button>
    <a href="{{ route('azure.login') }}" class="btn btn-primary"> Azure Login</a>
</form>

route/web.php

Route::get('login/azure', 'Auth\[email protected]')->name('azure.login');
Route::get('login/azure/callback', 'Auth\[email protected]');

config/services

'azure' => [
  'client_id' => env('AZURE_KEY'),
  'client_secret' => env('AZURE_SECRET'),
  'redirect' => env('AZURE_REDIRECT_URI')
],

.env

AZURE_KEY= something
AZURE_SECRET= something
AZURE_REDIRECT_URI= http://localhost:8888/login/microsoft/callback

config/app

\SocialiteProviders\Manager\ServiceProvider::class,

When I clicked on Azure Login button, I got this error:

AADSTS500113: No Reply Address is Registered for the Application

How do I resolve this?

Thank you.

Jan
08
1 week ago
Activity icon

Started a new Conversation Socialite Azure Login Failed In Laravel

I am using Laravel-5.8 for User Azure AD Authentication. I installed this package:

"socialiteproviders/microsoft-azure": "^3.0",

composer require socialiteproviders/microsoft-azure

I also did the configuration.

Login Controller

<?php

namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;
use Socialite;

class LoginController extends Controller
{
  use AuthenticatesUsers;
  public function __construct()
  {
    $this->middleware('guest')->except('logout');
  }  
}    

login.blade

    <form class="login-form" method="POST" action="{{ route('login') }}">
        {{ csrf_field() }}

        <div class=" w3l-form-group{{ $errors->has('email') ? ' has-error' : '' }}">
            <label>Username:</label>
            <div class="group">
                <i class="fas fa-user"></i>
                <input id="email" type="text" class="form-control" name="email" placeholder="Email" required autofocus>
            <div>
            </div>
            </div>
        </div>
        <div>
            @if ($errors->has('email'))
                <span class="help-block" style="color: red">
                    <strong>{{ $errors->first('email') }}</strong>
                </span>
            @endif
        </div>

        <div class=" w3l-form-group{{ $errors->has('password') ? ' has-error' : '' }}">
            <label>Password:</label>
            <div class="group">
                <i class="fas fa-unlock"></i>
                <input id="password" type="password" class="form-control" name="password" placeholder="Password"  required>
                @if ($errors->has('password'))
                    <span class="help-block">
                        <strong>{{ $errors->first('password') }}</strong>
                    </span>
                @endif
            </div>
        </div>
        <div class="forgot">
            <a href="{{ route('password.request') }}"> Forgot Password?</a>
            <p><input type="checkbox" value="remember-me" {{ old('remember') ? 'checked' : '' }}></p>
        </div>
        <button type="submit">Login</button>
    </form>

config/services

'azure' => [
'client_id' => env('AZURE_KEY'),
'client_secret' => env('AZURE_SECRET'),
'redirect' => env('AZURE_REDIRECT_URI')
],

.env

AZURE_KEY= 
AZURE_SECRET= 
AZURE_REDIRECT_URI= http://localhost:8888/login/microsoft/callback

config/app

\SocialiteProviders\Manager\ServiceProvider::class,

When I logged in, I got this error: Login failed

How do I resolve this?

Thank you

Activity icon

Replied to Class 'Request' Not Found In Azure AD Laravel Socialite

When I did that, I got another error:

Using $this when not in object context

and it highlights this:

  public function root()
  {
       return rtrim($this->getSchemeAndHttpHost().$this->getBaseUrl(), '/');
  }
Activity icon

Started a new Conversation Class 'Request' Not Found In Azure AD Laravel Socialite

In order to integrate Azure AD SSO, I installed this package in my application:

composer require metrogistics/laravel-azure-ad-oauth

When, I wanted to relaunch my application I got this error:

Class 'Request' not found

The error is found here:

config\azure-oath.php

 'credentials' => [
      'client_id' => env('AZURE_AD_CLIENT_ID', ''),
      'client_secret' => env('AZURE_AD_CLIENT_SECRET', ''),
      'redirect' => Request::root().'/login/microsoft/callback'
    ],

How do I resolve this?

Activity icon

Replied to Laravel - Authenticating Using Azure AD And Database

Which of these three (3) am I going to use? Or do I need all?

Activity icon

Replied to Self Referencing Dropdown Display Nothing

There is no wrong naming of line managers. What I mean by onChange is that once you click the dropdown list it displays the records

Jan
07
1 week ago
Activity icon

Replied to Self Referencing Dropdown Display Nothing

When I click on the dropdownlist, on change there is no data (employee line manager). No data is populated in the dropdownlist

Activity icon

Started a new Conversation How To Manage Application With Multiple Role Users

I am developing a web application using Laravel-5.8. The application has users with single or multiple roles. The roles are: SuperAdmin, Admin, Employee, Driver.

A user can be and Employee and at the same time Admin. Likewise, a user can be a SuperAdmin at the same time an Admin.

When each user user logs in, a want a form with drop downlist to popup. The dropdown list should contain the roles of that particular user. The the user picks his role, the application should take time to the module and dashboard of that particular role.

How do I achieve this?

Activity icon

Started a new Conversation Current Date Is Being Displayed When Date Is Null

In my Laravel project:

      @foreach($employees as $key => $employee)
               <td>
                   {{$key+1}}
               </td>
               <td>
                    {{Carbon\Carbon::parse($employee->employment_date)->format('d-m-Y') ?? '' }}
               </td>                                
         </tr>
      @endforeach

I observed that the application displayed current date (today's date) whenever the date is null.

Why is it so and how do I correct that?

Activity icon

Started a new Conversation Self Referencing Dropdown Display Nothing

In my Laravel-5.8 project, I have this model:

class HrEmployee extends Model
{
   protected $fillable = [
              'employee_code',
              'line_manager_id',
              'first_name',
              'last_name',
          ];

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

Controller

public function create()

    $linemanagers       =       HrEmployee::all();
    return view('hr.employees.create')
            ->with('linemanagers', $linemanagers);
}

HrEmployee is referencing itself through line_manager_id, and its to generate a dropdownlist by displaying first_name.

    <form action="{{ route("hr.employees.store") }}" method="post" class="form-horizontal" enctype="multipart/form-data">

        {{csrf_field()}}
          <div class="col-12 col-sm-4">
            <div class="form-group">
                <label class="control-label"> Line Manager:</label>
              <select class="form-control select2bs4" data-placeholder="Choose Line Manager" tabindex="1" name="line_manager_id" style="width: 100%;">
                <option value="">Select Line Manager</option>
                   @if($linemanagers->count() > 0 )
                     @foreach($linemanagers as $linemanager)
                       <option value="{{$linemanager->id}}">{{$linemanager->first_name}}</option>
                     @endforeach
                   @endif
              </select>
            </div>
            <!-- /.form-group -->
          </div>          
          

      </div>
      <!-- /.card-body -->
      <div class="card-footer">
        <button type="submit" class="btn btn-primary">Add Company</button>
        <button type="button" onclick="window.location.href='{{route('hr.employees.index')}}'" class="btn btn-default">Cancel</button>
      <!--</div>-->
    </div>
   </form>

But I observed that its displaying nothing.

How do I resolve this?

Jan
06
1 week ago
Activity icon

Started a new Conversation Validating Scores In Laravel

I am developing a goal-setting application using Laravel-5.8. I have a table called goal_types as shown below:

GoalType

protected $fillable = [
          'goal_type',
          'score'
      ];

GoalTypeController

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

 public function store(StoreGoalTypeRequest $request)

   $goaltype = GoalType::create([
      'goal_type'              => $request->goal_type,
      'score'                  => $request->score,
  ]);
   Session::flash('success', 'Goal Type is created successfully');
   return redirect()->route('goal_types.index');
}

create.blade.php

   <form  action="{{route('goal_types.store')}}" method="post" class="form-horizontal" enctype="multipart/form-data">
       {{csrf_field()}}
                    <div class="form-body">
                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group row">
                                    <label class="control-label text-right col-md-3">Goal Type<span style="color:red;">*</span></label>
                                    <div class="col-md-9 controls">
                                        <input  type="text" name="goal_type" placeholder="Enter goal type here" class="form-control" value="{{old('goal_type')}}">
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group row">
                                    <label class="control-label text-right col-md-3">Score<span style="color:red;">*</span></label>
                                    <div class="col-md-9 controls">
                                        <input  type="number" name="max_score" placeholder="Enter score here" class="form-control" value="{{old('score')}}" step="0.01">
                                    </div>
                                </div>
                            </div>
                            <!--/span-->

                        </div>
                    </div>
      
        <div>
            &nbsp;&nbsp;&nbsp;<button type="submit" class="btn btn-primary">{{ trans('global.save') }}</button>
            <button type="button" onclick="window.location.href='{{route('goal_types.index')}}'" class="btn btn-default">Cancel</button>
        </div>
    </form>

The field goal_type will consist of these five parameters (Plan1, Plan2, Plan3, Dev, Job), and should be entered one after the other.

For the field score, this is what I want to achieve:

The sum of Plan1, Plan2 and Plan3 should not be more than 75
Dev should be exactly 15 while Job should be exactly 10. So that everything is 100%

How do I validate my code to achieve this?

Thank you.

Activity icon

Started a new Conversation Master Detail Form With Just Two Tables

I am developing an appraisal management system using Master Detail Form with just three tables:

  1. Goals

  2. KPI

  3. Goal Types

Models

Goal

protected $fillable = [
    'goal_name',
    'goal_description',
];

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

KPI

protected $fillable = [
'goal_id
    'goal_type_id',
    'kpi_description',
];

GoalController

public function create()
{
    $goaltypes = GoalType::all();
    return view('goals.create');
}

Goal Type

protected $fillable = [
              'goal_type_name'
          ];

public function store(StoreGoalRequest $request)
{
    
    $goaltype = GoalType::create([
        'goal_name'                 => $request->goal_name,
         'goal_description'         => $request->goal_description,
        'created_by'                => Auth::user()->id,
        'created_at'                => date("Y-m-d H:i:s"),
        'is_active'                 => 1,
    ]);
    Session::flash('success', 'Appraisal Goal is created successfully');
    return redirect()->route('goals.index');
}

One Goal will have many KPI. The goal_name, goal_type_name and goal_description are entered only once at an instance. goal_type_name is a dropdown derived from goal_type_id.

I want to create a master detail form, whereby there will be a add button that will add kpi_description (text box) several times.

When save button is clicked:

  1. goal_name and goal_description will be saved in goals table

  2. goal_type_id from the dropdown, goal_id from goals table and kpi_description will be saved in the kpi table

  3. nothing is saved in goal_type table. It only supplies the goal_type_id and goal_type_name for the dropdown

  4. goals table is the main controller.

How do I modify my model and controller, and also write my view to achieve this?

Thank you

Activity icon

Replied to How To Perform Complex User Registration

Thanks a lot @alanholmes. Please there is one more thing. When the employee is created, it sends an invite to the user. It integrates the user auth with his/her Azure AD Details. Its then that user becomes active.

How do I do this integration.

Thank you

Activity icon

Replied to How To Access My Laravel Project With Customized Name

When I run:

php artisan serve --host=eventcenter -- port=8888

I got thiis error: Unknown: php_network_getaddresses: getaddrinfo failed: No such host is known

Activity icon

Started a new Conversation How To Access My Laravel Project With Customized Name

I have a Laravel-5.8 on my Local Server on Windows system that access with this URL:

localhost:8888/eventcenter

How do I access it with a customized name like eventcenter with localhost:8888

Thank you

Jan
05
1 week ago
Activity icon

Replied to How To Correct 419|Page Expired

One do I instruct Laravel to direct the error to resources/views/errors/419.blade.php

Activity icon

Started a new Conversation How To Correct 419|Page Expired

In my Laravel Project, I normally have this error:

419|Page Expired

  1. How do I stop it.

  2. How do I create a custom page for it.

  3. Where is it located.

Thank you.

Activity icon

Started a new Conversation Download Sample Excel Sheet File Before Import/Upload

I have already written the code to Import/Upload Excel sheet into the database using Laravel Maatwebsite package as shown in this code.

Controller

class HrEmployeesController extends Controller
{
    public function importExportView()
    {
       return view('import');
    }

    public function import() 
    {
      Excel::import(new EmployeesImport,request()->file('file'));

      return back();
    }
}

class EmployeesImport implements ToModel, WithHeadingRow
{
   public function model(array $row)
  {
    return new HrEmployee([
      'employee_code'     => $row['employee_code'],
      'email'    => $row['email'], 
      'first_name'    => $row['first_name'],
      'last_name'    => $row['last_name'],
      'line_manager_id'    => $row['line_manager_id'],
      'employee_designation_id'    => $row['employee_designation_id'],
      'employee_job_title_id'    => $row['employee_job_title_id'],
   ]);
  }
}

View

<div class="container">
    <div class="card bg-light mt-3">
        <div class="card-header">
            Import Export Excel
        </div>
        <div class="card-body">
            <form action="{{ route('import') }}" method="POST" enctype="multipart/form-data">
                @csrf
                <input type="file" name="file" class="form-control">
                <br>
                <button class="btn btn-success">Import Employee Data</button>
            </form>
        </div>
    </div>
</div>

I have been able to import the excel file successfully. However, there is one more thing. I have a sample Excel file. Before import, I want the user to download the sample excel sheet and see how the file format is, and how it should be arranged.

The file is in this directory: public/storage/employees/employee.xlsx

How do I modify my code, expecially in the view to achieve this?

Thank you

Jan
04
1 week ago
Activity icon

Started a new Conversation HOD And Line Manager To See Only Staff Attached To Them

I have this model for employee:

class HrEmployee extends Model { public $timestamps = false;

protected $table = 'hr_employees';

protected $fillable = [
              'employee_code',
              'user_id',
              'address',
              'company_id',
              'email',
              'line_manager_id',
              'employee_designation_id',
              'employee_job_title_id',
              'employee_status_id',
              'employee_type_id',
              'employement_type_id',
              'employment_date',
              'first_name',
              'last_name',
          'is_hod'
          ];
protected $casts = [];

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

public function parent()
{
    return $this->belongsTo('HrEmployee', 'ine_manager_id');
}

public function children()
{
    return $this->hasMany('HrEmployee', 'ine_manager_id');
}

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


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

}

and controller

public function index()
{
    $userCompany = Auth::user()->company_id;
    abort_unless(\Gate::allows('employee_access'), 403);
    if (auth()->user()->isAdmin()) {
        $employees = HrEmployee::all();
    } else {
        $employees = HrEmployee::where('company_id', $userCompany)->get();
    }
    return view('hr.employees.index')->with('holidays', $holidays);
}

Already I have set it that if logged in user is Admin, he should view all. If else view his company staff only.

But, I also want the HOD to view only the employee in his department and Line manager to view only the employee that have him as line manager.

  1. For the HOD, if is_hod is 1, he should view all the employee that have his department_id

  2. For line manager, it should check all the employee that have the line_manager_id. The line_manager_id is derived from id in employee table.

How do I achieve this from the controller.

Thank you

Activity icon

Started a new Conversation User Roles And Permissions (acl) Using Spatie Example Laravel 5.8

I found this package very useful, but I need some help:

User Roles and Permissions (acl) using Spatie Example Laravel 5.8 https://github.com/savanihd/user-roles-and-permissions-acl-using-spatie-tutorial-laravel-5.8:

On the create new role where roles are created and permissions added

class RoleController extends Controller
{
function __construct()
{
     $this->middleware('permission:role-list|role-create|role-edit|role-delete', ['only' => ['index','store']]);
     $this->middleware('permission:role-create', ['only' => ['create','store']]);
     $this->middleware('permission:role-edit', ['only' => ['edit','update']]);
     $this->middleware('permission:role-delete', ['only' => ['destroy']]);
}

public function create()
{
    $permission = Permission::get();
    return view('roles.create',compact('permission'));
}

public function store(Request $request)
{
    $this->validate($request, [
        'name' => 'required|unique:roles,name',
        'permission' => 'required',
    ]);
    $role = Role::create(['name' => $request->input('name')]);
    $role->syncPermissions($request->input('permission'));
    return redirect()->route('roles.index')
                    ->with('success','Role created successfully');
}

public function edit($id)
{
    $role = Role::find($id);
    $permission = Permission::get();
    $rolePermissions = DB::table("role_has_permissions")->where("role_has_permissions.role_id",$id)
        ->pluck('role_has_permissions.permission_id','role_has_permissions.permission_id')
        ->all();
    return view('roles.edit',compact('role','permission','rolePermissions'));
}

public function update(Request $request, $id)
{
    $this->validate($request, [
        'name' => 'required',
        'permission' => 'required',
    ]);
    $role = Role::find($id);
    $role->name = $request->input('name');
    $role->save();
    $role->syncPermissions($request->input('permission'));
    return redirect()->route('roles.index')
                    ->with('success','Role updated successfully');
}
}

view: roles: create,blade

{!! Form::open(array('route' => 'roles.store','method'=>'POST')) !!}
<div class="row">
<div class="col-xs-12 col-sm-12 col-md-12">
    <div class="form-group">
        <strong>Name:</strong>
        {!! Form::text('name', null, array('placeholder' => 'Name','class' => 'form-control')) !!}
    </div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12">
    <div class="form-group">
        <strong>Permission:</strong>
        <br/>
        @foreach($permission as $value)
            <label>{{ Form::checkbox('permission[]', $value->id, false, array('class' => 'name')) }}
            {{ $value->name }}</label>
        <br/>
        @endforeach
    </div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12 text-center">
    <button type="submit" class="btn btn-primary">Submit</button>
</div>
</div>
{!! Form::close() !!}

I have these issues:

  1. How do I add SelectAll/UnselectAll to the Role Permissions checkboxes

  2. The checkboxes for permission under roles are in one column. It will be too clumpsy if they are many. How can I div it to there (3) columns to make it neater.

  3. Is it possible to display the permissions under groups based on the Controller name like Product, Sales ...

Jan
03
2 weeks ago
Activity icon

Replied to How To Perform Complex User Registration

All Employees are also users. The Employee table store a very large detail which I don't want to be in users table. The Users will only contain credentials for Login while the Employee contains all other details.

The goal is that at the initial moment when the when the employee data is created by the Admin, auto-generated password will be generated in the user table but active field will be 0. The username will be emailid/username extracted from the employee email. So an invite will be sent to the employee through the email.

I am using Azure Active directory for the authentication. When he accepts the invite, his Azure credentials will now be used to updated the login credentials and active field will be set to 1

I've been on it for a long time now and confused on what else to do.

Thanks

Activity icon

Replied to How To Perform Complex User Registration

Please just a clarification. In my own case I still want to have another table for employee as shown in the code. How do I re-adjust the code for that? I think that's the only difference now.

Activity icon

Replied to How To Perform Complex User Registration

Yes, it will be multi-company. And each company will have admins. But I cant't see the example you are trying to show me. Also, there is nothing in the spatie link

Activity icon

Started a new Conversation How To Perform Complex User Registration

Initially, I performed user registration using these tables users, roles, permissions, user_roles, role_permissions. This was successfully done using the codes below:

User model

protected $fillable = [
    'name', 
    'email', 
    'email_verified_at',
    'password', 
    'active', 
];

public function __construct(array $attributes = [])
{
    parent::__construct($attributes);
    self::created(function (User $user) {
        $registrationRole = config('panel.registration_default_role');

        if (!$user->roles()->get()->contains($registrationRole)) {
            $user->roles()->attach($registrationRole);
        }
    });
} 


public function roles()
{
    return $this->belongsToMany(Role::class);
}

User Controller

public function rules()
{
    return [
        'name'     => [
            'required',
        ],
        'email'    => [
            'required',
        ],
        'password' => [
            'required',
        ],
        'roles.*'  => [
            'integer',
        ],
        'roles'    => [
            'required',
            'array',
        ],
    ];
}

public function create()
{
    abort_unless(\Gate::allows('user_create'), 403);

    $roles = Role::all()->pluck('title', 'id');

    return view('admin.users.create', compact('roles'));
}

public function store(StoreUserRequest $request)
{
    abort_unless(\Gate::allows('user_create'), 403);

    $user = User::create($request->all());
    $user->roles()->sync($request->input('roles', []));

    return redirect()->route('admin.users.index');
}

This was successfully done.

However, I now have a new table called employees with the model class Employee. This have several foreign key keys.

Employee Model

protected $fillable = [
              'employee_code',
              'user_id',
          'line_manager_id',
              'address',
              'company_id',
              'email',
              'employee_designation_id',
              'employee_job_title_id',
              'employee_status_id',
              'employee_type_id',
              'employement_type_id',
              'employment_date',
              'first_name',
              'image',
              'last_name',
              'other_name',
              'phone',
              'resignation_date',
              'department_id',
              'date_of_birth',
              'title_id',
          ];

protected $casts = [];


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

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

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

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

public function jobtitle()
{
    return $this->belongsTo('App\Models\Hr\HrJobTitle','employee_job_title_id');
}

public function employeestatus()
{
    return $this->belongsTo('App\Models\Hr\HrEmployeeStatus','employee_status_id');
}

public function employeetype()
{
    return $this->belongsTo('App\Models\Hr\HrEmployeeType','employee_type_id');
}

public function employementtype()
{
    return $this->belongsTo('App\Models\Hr\HrEmployementType','employement_type_id');
}

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

public function title()
{
    return $this->belongsTo('App\Models\Config\ConfigTitle','title_id');
}


public function rules()
{
    return [
        'employee_code'             => 'required|min:1|max:20|unique:hr_employees,employee_code,company_id',
        'first_name'                => 'required|min:3|max:50',
        'last_name'                 => 'required|min:3|max:50',
        'other_name'                => 'nullable|max:50',
        'image'                     => 'required|mimes:jpg,tiff,png,svg,gif,bmp,jpeg|max:10240',
        'address'                   => 'nullable|max:255',
        'email'                     => 'required|email|max:100|unique:hr_employees,email,company_id',   // official email
        'phone'                     => 'nullable|max:14|unique:hr_employees,phone',
        'phone2'                    => 'nullable|max:14|unique:hr_employees,phone2',
        'phone3'                    => 'nullable|max:14|unique:hr_employees,phone3',
        'phone4'                    => 'nullable|max:14|unique:hr_employees,phone4',
        'company_id'                => 'required',
        'gender_id'                 => 'required',
        'department_id'             => 'required',
    'title_id'              => 'required',
    'employement_type_id'       => 'required',
        'employee_type_id'          => 'required',
        'employee_designation_id'   => 'required',
    ];
}

In re-writing the user registration:

  1. How do I now write the controller and incorporate the employee model detail into the user registration.

  2. The email in users table should also be saved into the employee table while the company_id in employee table should be saved into user table.

  3. Which should be the main controller: employee or user

I'm somehow confused. Kindly show me examples.

Thank you

Activity icon

Replied to Email Address Field Is Not Saving To The Database

I added that because the fields are not compulsory. I f nothing is there, it will generate an error

Activity icon

Started a new Conversation Email Address Field Is Not Saving To The Database

I have this code:

public function rules()
{
    return [
        'organization_code'     => 'required|string|min:1|max:20|unique:org_companies',
        'organization_name'     => 'required|string|min:3|max:255|unique:org_companies',
        'org_image'             => 'nullable|image|mimes:jpeg,bmp,png,gif|max:2048',
        'email'                 => 'nullable|email|max:50|unique:org_companies',
        'secondary_email'       => 'nullable|email|max:50|unique:org_companies',
        'total_employees'        => 'nullable|numeric|max:200000',
    ];
}


public function store(StoreCompanyRequest $request)
{
    abort_unless(\Gate::allows('company_create'), 403);
    try {           
            $orgStartDate = Carbon::parse($request->org_start_date);  

            $arr = [
                'organization_code'     => $request->organization_code,
                'organization_name'     => $request->organization_name,
            'org_image'             => 'nullable|image|mimes:jpeg,bmp,png,gif|max:2048',
                'total_employees'       => $request->total_employees,
                'email'                 => $request->email,
                'secondary_email'       => $request->secondary_email,
            ];
            
            
             if ($request->org_image != "") {
                 $org_image = $request->file('org_image');
                 $new_name = rand() . '.' . $org_image->getClientOriginalExtension();
                 $org_image->move(public_path('storage/companies/image'), $new_name);
                 $arr['org_image'] = $new_name;
            }
            Session::flash('success', 'Company is created successfully');
            return redirect()->route('organization.companies.index');                
            
    } catch (Exception $exception) {
            Session::flash('danger', 'Action failed!');
            return redirect()->route('organization.companies.index');  
    }
}

view:

    <form action="{{ route("organization.companies.store") }}" method="post" class="form-horizontal" enctype="multipart/form-data">

        {{csrf_field()}}

            <div class="text-center">
              <input type="image" class="profile-user-img img-fluid img-circle"
                   src="{{asset('theme/adminlte3/dist/img/company_logo.png')}}"

                    id="wizardPicturePreview" title="" width="150">                   

              <input type="file"  name="org_image" id="wizard-picture" class="" hidden>
              <h4 class="profile-username text-center">Click On Image to Add Logo</h4>
            </div>
                <hr class="m-t-0 m-b-40">  
                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group row">
                                    <label class="control-label text-right col-md-3"> Company Code<span style="color:red;">*</span></label>
                                    <div class="col-md-9 controls">
                                        <input  type="text" name="organization_code" placeholder="Enter company code here" class="form-control" value="{{old('organization_code')}}">
                                    </div>
                                </div>
                            </div>
                            <!--/span-->
                            <div class="col-md-6">
                                <div class="form-group row">
                                    <label class="control-label text-right col-md-3"> Company Name<span style="color:red;">*</span></label>
                                    <div class="col-md-9 controls">
                                        <input  type="text" name="organization_name" placeholder="Enter company code here" class="form-control" value="{{old('organization_name')}}">
                                    </div>
                                </div>
                            </div>
                            <!--/span-->
                        </div>
                        <!--/row-->
                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group row">
                                    <label class="control-label text-right col-md-3"> Total Employees</label>
                                    <div class="col-md-9 controls">
                                        <input  type="number" name="total_employees" placeholder="Enter total employees here" class="form-control" value="{{old('total_employees')}}">
                                    </div>
                                </div>
                            </div>
                            <!--/span-->
                        </div> 
                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group row">
                                    <label class="control-label text-right col-md-3"> Email</label>
                                    <div class="col-md-9 controls">
                                        <input  type="email" name="email" placeholder="Enter Email: [email protected]" class="form-control" value="{{old('email')}}">
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group row">
                                    <label class="control-label text-right col-md-3"> Alternative Email</label>
                                    <div class="col-md-9 controls">
                                        <input  type="email" name="secondary_email" placeholder="Enter Alternative Email: [email protected]" class="form-control" value="{{old('secondary_email')}}">
                                    </div>
                                </div>
                            </div>
                            <!--/span-->
                        </div>
                    <div class="form-actions">
                        <div class="row">
                            <div class="col-md-6">
                                <div class="row">
                                    <div class="col-md-offset-3 col-md-9">
                                        <button type="submit" class="btn btn-primary">Add Company</button>
                                        <button type="button" onclick="window.location.href='{{route('organization.companies.index')}}'" class="btn btn-default">Cancel</button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
    </form>

When I click on save, I observed that every other field was saved into the database apart from

email and secondary_email

I did the var_dump() and observe that they are null.

How do I resolve this?

Activity icon

Started a new Conversation How To Extract Emailid From Email Before Saving It

I am using Laravel-5.8 for my project. When creating new employee, I want the user to only enter the email address. Then, the application will extract the emailid from the email and save it as username.

Already I have this code:

    $employee = Employee::create([
        'fname' => $request->fname,
        'lname' => $request->lname,
        'email' => $request->email,
        'usename' => 
    ]);

So, from the code above how do I get emailid from email entered and save it as username. For example, if email is david2000@gmail.com, the username should be david2000.

How do I adjust my code to achive this.

Jan
02
2 weeks ago
Activity icon

Started a new Conversation Laravel Select Option List On Change To Route Pages

I am working on a project using Laravel-5.8. In my header.blade, I have this dropdownlist:

<form class="form-inline ml-3">
    <div class="input-group input-group-sm">
                  <div class="form-group">
                    <select class="form-control" data-placeholder="Select a State">
                      <option>Dashboard</option>
                      <option>Assets</option>
                      <option>HR</option>
                    </select>
                  </div>
    </div>
</form>

I want the dropdownlist on change to route different pages

If Dashboard then display {{ route('hr-default') }}

If Assets then display {{ route('asset-default') }}

If HR then display {{ route('hr-default') }}

How do I achieve this?

Dec
31
2 weeks ago
Activity icon

Replied to No Record Saved In Multiple Records Insertion With Dynamically Created Input Fields

When I changed the controller to this:

        $rating = new AppraisalRating([
                'rating_point'              => $request->input('rating_point'),
                'rating_type'               => $request->input('rating_type'),
                'rating_value'              => $request->input('rating_value'),
                'rating_description'        => $request->input('rating_description'),
                'company_id'                =>       Auth::user()->company_id,
                'created_by'                =>       Auth::user()->id,
                'created_at'                =>       date("Y-m-d H:i:s"),
                'is_active'                 =>       1,
        ]);

        $rating->save();

It saves only one row

Activity icon

Replied to Laravel 5.4 Dynamic Form Save Data To Database

Can you show me the complete code for this discussion? I'm having similar issue

Activity icon

Replied to No Record Saved In Multiple Records Insertion With Dynamically Created Input Fields

Who can really assist. I'm getting frustrated

Activity icon

Replied to No Record Saved In Multiple Records Insertion With Dynamically Created Input Fields

Where do I put dd($request->all()) and dd(count($input['rating type'])) from my code

Activity icon

Started a new Conversation No Record Saved In Multiple Records Insertion With Dynamically Created Input Fields

I want to save the multiple data to database. With the aid of Select option dropdownlist, User can dynamically add input fields and finally click submit button to save data in database. The value in the select option will determine the number of field rows to be generated.

public $rating_points = [
"1" => "Three-Star-Rating",
"2" => "Four-Star-Rating",
"3" => "Five-Star-Rating",
"4" => "Six-Star-Rating",
"5" => "Seven-Star-Rating",
];

public function create()
{
  return view('appraisal.ratings.create')->with('rating_points', $this->rating_points);
}

public function store(StoreRatingRequest $request)
{

        for($idx=0; $idx<= count($input['rating_type']); $idx++)
        {
            $rating = new AppraisalRating;
            $rating->rating_point           =       $ratingpoints;
            $rating->rating_type            =       $ratingtypes[$idx];
            $rating->rating_value           =       $ratingvalues[$idx];
            $rating->rating_description     =       $ratingdescriptions[$idx];
            $rating->company_id             =       Auth::user()->company_id;
            $rating->created_by             =       Auth::user()->id;
            $rating->created_at             =       date("Y-m-d H:i:s");
            $rating->is_active_id           =       1;
            $rating->save();
        }

    Session::flash('success', 'Appraisal Rating is created successfully');
    return redirect()->route('appraisal.ratings.index');
}

view

<div class="card-body">
   <form  action="{{route('appraisal.ratings.store')}}" method="post" class="form-horizontal" enctype="multipart/form-data">
       {{csrf_field()}}
                    <div class="form-body">
                        <div class="row">
                            <div class="col-md-12">
                                <div class="form-group row">
                                    <label for="rating-point" class="col-4 col-form-label"> Rating Point<span style="color:red;">*</span></label>
                                    <div class="col-md-6 controls">
                                        <select id='rating-point' class="form-control select2" data-placeholder="Choose Rating Value" tabindex="1" name="rating_point">
                                            <option value="">Select Rating Point</option>
                                            @foreach($rating_points as $k => $rating_point)
                                                <option value="{{$k}}" @if(old("rating_point") == "$k") selected @endif>{{$rating_point}}</option>
                                            @endforeach
                                        </select>
                                    </div>
                                </div>
                            </div>  
                        </div>

                    <div class="row" id="rating-data"></div>
                </div>
      
        <div id="rating-button" style="display: none;">
            &nbsp;&nbsp;&nbsp;<button type="submit" class="btn btn-primary">{{ trans('global.save') }}</button>
            <button type="button" onclick="window.location.href='{{route('appraisal.ratings.index')}}'" class="btn btn-default">Cancel</button>
        </div>
    </form>
</div> 
@endsection

@section('javascript')
<!-- jQuery -->
<script src="{{ asset('theme/adminlte3/plugins/jquery/jquery.min.js') }}"></script>
<!-- jQuery UI 1.11.4 -->
<script src="{{ asset('theme/adminlte3/plugins/jquery-ui/jquery-ui.min.js') }}"></script>


<script>
$(document).ready(function($){
$('#rating-point').on('change', function() {
 $('#rating-data').html('');

  if ( this.value == '1')
  {
    var numInputs = '3';
     for(var i=0; i < numInputs; i++)
     {
         var j = i*1+1;
         var $section =  $('<div class="col-md-4"><div class="form-group row"><label class="control-label text-right col-md-3">Type<span style="color:red;">*</span></label><div class="col-md-9 controls"><input  type="text" name="rating_type" value="'+j+'" class="form-control" value="{{old('rating_type')}}" readonly></div></div></div><div class="col-md-4"><div class="form-group row"><label class="control-label text-right col-md-3">Value<span style="color:red;">*</span></label><div class="col-md-9 controls"><input  type="number" name="rating_value" placeholder="Rating Value" class="form-control" value="{{old('rating_value')}}"></div></div></div><div class="col-md-4"><div class="form-group row"><label class="control-label text-right col-md-3">Description<span style="color:red;">*</span></label><div class="col-md-9 controls"><input  type="text" name="rating_description" placeholder="Enter rating description here" class="form-control" value="{{old('rating_description')}}"></div></div></div>');
         $('#rating-data').append($section);
     }           
    $("#rating-button").show();
  }
  else if ( this.value == '2')
  {
    var numInputs = '4';
     for(var i=0; i < numInputs; i++)
     {
         var j = i*1+1;
         var $section =  $('<div class="col-md-4"><div class="form-group row"><label class="control-label text-right col-md-3">Type<span style="color:red;">*</span></label><div class="col-md-9 controls"><input  type="text" name="rating_type" value="'+j+'" class="form-control" value="{{old('rating_type')}}" readonly></div></div></div><div class="col-md-4"><div class="form-group row"><label class="control-label text-right col-md-3">Value<span style="color:red;">*</span></label><div class="col-md-9 controls"><input  type="number" name="rating_value" placeholder="Rating Value" class="form-control" value="{{old('rating_value')}}"></div></div></div><div class="col-md-4"><div class="form-group row"><label class="control-label text-right col-md-3">Description<span style="color:red;">*</span></label><div class="col-md-9 controls"><input  type="text" name="rating_description" placeholder="Enter rating description here" class="form-control" value="{{old('rating_description')}}"></div></div></div>');
         $('#rating-data').append($section);
     } 
    $("#rating-button").show();
  }
  else
  {
    $("#rating-button").hide();
  }
 });
});
</script>
 @stop

When I clicked on submit button, I expected the data to be saved into the database and the page redirect to index.blade. The page only redirect to index page and no record is saved.

How do I resolve this.

Thank you.

Activity icon

Awarded Best Reply on Error:Undefined Variable: Rating_points In Laravel

Thanks. I observe that it was still referencing the old controller I used. I delete it and run composer update. Problem solved.

Activity icon

Replied to Error:Undefined Variable: Rating_points In Laravel

Thanks. I observe that it was still referencing the old controller I used. I delete it and run composer update. Problem solved.