lundi 30 novembre 2020

Laravel how to sort collection by specific value and id

How to sort collections by specific value and id. I need to sort records where the name = X should be the first in the order.

product model

|---------------------|------------------|
|          id         |        Name      |
|---------------------|------------------|
|          1          |         a        |
|---------------------|------------------|
|          2          |         x        |
|---------------------|------------------|
|          3          |         b        |
|---------------------|------------------|
|          4          |         c        |
|---------------------|------------------|
|          5          |         x        |
|---------------------|------------------|

I tried this code but not working.

Product::orderBy('id', 'asc')->get()


via Chebli Mohamed

How to install Laravel Package on Webserver

i've finished my web application with laravel and i've running it now on production mode on my webserver. The point is that i need some new laravel packages to improve my Laravel application. How can i install packages to my live server?

Thanks very much!



via Chebli Mohamed

Laravel Eloquent - method to obtain grandchildren's data from GrandParents

I'm making Ecommerce-website and I have the following relationship:

Grandparents : Category ( id , name )
Parents : Brand ( id , name , category_id )
Children : Product ( id , name , brand_id )

Example : Smartphone (Category) -> iPhone (Brand) -> iPhone 12, iPhone 12 Pro, iPhone 12 Pro Max (Product)
I want to get all the iPhone 12 as above from Category likes

$iPhone = App\Category::find(1)->brands->where('name','iPhone')->toArray()

Thanks for helping



via Chebli Mohamed

laravel mews captcha_img() does not return on refresh

I have wracked my brain and the internet seeing if anyone else has had this issue, but no luck. So I turn to you all.

I'm using Mews/Captcha package with a Laravel 5.5. application.

I'm implementing a contact form where the user fills it out, enters in Captcha data, and submits it. All of that works. If you go to the form, the captcha image appears. If you refresh the page, a new captcha image appears. If you try to submit the form without the captcha or an incorrect captcha, it fails. If you submit with the correct captcha it succeeds.

The issue I am having is with the refresh button in case the user wants to change the image. For the life of me, I can't get it to return the image, even though I've seen numerous examples that claim to work that are using similar code. What happens is that the current captcha image is replaced by blank space.

Here's the code for the button:

<script>
    $(document).ready(function(){
        $('#reload').on('click', function(){
            $.ajax({
                type: 'GET',
                url: '/reload-captcha',
                success: function(data) {
                    $("#captchadiv").html(data.captcha);
                }
            });
        });
    });
</script>

Here's the code further down the page where the captcha image and buttons are:

        <tr>
            <td><button type="button" class="button reload" id="reload">Refresh</button></td>
            <td><div id="captchadiv">{!! captcha_img('flat') !!}</div></td>
        </tr>
        <tr>
            <td><label for="captcha">Captcha</label></td>
            <td><input type="text" id="captcha" class="form-control" placeholder="Enter Captcha" name="captcha">
                @if ($errors->has('captcha'))
                    <span class="textRed">
                        <strong></strong>
                    </span>
                @endif</td>
        </tr>

Here's the code for the response:

    public function reloadCaptcha()
    {
        return response()->json(['captcha'=> captcha_img('flat')]);
    }

Now, if I replace captcha_img('flat') with some text and click the button, it behaves as expected and replaces the previous image with the text.

So either one of two things is going on:

  1. the captcha_img() function is failing during the response step. So nothing returns.
  2. the javascript in the form is failing to extract the image from the returned json object.

Note that in my experiments, I put in an alert which showed the data and the status, and the data displayed an "object" and the status was "success".

I'm at my wit's end. If you want to see it in action, you can visit the page here: https://creativehaven.net/contact



via Chebli Mohamed

dimanche 29 novembre 2020

Laravel Horizon not working on live server

I am using laravel horizon on live server. It was working 2 days ago. Now suddenly it stops working and giving 403 forbidden. I tried much to solved it but nothing is working. Same thing was happening with telescope but when I get telescope out of authentication it starts working but horizon is still not working?

What could be the reason?



via Chebli Mohamed

Laravel WhereIn method in Eloquent not working

I want to use the WhereIn method in Eloquent but it now works like the below function.

<?php 
  $product = DB::table('product')
                   ->join('supplier','supp_code','=','prod_supplier_code')
                   ->select('product.*','supplier.supp_margin')
                   ->where('prod_seo_title','=',$id)
                   ->first();

  $decArr = explode(',',$product->prod_decoration_type);

        for($i=0; $i<count($decArr); $i++)
        {
            if($i==0)
            $inString = "'".$decArr[$i]."','";
            elseif ($i<(count($decArr))-1)
            $inString .= $decArr[$i]."','";
            else
            $inString .= $decArr[$i]."'";
        }

        $proDeco = DB::table('decoration')->whereIn('deco_print_type', [$inString])->get();
?>

But In the query, it's displaying like this.

select * from `decoration` where `deco_print_type` in ('\'100109C9\',\'100110B9\',\'100144C9\',\'100186C9\'');

I can't understand why these slashes are coming. Please help me to fix this issue.



via Chebli Mohamed

Catch all exceptions and send them by e-mail - Laravel 7

I'm in

My dd() seems working, and I got

Illuminate\Database\QueryException {#521 ▼
  #sql: "select `color_code`, `name` from `skills` order by `created_at` desc"
  #bindings: []
  #message: "SQLSTATE[HY000] [2002] Connection refused (SQL: select `color_code`, `name` from `skills` order by `created_at` desc)"
  #code: 2002
  #file: "/Users/bheng/Sites/bheng2020/vendor/laravel/framework/src/Illuminate/Database/Connection.php"
  #line: 671
  -previous: Doctrine\DBAL\Driver\PDO\Exception {#526 ▶}
  +errorInfo: null
  trace: {▶}
}

I'm trying to mail this message to myself

SQLSTATE[HY000] [2002] Connection refused (SQL: select color_code, name from skills order by created_at desc)

Then, I tried to do this

public function report(Throwable $exception)
{

    // dd($exception);

    if(isset($exception)){
        $message = $exception->message;
        $mail = Mail::send('layouts.share.emails.log', array('message' => $message) , function ($message) use ($message) {
            $message->from(env('MAIL_FROM') , 'Server 27');

            if(env('APP_ENV') == 'local'){
                $message->to($email , 'Server 27')->subject('ERROR - 🟢');
            } else {
                $message->to($email , 'Server 27')->subject('ERROR');
            }
        });
    }

    parent::report($exception);
}

I was hoping to email all exceptions to my email but see nothing.

Kept getting this :

enter image description here



via Chebli Mohamed

Async/Await in Vue/Laravel

Im doing a CRUD for my Vue-Laravel aplication Im getting to the "/create" route and im creating a new "despesa" in my browser but when i press F5 doesnt save in my backend only in my frontend, how can i do that?

FRONTEND:

async addDespesa() {
  let uri = "api/despesas/create";
  const response = await axios.get(uri, this.despesa).then((response) => {
      this.despesas.push({
        des: this.despesa.des,
        valr: this.despesa.valr,
        stt: this.despesa.stt,
        vencc: this.despesa.vencc,
        emiss:this.despesa.emiss,
      });
       this.despesa.des = '';
      this.despesa.valr = '';
      this.despesa.vencc = '';
      this.despesa.stt = '';
      this.despesa.emiss = '';
      })

},

BACKEND:

public function create() {
//
}


via Chebli Mohamed

Trigger action(s) before Exception print to the log file - Laravel

I monitor my local Laravel logs by doing this :

tail -f storage/logs/laravel.log | grep .ERROR:

enter image description here

[2020-11-29 08:46:01] local.ERROR: SQLSTATE[HY000] [2002] Connection refused (SQL: select `color_code`, `name` from `skills` order by `created_at` desc) {"exception":"[object] (Illuminate\\Database\\QueryException(code: 2002): SQLSTATE[HY000] [2002] Connection refused (SQL: select `color_code`, `name` from `skills` order by `created_at` desc) at /Users/hunter/Sites/app/vendor/laravel/framework/src/Illuminate/Database/Connection.php:671) 

Rather than keep monitoring it, I would like to add an action (do something) right before it printed into the Log file.

Ex.

  • Send me an email
  • Store into logs table
  • do something before log printed in log file

I've tried

/Users/hunter/Sites/app/app/Exceptions/Handler.php



public function report(Throwable $exception)
{

    Log::debug('>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>RUNNING ');
    parent::report($exception);
}

Result: I don't see my log printed.

How would one go above and do this ?



via Chebli Mohamed

How to paginate the API response of another API?

The context: Laravel 5.7, ApiClient for external client available via ServiceProvider & Facade. I get the response with the list of dictionaries in the controller. Is there a way to paginate the API response of another API in the view to get another portion?

For example, in this code:

public function report(Request $request) {
        $date_from = $request->date_from;
        $date_to = $request->date_to;

        $func = function($date) {
            return date("Y-m-d", strtotime($date));
        };


        if(!empty($date_from) && !empty($date_to)) {
            $date_from_slice = explode(' - ', $date_from);
            $date_from_slice = array_map($func, $date_from_slice);

            $stats = [];
            $data = [
                'from'       => $date_from_slice[0],
                'to'         => $date_from_slice[1],
                'page'       => 1,
                'rowsOnPage' => 20,
                'groupBy[4]' => 'sspId',
            ];

            $reportDataFirst = ApiClient::exec('statistics', $data);
            $first_collection = collect($reportDataFirst->data);

            if(!empty($first_collection)){
                foreach($first_collection as $first_item) {
                        $stats[] = [
                            'ssp_id'                 => $first_item->sspId,
                            'ssp_name'               => $first_item->sspName,
                            'impressions_first'      => $first_item->impressions,
                            'ssp_spend_first'        => $first_item->sspSpend,
                            'dsp_spend_first'        => $first_item->dspSpend,
                         ];
                 }
             }
            $data = ['stats' => $stats];
            return view('client.index', $data);
}

I have fixed 'page' and 'rowsOnPage' parameters:

            'page'       => 1,
            'rowsOnPage' => 20,

I need something to create the pagination interface for it. Is there a way to build it in Laravel?



via Chebli Mohamed

Get Data through relation in laravel

I'm using this query to get data using relation

 return Product::with('attributes')
        ->whereHas('attributes', function ($query) use ($attribute_id,$attribute_value){
            $query->whereIn('attribute_id', $attribute_id);
            $query->whereIn('value', $attribute_value);
        })
        ->paginate(10);

$attribute_id and $attribute_value are arrays, i'm getting data using this relation but when $attribute_id and $attribute_value are empty then i'm not getting any result but it should return result through product table if there are no attributes.

I have changed it to something like this:

 if(!empty($attribute_id))
                {
                    $query->whereIn('attribute_id', $attribute_id);
                }
                if(!empty($attribute_value))
                {
                    $query->whereIn('value', $attribute_value);
                }

model relation :

 public function attributes()
    {
        return $this->hasMany(ProductsAttribute::class, 'product_id ');
    }

Table:

id | Title     | Price

1    Title 1     5000
2    Product 2   7000

this is related to product_attribute table

id | product_id | attribute_id | attribute_name | value
 1     1              5             Color         Red
 2     1              6             Size           XL
 3     2              5             Color         Green

Is there any other way to make a check in query so that if attributes are not provided then atleast product data should return.



via Chebli Mohamed

samedi 28 novembre 2020

How to search records sorted by of least difference in laravel

I have two tables customers and providers . Both table has longitude, latitude and location column . Customer will search in providers table and will get data in order by distance.

Provider which is most closed to the provider will come first.

Models names are

Provider
Customer

Provider Migration

 public function up()
    {
        Schema::create('providers', function (Blueprint $table) {
            $table->id();
            $table->string('owner_name');
            $table->string('owner_email')->unique();
           
            $table->string('password');
            $table->string('rfc');
            $table->string('tax');
            $table->string('location');
            $table->string('longitude')->nullable();
            $table->string('latitude')->nullable();
         
            $table->boolean('status')->default(1);
            $table->timestamps();
        });
    }

Customer Migration

 Schema::create('customers', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('email');
            $table->string('phone');
            $table->string('password');
          
            $table->string('location');
            $table->string('longitude')->nullable();
            $table->string('latitude')->nullable();
            $table->boolean('status')->default(1);
            $table->timestamps();
        });

How i can write query for this situation



via Chebli Mohamed

vendredi 27 novembre 2020

Laravel: is it possible to make add another account feature to Auth system like Google account

I want to know how would it be possible to save previously logged users in Laravel Auth system.

Once a user logs in, it should be possible to switch to another account without having to sign out from current account. So it will be possible to switch between accounts without having to enter login-password each time.

Like Google account, there we can add multiple Gmail accounts and when we want switch account then we chose one of them then it is happens.



via Chebli Mohamed

Upgrade Laravel 5.3 to Laravel 8 [closed]

What is the easiest and fastest way to upgrade code from Laravel 5.3 to Laravel 7.3 or 8 ? Is there a tool which can do that for me ? How long does it take to do that?

Please help .

Regards



via Chebli Mohamed

How to get data from third table in eloquent relationships eloquent many to many relationship

I am using Eloquent ORM and I have Book model which connect to BookCategory model and BookCategory connect to Category. The l'm problem facing is how to include data from third table in eloquent relationships?

Book
    id
    name
    
Category 
    id
    name
    type
    
BookCategory 
    id
    book_id
    category_id


via Chebli Mohamed

how to keep alive parent job in laravel?

I am using laravel jobs i have chained all the jobs like this

 CalculateSingleInvoice::withChain([
            (new CalculateInvoiceGrandTotal($invoice,$this->user_id,true))->onQueue('invoice'),
        ])->dispatch($invoice,$this->user_id = 1,true)->onQueue('invoice');

These jobs are working fine

Now there is another job inside CalculateSingleInvoice

which is

 CalculateSingleConsignment::dispatch($consignment, $total_consignments, $i)->onQueue('invoice');

Now the problem is i want to keep alive parent CalculateSingleInvoice job and it works when i use dispatchNow() but the problem is there are almost 1000 child jobs so parent jobs gets timeout . I know i can set time out but i dont want to use timeout because it can vary from job to job.

What could be best approach?



via Chebli Mohamed

jeudi 26 novembre 2020

How to send some data and image from AJAX to Controller in Laravel?

I'm a freshmen in the office and I was assigned by my boss to fix the code of the website that the developer is not in the company anymore. He used mostly AJAX to do things which I'm not used to it. I rarely use AJAX in my project, so I'm very very new about this.

From the old code, I'm trying to send an image with some data from an input form. I can console.log(form_data) to see its values, but I don't know why the content of image cannot be sent to Controller. It's getting 'null' and I can't store it.

Here is the code in input form

<div class="modal-dialog">
<div class="modal-content">
    <div class="modal-header">
      <h4 class="modal-title"></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 id="input-form" class="needs-validation" novalidate method="POST" enctype="multipart/form-data" name="input-form">
        
        <div class="form-horizontal">
          <div class="form-group required">
            <label class="col-sm-12 control-label" for="thai_name"></label>
            <div class="col-sm-12">
              <input type="text" class="form-control" id="thai_name" name="thai_name" value="" required/>
            </div>
          </div>
          <div class="form-group required">
            <label class="col-sm-12 control-label" for="eng_name"></label>
            <div class="col-sm-12">
              <input type="text" class="form-control" id="eng_name" name="eng_name" value="" required/>
            </div>
          </div>
          <div class="form-group required">
            <label class="col-sm-12 control-label" for="email"></label>
            <div class="col-sm-12">
              <input type="text" class="form-control" id="email" name="email" value="" required/>
            </div>
          </div>
          <div class="form-group required">
            <label class="col-sm-12 control-label" for="password"></label>
            <div class="col-sm-12">
              <input type="password" id="password" class="form-control" required/>
            </div>
          </div>
          <div class="form-group required">
            <label class="col-sm-12 control-label" for="password_confirmation"></label>
            <div class="col-sm-12">
              <input type="password" id="password_confirmation" class="form-control" required/>
            </div>
          </div>
          <div class="form-group col-sm-12">
            <a class="btn-link" id="message" style="text-align: center;"></a>
          </div>
          <div class="form-group required">
            <label class="col-sm-12 control-label" for="phone"></label>
            <div class="col-sm-12">
              <input type="text" class="form-control" id="phone" name="phone" value="" required/>
            </div>
          </div>
          <div class="form-group">
            <label class="col-sm-12 control-label" for="fax"></label>
            <div class="col-sm-12">
              <input type="text" class="form-control" id="fax" name="fax" value=""/>
            </div>
          </div>
          <div class="form-group required">
            <label class="col-sm-12 control-label"></label>
            <div class="col-sm-12">
              <div class="form-check form-check-inline">
                <input class="form-check-input role" type="radio" id="admin" name="role" value="1"
                 required>
                <label class="form-check-label" for="admin">ผู้ดูแลระบบ</label>
              </div>
              <div class="form-check form-check-inline">
                <input class="form-check-input role" type="radio" id="content_admin" name="role" value="2"
                 required>
                <label class="form-check-label" for="content_admin">ผู้ดูแลข้อมูล</label>
              </div>
              <div class="form-check form-check-inline">
                <input class="form-check-input role" type="radio" id="user" name="role" value="3"
                 required>
                <label class="form-check-label" for="user">ผู้ใช้งาน</label>
              </div>
            </div>
          </div>
          <div class="form-group required">
            <label class="col-sm-12 control-label"></label>
            <div class="col-sm-12">
              <select id="faction" class="form-control">
                @foreach($factions as $faction)
                  <option value="" >
                    
                  </option>>
                @endforeach
              </select>
            </div>
          </div>
          <div class="form-group required">
            <label class="col-sm-12 control-label"></label>
            <div class="col-sm-12">
              <select id="position" class="form-control">
                @foreach($positions as $position)
                  <option value="" >
                    
                  </option>>
                @endforeach
              </select>
            </div>
          </div>
          <div class="form-group required">
            <div class="col-sm-12">
              <label class="control-label" for="photo">รูปถ่าย</label>
              <input type="file" class="form-control-file" id="photo" name="photo" accept="image/*" required/>
            </div>
          </div>
          <div class="form-group">
            <label class="col-sm-12 control-label"> / </label>
            <div class="col-sm-12">
              <div class="form-check form-check-inline">
                <input class="form-check-input" type="checkbox" id="acting" name="acting" >
                <label class="form-check-label" for="acting"></label>
              </div>
              <div class="form-check form-check-inline">
                <input class="form-check-input" type="checkbox" id="past" name="past" >
                <label class="form-check-label" for="past"></label>
              </div>
            </div>
          </div>
          <div class="form-group">
            <label class="col-sm-12" for="start"></label>
            <div class="col-sm-12">
              <div class="input-group" id="start" name="start">
                <input type="text" class="form-control" readonly="readonly"/>
                <div class="input-group-append">
                  <span class="input-group-text input-group-addon">
                    <span class="fa fa-calendar"></span>
                  </span>
                </div>
              </div>
            </div>
          </div>
          <div class="form-group">
            <label class="col-sm-12" for="end"></label>
            <div class="col-sm-12">
              <div class="input-group" id="end" name="end">
                <input type="text" class="form-control" readonly="readonly"/>
                <div class="input-group-append">
                  <span class="input-group-text input-group-addon">
                    <span class="fa fa-calendar"></span>
                  </span>
                </div>
              </div>
            </div>
          </div>
          <div class="form-group">
            <div class="row col-sm-12 text-center">
              <input type="button" class="btn btn-default" value=""
                     onclick=""
                     />
            </div>
          </div>
        </div>
      </form>
    </div>
  </div>
</div>
<script type="text/javascript">
$(function () {
  $('#start').datetimepicker({
    sideBySide: true,
    locale: 'th',
    format: 'YYYY-MM-DD',
    ignoreReadonly: true,
    defaultDate: ""
  });
  $('#end').datetimepicker({
    sideBySide: true,
    locale: 'th',
    format: 'YYYY-MM-DD',
    ignoreReadonly: true,
    defaultDate: ""
  });
  $('#password, #password_confirmation').on('keyup', function () {
      if ( $('#password').val() == $('#password_confirmation').val() ) {
        if ( $('#password').val() != '') {
          $('#message').html('').css('color', 'green');
        } else {
          $('#message').html('').css('color', 'red');
          $('#password').removeClass('valid').addClass('invalid');
          $('#password_confirmation').removeClass('valid').addClass('invalid');
        }
      } else {
        $('#message').html('').css('color', 'red');
        $('#password').removeClass('valid').addClass('invalid');
        $('#password_confirmation').removeClass('valid').addClass('invalid');
      }
    });
});
</script>

Here is the code in user.js where I'm using AJAX to send form_data contains image and some data

function addUser() {
 var validate = validateUser("add");
  if (validate.error == '') {
    $('#modal1').modal({backdrop: "static"});
    var form_data = {
      thai_name: validate.thai_name,
        eng_name: validate.eng_name,
      email: validate.email,
      password: validate.password,
      password_confirmation: validate.password_confirmation,
      telephone: $('#phone').val(),
      fax: $('#fax').val(),
      system_role_id: $('input[name=role]:checked').val(),
      faction_id: $('#faction').val(),
      position_id: $('#position').val(),
      photo: $('#photo').val(),
      photo_file: $('#photo').prop("files")[0],
      is_acting: 0,
      is_past: 0,
      start: $('#start').data('date'),
      end: $('#end').data('date'),
    };

    if ($('#acting').is(':checked')) {
      form_data.is_acting = 1;
    }
    if ($('#past').is(':checked')) {
      form_data.is_past = 1;
    }

    console.log(form_data);

    $.ajax({
        type: "post",
      enctype: "multipart/form-data",
      url: baseurl + "/admin/user/add",
      data: form_data,
      processData: false,
      contentType: false,
      headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        },
        success: function () {
            $('#input-area').modal('hide');
            listUser();
        }
    });
  }
}

Here is some code in my controller

public function addUser(Request $request) {
  $user = new User();
  $user->thai_name = request()->thai_name;
  $user->eng_name = request()->eng_name;
  $user->email = request()->email;
  $user->password = Hash::make(request()->password);
  $user->telephone = request()->telephone;
  $user->fax = request()->fax;
  $user->system_role_id = request()->system_role_id;
  $user->faction_id = request()->faction_id;
  $user->position_id = request()->position_id;

  // Store Profile Photo
  $filename = "profile-photo-" . time() . "-name-" . basename(request()->photo);
  request()->file('photo_file')->storeAs('', $filename, 'images');
  $user->photo = $filename;

  $user->is_acting = request()->is_acting;
  $user->is_past = request()->is_past;
  $user->start = request()->start;
  $user->end = request()->end;
  $user->save();
}

Which part I did wrong? Any ideas? Please help me figure this out. Thank you in advanced.



via Chebli Mohamed

Invalidating Session not logging out - Laravel 5

So basically a user can stay logged in accross iPhone, Chrome, Firefox and multiple browsers and I want to stop that, and only allow the user to be logged in at (1 session only at a time).

Meaning: When the user logs in somehwere else... it logs them out on the other.

I have added the following to the very bottom of my LoginController.php

/**
 * The user has been authenticated.
 *
 * 
 * @return mixed
 */
 
 
protected function authenticated()
{
    \Auth::logoutOtherDevices(request($password));
}

I also uncommented the line: \Illuminate\Session\Middleware\AuthenticateSession::class, in my Kernel.php

But it still allows the user to stay logged in across many browsers.

I would like it to invalidate the session correctly and log the user OUT everywhere else wherever it is logged in.

Here is my complete LoginController.php just incase I have made some mistake:

   <?php

            namespace App\Http\Controllers\Auth;

            use App\Http\Controllers\Controller;
            use Illuminate\Foundation\Auth\AuthenticatesUsers;


            class LoginController extends Controller
            {
                /*
                |--------------------------------------------------------------------------
                | Login Controller
                |--------------------------------------------------------------------------
                |
                | This controller handles authenticating users for the application and
                | redirecting them to your home screen. The controller uses a trait
                | to conveniently provide its functionality to your applications.
                |
                */

                use AuthenticatesUsers;

                /**
                 * Where to redirect users after login.
                 *
                 * @var string
                 */
                protected $redirectTo = '/dashboard';

                /**
                 * Create a new controller instance.
                 *
                 * @return void
                 */
                public function __construct()
                {

                    $this->middleware('guest')->except('logout');

                    $this->middleware('guest:admin', ['except' => 'logout']);

                }

                public function username()
                {
                    return 'username';
                }


                public function logoutUser()
                {

                    $this->guard()->logout();

                    $this->session()->invalidate();

                    return redirect('/login');
                }
                
            }



            /**
                 * The user has been authenticated.
                 *
                 * 
                 * @return mixed
                 */
                 
                 
                protected function authenticated()
                {
                    \Auth::logoutOtherDevices(request($password));
                }


via Chebli Mohamed

Filter data based on relation laravel

I have product table like:

id | Title     | Price

1    Title 1     5000
2    Product 2   7000

this is related to product_attribute table

id | product_id | attribute_id | attribute_name | value
 1     1              5             Color         Red
 2     1              6             Size           XL
 3     2              5             Color         Green

in product model there is following relation:

 public function attributes()
    {
        return $this->hasMany(ProductsAttribute::class, 'product_id ');
    }

In controller method :

public function search(Request $request)
    {  
     $attributes=$request->attributes;
     foreach($attributes as $attr)
          {
            $attribute_id=$attr['attribute_id'];
            $attribute_value=$attr['value'];
          }

     return product::with('attributes')
            ->whereHas('attributes', function ($query) use ($attribute_id,$attribute_value)  {
                $query->where('attribute_id', $attribute_id);
                $query->where('value', $attribute_value);
            })->paginate(10);
    }

Issue is in my foreach loop i'm getting multiple attribute_id and attribute_value but in the query i can pass only single value of attribute_id and value. I want to fetch all the products where attribute id and attribute value matches. Any help is highly appreciated.



via Chebli Mohamed

Dynamic dependent search drop down list and update my data in laravel

Dynamic dependent search drop down list and update my data in laravel Suggest any code you have done before.



via Chebli Mohamed

Using try catch in laravel [closed]

I have to send mail and messages on mobiles so i want if mail or mobile messages gateway throws any error then rest of the code should not stop working. So i have used below try and catch block. Should i place both mobile otp and email in one single try catch block or there will be different try catch for both.

try{
       $mobile = \App\Helpers\Helper::sendMessage($request->mobile,'message');
    }
    catch (\Exception $e) { 
       
    }

    try{
        Mail::to($request->email)->send(new Mail($data));
    }
    catch (\Exception $e) { 
       
    }


via Chebli Mohamed

mercredi 25 novembre 2020

laravel 5.6 search keep send me 404 not found page

hi im sorry if I do this wrong but my search function always send me to 404 not found despite having the necessary routes...

here the code:

Web.php

Route::get('/pegawai')->name('pegawai.index')->uses('pegawaicontroller@index');
Route::get('/pegawai/search')->uses('pegawaicontroller@search');

pegawaicontroller.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Pegawai;


class pegawaicontroller extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $pegawais = Pegawai::orderBy('id', 'ASC')->paginate(5);
        return view('pegawai.index', compact('pegawais')); 
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('pegawai.create');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $this->validate($request, [
            'kategori' => 'required',
            'jabatan' => 'required',
            'nama_pegawai' => 'required',
            'alamat' => 'required',
            'gambar_pegawai' => 'required'
            ]);
            
            // upload file
            $filename = time() . '.png';
            $request->file('gambar_pegawai')->storeAs('public/images', $filename);

            $pegawai = new Pegawai;
            $pegawai->kategori = $request->input('kategori');
            $pegawai->jabatan = $request->input('jabatan');
            $pegawai->nama_pegawai = $request->input('nama_pegawai');
            $pegawai->alamat = $request->input('alamat');
            $pegawai->gambar_pegawai = $filename;
            $pegawai->save();
            // $pegawai = Pegawai::create($request->all()); 
            return redirect()->route('pegawai.index')->with('message','Data berhasil dibuat!'); 
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        $pegawai = Pegawai::findOrFail($id);
        return view('pegawai.show', compact('pegawai'));
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $pegawai = Pegawai::findOrFail($id);
        return view('pegawai.edit', compact('pegawai')); 
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $this->validate($request, [
            'kategori' => 'required',
            'jabatan' => 'required',
            'nama_pegawai' => 'required',
            'alamat' => 'required',
            'gambar_pegawai' => 'required'
            ]);
            
            // script delete tapii gagal
            // if ($request->produk()->gambar_pegawai){
            //     Storage::delete('images/' . $request->produk()->gambar_pegawai);
            // }

            // update file
            $filename = time() . '.png';
            $request->file('gambar_pegawai')->storeAs('public/images', $filename);

            $pegawai = Pegawai::find($id);
            $pegawai->kategori = $request->input('kategori');
            $pegawai->jabatan = $request->input('jabatan');
            $pegawai->nama_pegawai = $request->input('nama_pegawai');
            $pegawai->alamat = $request->input('alamat');
            $pegawai->gambar_pegawai = $filename;
            $pegawai->save();

            // $pegawai = Pegawai::findOrFail($id)->update($request->all());
            return redirect()->route('pegawai.index')->with('message', 'Data berhasil diubah!'); 
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $pegawai = Pegawai::findOrFail($id)->delete();
        return redirect()->route('pegawai.index')->with('message', 'Data berhasil dihapus!');
    }

public function search(Request $request)
{
    // menangkap data pencarian
    $search = $request->search;

    // mengambil data dari table pegawai sesuai pencarian data
    $pegawai = DB::table('pegawais')
    ->where('nama_pegawai','LIKE',"%".$search."%")
    ->paginate();

        // mengirim data pegawai ke view index
    return view('pegawai.index',['pegawais' => $pegawai]);

    }
}

Index.php

<form action="/pegawai/search" method="GET">
    <input type="text" name="search" placeholder="Cari Pegawai .." value="">
    <input type="submit" value="Search">
</form>

P.S : im sorry if I post it wrong since this is my first post... and sorry for my terrible english

any help is truly appreciated.



via Chebli Mohamed

Route is not working inside the controller

I did an autocomplete search function in Laravel using ajax. I tried to pass the route inside the href but it's working. I don't know how to pass the route in the controller. Please help me and give a solution on how to fix this.

$output = '';

        if (count($pro)>0)
        {
            foreach ($pro as $row)
            {
                $url = "";

                $output .= '<li><a href="'.$url.'">'.$row->product_name.'</a></li>';
            }
        }
        else {

            $output .= '<li>'.'No results'.'</li>';
        }

        return $output;

Now once I click the li tag URL is coming like this.

https://testing.com/product-detail/%7B%7B%20route('ProductDetail','.Chiaro-Tote-1.')%20%7D%7D

I attached the screenshot here

enter image description here



via Chebli Mohamed

Laravel Broadcast Event not working with Socket.io & Laravel-Echo

Here is the event:

class AssetsInfo implements ShouldBroadcast
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    public $actionId;
    public $actionData;

    public function __construct($actionId, $actionData)
    {
        $this->actionId = $actionId;
        $this->actionData = $actionData;
    }

    public function broadcastOn()
    {
        return new Channel('sahmshenas-channel');
    }

    public function broadcastWith()
    {
        return [
            'actionId' => $this->actionId,
            'actionData' => $this->actionData,

        ];
    }
    public function broadcastAs(){
        return 'QueueStats';
    }
}

And here is the bootstrap.js:

import Echo from "laravel-echo"

window.io = require('socket.io-client');

window.Echo = new Echo({
    broadcaster: 'socket.io',
    host: window.location.hostname + ':6001'
});

Here is the Echo call in frontend:

Echo.channel('sahmshenas-channel')
        .listen('.QueueStats', (e) => {
        var action = e.actionId;
        var actionData = e.actionData;
        if(action == "score_update" && actionData.team1_score) {
        $("#team1_score").html(actionData.team1_score);
        console.log("yes");
        }
        });

And the route:

Route::get('queue-stats', function (){
        $actionId = "score_update";
        $actionData = array("team1_score" => 46);
        event(new ActionEvent($actionId, $actionData));
        return view('pages.queue-stats');
    });

I want to use WebSockets to show stock market data in realtime in the app for all users.
Data is being stored in a MySQL database, so I want to call the data, and send to users via this channel.
Anyways, Websocket connects without any problem. But nothing receives in the frontend.
Not even console logs anything. Where am I doing wrong?



via Chebli Mohamed

Cloudinary Video uploading error Entity too large up to 300MB

I am using Cloudinary by using library "https://ift.tt/2fz6Z2Q" but when I upload large video files greater than 100MB it shows "Entity too large: error, I am using apache server. Also try Cloudinary upload_large function but show same error.

    Cloudder::uploadVideo($tmpFilePath,null, ['resource_type' => 'video','chunk_size' => 60000000000]);
    $response = Cloudder::getResult();

Resulted error: enter image description here



via Chebli Mohamed

mardi 24 novembre 2020

Laravel Delayed queued jobs disappearing randomly

I'm facing a very strange issue for a long time now. I am working in Laravel 5.3. The problem is with delayed queues.

i.e. for my customer's I have something to do via queue jobs.

But sometimes my jobs disappears randomly. I can't see them in logs, failed_jobs table or anywhere. Even if my action / data is the same, It will work first time. 2nd time may be done't.

I had tried putting some logs. They gave me no issue. And getting passed successfully before / after where I'm placing queue job in my code.

I've tried this on Laravel 8 also. But the issue is same.

Before my QUEUE_CONNECTION was SYNC But i've also tested with following. But the result is same

QUEUE_DRIVER=redis

QUEUE_CONNECTION=redis

QUEUE_DRIVER=database

QUEUE_CONNECTION=database

Current code.

queue.php

return [

/*
|--------------------------------------------------------------------------
| Default Queue Driver
|--------------------------------------------------------------------------
|
| The Laravel queue API supports a variety of back-ends via an unified
| API, giving you convenient access to each back-end using the same
| syntax for each one. Here you may set the default queue driver.
|
| Supported: "null", "sync", "database", "beanstalkd", "sqs", "redis"
|
*/

'default' => env('QUEUE_DRIVER', 'redis'),
'failed' => [
    'database' => env('DB_CONNECTION', 'mysql'),
    'table' => 'failed_jobs',
],

.env

QUEUE_DRIVER=redis
QUEUE_CONNECTION=redis

jobFile.php

<?php

 namespace App\Jobs;

 use Illuminate\Bus\Queueable;
 use Illuminate\Queue\SerializesModels;
 use Illuminate\Queue\InteractsWithQueue;
 use Illuminate\Contracts\Queue\ShouldQueue;
 use Illuminate\Support\Facades\Log;

 class jobFile implements ShouldQueue
 {
     use InteractsWithQueue, Queueable, SerializesModels;

  protected $order_id;
/**
 * Create a new job instance.
 *
 * @return void
 */
public function __construct($data)
{
      $this->order_id=$data;
}

/**
 * Execute the job.
 *
 * @return void
 */
public function handle()
{

And this is how i am placing jobs

   $this->dispatch((new jobFile($id))->onQueue('high')
            ->delay(Carbon::now()->addMinutes(1)))
   );

   Also tried with dispatch().

Can anyone please let me know what can i do for fixing this problem?



via Chebli Mohamed

HRM Laravel 7 Installation

I am trying to install this HRM but it does not work, I have always an error when I am using installation.( When I am trying to open Public folder ). I tried different versions of PHP. I use Easy PHP. If some would give me an advice or help me, I would appreciate it a lot.

https://codecanyon.net/item/hrm-saas-human-resource-management/23400912 Laravel 7



via Chebli Mohamed

localhost is currently unable to handle this request HTTP ERROR 500

I am using Laravel 7 with PHP 7.3. I am running my project with artisan serve it works perfectly. But I want to run without artisan serve i have set up everything how to run without artisan serve. But Now I getting HTTP ERROR 500 I have checked larave.log for error but it's not creating in the logs folder. I have tried with this command but still not get success.

sudo chmod -R 775 storage

I have searched a lot of this error but failed to solve this. thanks in advance



via Chebli Mohamed

Is this Possible to run Multiple jobs in parallel?

We are using many of job in our project . But the problem is on some places we dispatch() queue in loop or database chunk() . But problem is when data is big almost 10000 it runs for hours . and All other jobs get paused for that time.

Is there Possible to run those 10000 jobs separately without disturbing other jobs?

Here is code for database queuery which is taking data in chunk which has 10000 records

Invoice::where('payment_status', 1)->chunk(1, function($invoices) {
        FillUpInChunkJob::dispatch($invoices);
            
        });


via Chebli Mohamed

Laravel could not find second driver

I'm building a webapp which have two databases:
First: Database for user registrations, sign up etc. / in MySQL
Second: Database for the stock market data / in PostgreSQL


First database (MySQL) works without any problem.
But the second one (PostgreSQL) doesn't work.


This is my env file:

DB_CONNECTION=mysql
DB_HOST=localhost
DB_PORT=3306
DB_DATABASE=panel
DB_USERNAME=root
DB_PASSWORD=

DB_CONNECTION_SECOND=pgsql
DB_HOST_SECOND=localhost
DB_PORT_SECOND=5432
DB_DATABASE_SECOND=assets_daily_info
DB_USERNAME_SECOND=postgres
DB_PASSWORD_SECOND=1234

And here is the database config php file:

'mysql' => [
            'driver' => 'mysql',
            'url' => env('DATABASE_URL'),
            'host' => env('DB_HOST', '127.0.0.1'),
            'port' => env('DB_PORT', '3306'),
            'database' => env('DB_DATABASE', 'forge'),
            'username' => env('DB_USERNAME', 'forge'),
            'password' => env('DB_PASSWORD', ''),
            'unix_socket' => env('DB_SOCKET', ''),
            'charset' => 'utf8mb4',
            'collation' => 'utf8mb4_unicode_ci',
            'prefix' => '',
            'prefix_indexes' => true,
            'strict' => true,
            'engine' => null,
            'options' => extension_loaded('pdo_mysql') ? array_filter([
                PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'),
            ]) : [],
        ],

        'pgsql' => [
            'driver' => 'pgsql',
            'url' => env('DATABASE_URL'),
            'host' => env('DB_HOST_SECOND', '127.0.0.1'),
            'port' => env('DB_PORT_SECOND', '5432'),
            'database' => env('DB_DATABASE_SECOND', 'forge'),
            'username' => env('DB_USERNAME_SECOND', 'forge'),
            'password' => env('DB_PASSWORD_SECOND', ''),
            'charset' => 'utf8',
            'prefix' => '',
            'prefix_indexes' => true,
            'schema' => 'public',
            'sslmode' => 'prefer',
        ],

I made a Model where I want to get data from PostgreSQL database:

    namespace App\Models;
use Illuminate\Support\Facades\DB;
use Illuminate\Database\Eloquent\Model;

class Thepage extends Model
{
    protected $connection = 'pgsql';
    protected $table = 'queue_stats';
    protected $fillable = [
        'buyqueue', 'sellqueue', 'timestamp',
    ];
}

And finally, here is the controller:

class Thepage Controller extends Controller
{
    public function index()
    {
        $queues = Thepage::all();
        return view('pages.queue-stats',compact('queues'));
    }
}

The problem is that laravel can't find the driver, it just shows:

Illuminate\Database\QueryException could not find driver (SQL: select * from "queue_stats")

I double checked apache's and php's .ini files, extension pdo_pgsql and pgsql are uncommented in both files.
I tried clear cache and config cache, nothing happened and I still get this annoying error.
Where am I doing wrong?



via Chebli Mohamed

lundi 23 novembre 2020

How to pass multiple value with key to url using vue.js

I have this attributes data

 data(){
        return {
             formData :new Form({
                attributes:[],
}),

I have a attribute id and an attribute value so i want to pass this id and value to url so that i cab loop in my controller attributes array and get id and value :

localhost:8000..?attributes[]['attribute_id_1']=attributevalue1&attributes[]['attribute_id_2']=attributevalue2...

I'm redirecting like this :

 this.$router.push({ path: '/search-list',query:
                    {

                     
                    }

Issue is i want to pass this multidimentional array to url, anyother workaround for this is also highly appreciated



via Chebli Mohamed

Having issue with connection to AZURE SQL DB in LARAVEL

I am trying to connect to Azure sql db in laravel for that I have added the creds in the .env file and changed the default to 'default' => env('DB_CONNECTION', 'sqlsrv'), but its giving error that login for user username. Error

[Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Login failed for user 'username'

This is the error I am getting when I am trying to fetch any record from DB.



via Chebli Mohamed

installin,g dompdf package get this error

PHP Fatal error: Uncaught ReflectionException: Class config does not exist in E:\MesProjetsLaravel\dgrs\vendor\laravel\framework\src\Illuminate\Container\Container.php:788 Stack trace:



via Chebli Mohamed

Why I cannot maximize the Slider Size?

Hello I am using Laravel Version 5. I wanted to Fit the Slider on a certain Screen or to maximize its size. Apologies since I am still new to using PHP and Laravel.

Here's my code for the slider:

`@extends('layouts.front')

 @section('content')

 @if($ps->slider == 1)

    @if(count($sliders))

        @include('includes.slider-style')
    @endif
@endif

@if($ps->slider == 1)
    <!-- Hero Area Start -->
    <section class="hero-area">
        @if($ps->slider == 1)

            @if(count($sliders))
                <div class="hero-area-slider">
                    <div class="slide-progress"></div>
                    <div class="intro-carousel">
                        @foreach($sliders as $data)
                            <div class="intro-content " style="background-image: url()">
                                <div class="container">
                                    <div class="row">
                                        <div class="col-lg-12">
                                            <div class="slider-content">
                                                <!-- layer 1 -->
                                                <div class="layer-1">
                                                    <h4 style="font-size: px; color: " class="subtitle subtitle" data-animation="animated "></h4>
                                                    <h2 style="font-size: px; color: " class="title title" data-animation="animated "></h2>
                                                </div>
                                                <!-- layer 2 -->
                                                <div class="layer-2">
                                                    <p style="font-size: px; color: "  class="text text" data-animation="animated "></p>
                                                </div>
                                                <!-- layer 3 -->
                                                <div class="layer-3">
                                                    <a href="" target="_blank" class="mybtn1"><span> <i class="fas fa-chevron-right"></i></span></a>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        @endforeach
                    </div>
                </div>
            @endif

        @endif`

Here is how my Slider is being shown: enter image description here

As you can see, the slider image was cut. it is not being shown as a full image.(Desktop) But when I change the view to Mobile, it shows full picture and adjust to its size. Should I check other forms inside my folder?

Thank you in the future!



via Chebli Mohamed

Larvel dhtmlx gantt chart with smartadmin/4.5.1 theme

I am using laravel dhtmlx gantt chart into bootstrap smartadmin/4.5.1 theme, And I am facing issue in app.bundal.css when I import dhtmlx gantt chart css file in the template. When I import dhtmlx gantt chart css template is continue loading. How I can solve this problem. Laravel version: 5.8 php version: 7.2



via Chebli Mohamed

dimanche 22 novembre 2020

Laravel Apply middlware on specific route of resource route controller

I want to apply middleware on create route of resource controller but confused how to set middleware. Normally we can add middleware like this

Route::get('api/users/{user}', function (App\Models\User $user) {
    return $user->email;
})->middleware('name');

but when we have a resource controller so how could I apply middleware on single route of resource controller.

Route::resource('front-pages','Admin\FrontPagesController');


via Chebli Mohamed

Trying to POST image into form from Admin side to User on main.js

Here is the Admin side where all the magic happens with posting on my Laravel app:

Admin POST

And this is what I am trying to achieve on my main.js for the admin side, I want it to Post the Image to the sql database and be shown on user side:

Main.js

This is what it looks like when trying to POST from admin:

It is incorrectly shown because it is incorrectly written I think.

and the following is what is inputted into the database from the main.js, and its as far as I can go :(

this or something like this



via Chebli Mohamed

samedi 21 novembre 2020

Maatwebsite Excel - how to name multiple sheets?

I've got an Maatwebsite (v3.1.25) Excel Export as follows. What is the simplest way to add a custom name for each sheet? Currently they just appear as "Worksheet", "Worksheet 1" etc.

I did see the official website's documentation, but couldn't figure out how to apply it to my specific situation.

class BizdevReport implements WithMultipleSheets
{


    public function sheets(): array
    {
        $sheets = [
            new BizdevReportTeachers(),
            new BizdevReportClasses(),
            new BizdevReportGMV()
        ];

        return $sheets;
    }


}


via Chebli Mohamed

jeudi 19 novembre 2020

config not working on production in laravel

I have Defined in .env file

MID = DE121323123
CALLBACK_URL = https://test.com/
MERCHANT_KEY = @32g#!hjcvxv

also defined config/app.php

'mid' => env('MID'),
'callback' => env('CALLBACK_URL'),
'marchendkey' => env('MERCHANT_KEY'),

and i am calling on my view page

    $mid=  config('app.mid');
    $callback=  config('app.callback');
    $printBarcodeUrl = config('app.marchendkey');

it's working fine in my localhost but its not working on my live server(production), i have also used given commands before the production

php artisan route:cache
php artisan config:clear
php artisan clear-compiled
php artisan cache:clear
php artisan config:cache
php artisan view:clear

but not working on my live server

also did APP_ENV=productionin env file



via Chebli Mohamed

Why my destroy function are not functioning?

i'm doing the destroy function in the controller. Therefore, once click the destroy icon it supposed to delete the data. But it don't do anything and just go to the blank page only.

Here are my coding:

AcademicQualificationController.

public function destroy($id)
    { dd($id);
        //dd($request->all());
        // $pastedu = $this->acadqualification->delete($id);
        return Redirect::to(URL::previous() . "#step-1");
    }

    // public function delete($id)
    // {
    //     dd($id);
    // }
    //
    /* DataTables*/
    //
    public function getData(Request $request)
    {
        $academic_qualification = AcademicQualification::select('academic_qualifications.*', 'institutions.name as institution', 'education_levels.name as qualification')
            ->join('institutions', 'academic_qualifications.institution_id', '=', 'institutions.id')
            ->join('education_levels', 'academic_qualifications.education_level_id', '=', 'education_levels.id')
            ->whereNull('academic_qualifications.deleted_at')
            ->where('academic_qualifications.staff_id', $request['id']);

        $datatables = DataTables::make($academic_qualification)
            ->addIndexColumn()
            ->addColumn('institute', function ($academic_qualification) {
                return $academic_qualification->institution;
            })
            ->addColumn('qualification', function ($academic_qualification) {
                return $academic_qualification->qualification;
            })
            ->addColumn('action', function ($academic_qualification) {
                $html = Forms::iconUpdate('#', [
                    'data-toggle' => 'modal',
                    'data-title'  => msg('lbl_update_academic_qualification'),
                    'data-target' => '#modal_global_form',
                    'data-url'    => route('academic_qualification.edit', ['staff_id' => $academic_qualification->staff_id, 'acad_id' => $academic_qualification->id]),
                    'data-action' => route('academic_qualification.update', ['staff_id' => $academic_qualification->staff_id, 'acad_id' => $academic_qualification->id]),
                    'data-size'   => 'modal-lg',
                ]) . " ";
                $html .= Forms::iconDelete(route('academic_qualification.destroy', ['acad_id' => $academic_qualification->id]), 'class="sa2_delete"') . " ";
                // $html .= Form::iconDelete(route('area_of_interest_detail.destroy', $id), 'class="sa2_delete"') . " ";
                return $html;
            })
            ->rawColumns(['action'])
            ->toJson();

        return $datatables;

        //
    }

This is my view blade: list.blade.php


<div class="panel panel-default">
    <div class="panel-heading">
        <h4></h4>
    </div>
    <div class="panel-body">
        <div class="form-horizontal">
            <div class="form-group">
                    <label class="col-lg-2 control-label">{!! msg('lbl_education_level') !!}</label>
                <div class="col-lg-4">
                    {!! Form::dropdown('education_level_id', $edulevelselection, '', 'class="select2-form edulevel"') !!}
                </div>
                <span>
                    {!! Form::buttonAdd('','#',[
                    'data-toggle' => 'modal',
                    'id' => 'education',
                    'data-title' => msg('lbl_new_academic_qualification'),
                    'data-target' => '#modal_global_form',
                    'data-url' => route('academic_qualification.create', [ 'id' => $staff_id] ),
                    'data-action' => route('academic_qualification.store'),
                    'data-size' => 'modal-lg',
                    'data-param' => '{ }'
                    ]) !!}
                </span>
            <div>
        </div>
        <div class="table-responsive">
            <table id="academic_qualification-table" class="table table-striped b-t b-b">
            </table>
        </div>
    </div>
    <div class="m-t-xl">
            <input type='button' class='btn btn-default button-previous' name='previous' value='Previous' />
            {!! Form::buttonSave('save & continue','',[
            'id' => 'submit-application',
            'class' => 'button-next pull-right'
            ]) !!}
    </div>
</div>

@push('scripts')

@endpush

<script type="text/javascript">

    $(".select2-form").select2({
    placeholder: "Please Select",
    allowClear: true
    });

    $("select[name=education_level_id]").change(function(e){
    var edulevelid = $('.edulevel').val();
    console.log(edulevelid);
    $('a[data-param]').attr('data-param','{"education_level_id":'+edulevelid+'}');
    });

    var table = $('#academic_qualification-table').DataTable({
    {!! Config::get('datatable.setting') !!}
    ajax: '{!! route('academic_qualification.postData', ['id' => $staff_id]) !!}',
    columns: [
        { sTitle: 'No', mData: 'DT_Row_Index', width:'5%' },
        { sTitle: '', mData: 'institution' },
        { sTitle: '', mData: 'qualification' },
        { sTitle: '', mData: 'grade' },
        { sTitle: '', mData: 'year' },
        { sTitle: '', mData: 'action' },
    ],
    });

    </script>


This is my route:

Route::resource('academic_qualification', 'Setting\General\AcademicQualificationController');

The view of system: before click the delete button enter image description here

after click the delete button enter image description here

The page just blank. Thank you.



via Chebli Mohamed

Checking if row exists in Table with 10 million rows

I'm importing XML file values to DB and end up checking if the row already exists, this takes a lot of time as the table has around 10million rows. For a file to import it takes roughly 90 seconds, on empty database 4secs. I'm checking if the row exists with laravel eloquent exists() method. I want to reduce this time as much as possible, if im importing 10k files, it takes DAYS. I was thinking of saving inserted rows in redis cache and checking if row exists from cache, but if for some reason cache is cleared I don't want to make duplicates in database. Is there anything better than redis?



via Chebli Mohamed

Login not working in Laravel using vue.js

I'm trying to Login using Laravel and Vue.js its controller code is:

  public function login(Request $request){ 

        $validation = Validator::make($request->all(),[
            'user_id' => 'required|email',
            'password' => 'required|string|min:8|max:15',
        ]);

        if ($validation->fails()) {
            $response['status'] = false;
            $response['message'] = $validation->errors()->first();
            return response()->json($response,200);
        }

        if(Auth::attempt(['email' => request('email'), 'password' => request('password')])){ 
            $user = Auth::user(); 
            $token =  $user->createToken('MyApp')->accessToken;  
   
            $user->api_token = $token;
            $user->save();
          
            return response()->json([
                'status'=>true,
                'message' => 'Login successfully',
                'user' => $user,
            ], 200); 
        } 
        else{ 
            return response()->json(['status'=>false,'message' => 'Invalid Login'], 200);
        } 

    }

but i'm getting Invalid Login message



via Chebli Mohamed

How to create project in laravel with Comopser

I want to create my project/folder with command C:\xampp\htdocs>composer create-project laravel/laravel laravel "5.1.*" on my local host but this error occur.

[Composer\Json\JsonValidationException] "./composer.json" does not match the expected JSON schema:

  • name : Does not match the regex pattern ^a-z0-9/a-z0-9$

How can i resolve this. I am new in Laravel and its my first project.



via Chebli Mohamed

Model property casts empty array in Laravel when it shouldn't

everyone. Model has a property

protected $casts = ['changes' => 'array'];

It's saved by laravel in db automatically as json object. For example

{"before":{"title":"Title1"},"after":{"title":"Title2"}}

But when I try to get it in a controller method as $this->changes it returns empty array [] for some reason. I created a getter:

    public function getTestAttribute()
    {
        return $this->changes;
    }

And that's what i get in tinker:

>>> $activity->changes
=> [
     "before" => [
       "creation_date" => "2021-05-12",
     ],
     "after" => [
       "creation_date" => "2020-07-07 00:00:00",
     ],
   ]
>>> $activity->test
=> []

And the same thing happens in a method where I reference the property. Undefined index because it's an empty array

$before = $this->changes['before'];

PHP Notice:  Undefined index: before

I have no idea what's going on and why it's empty



via Chebli Mohamed

Laravel - problem with Crypt::decrypt, wrong syntax in code

I know that my solution is wrong, but can someone help me with correct syntax how decrypt my string and log in ?

Laravel API resived code and store encrypted in Database

api route

Route::post('data','DataImport@Insert');

controller

use Illuminate\Support\Facades\Crypt;

function Insert(Request $request)
{
    $user=new User();
     $user->code=Crypt::encrypt($request->get('code'));
    return $user->save();
}

Auth\Controller

use Illuminate\Support\Facades\Crypt;

public function postLogin(Request $request)
{
    request()->validate([
        'id_message' => 'required',
        'code' => 'required',
    ]);
   
    $credentials = $request->only('id_message', 'code');
    $decrypted = $request->only('code'); 
    $request->session()->flash('success');

    if ($user=User::where($credentials)->first()) {
        if (\Crypt::decrypt($user->code) == $decrypted) {
            Auth::login($user);
            
        return redirect()->intended('dashboard')->with('success');
        }
    }
    //dd($decrypted);

    return Redirect::back()->with('error');
}

dd($decrypted);

 array:1 [▼
 "code" => "123456"
]

decrypted code is in correct value. No error in laravel.log only message code does not match.

thanks for any help.

(solution with hash, dont help me with this problem)



via Chebli Mohamed

Database Query taking long time and then failed in laravel 5.8

I am using laravel query which is taking long time and then failed. I tried many ways but nothing worked.

This is the query

$consignments = Consignment::where('customer_id', $invoice->customer_id)->doesnthave('invoice_charges')->get();

here is consignment model which is having Many relationships

<?php

namespace App\Models\Admin;

use Illuminate\Database\Eloquent\Model;

class Consignment extends Model
{
    protected $table = 'consignments';
    /**
     * @var array
     */
    protected $guarded = [];

    /**
     * @var array
     */
    protected $hidden = [
        'created_at', 'updated_at'
    ];

    public function pickupConsignment()
    {
        return $this->hasOne('App\Models\Admin\PickupDeliveryConsignment', 'pickup_consignment_id');
    }
    public function deliveryConsignment()
    {
        return $this->hasOne('App\Models\Admin\PickupDeliveryConsignment', 'delivery_consignment_id');
    }

    public function customers()
    {
        return $this->belongsTo('App\Models\Admin\Customer', 'customer_id');
    }

    public function income_charge_schemes()
    {
        return $this->hasOne('App\Models\Admin\IncomeChargeScheme', 'consignment_id');
    }

    
}

As you see consignment model has many relationships but i think query fetch all the relationships data with it .

When I use toBase() It gets load quickly but it doesn't fetch relationship which is required

here is the query with toBase()

$consignments = Consignment::where('customer_id', $invoice->customer_id)->doesnthave('invoice_charges')->toBase()->get();

I think this relationship which is creating issue

I also tried cursor() function but didn't work ..

How i can optimize this query any suggestion?



via Chebli Mohamed

mercredi 18 novembre 2020

How to call a blade file in img src tag in laravel

I am integrating php captcha into laravel, There i need to include a file in img src tag, so that captcha image may appear as code shown below

<img src="/Captcha.blade.php?rand="

captcha.blade.php file consists of code to generate image and random code.

But i am not getting how to include a blade file in src tag. Can anyone help me regarding this

Thank you



via Chebli Mohamed

Deploy laravel project on subfolder in cpanel

I am using laravel 5.6 . In my cpanel I keep php version 7.1 . I want to deploy it on a subfolder like url should be www.domain.com/project . I uploaded my full project in a subfolder. But I have to go www.domain.com/project/public this url to access project , which not my expectation. And If I hit any route it creates *www.domain.com/route and shows 404. It's not taking subfolder name. How can I fix it? Thanks in advance



via Chebli Mohamed

How to insert Token and data to API and display result

I am working one one Api where I have to Custno & his token which will give me data as output but I am unable to do so. i have done so for is

class Profiles extends Controller
 {
function list()
{
    $data = Http::get('https://hris.kseb.in/osvtest/ksebltws/api.php/usrp/validateConsumerWS')->json();

    
    return view('profiles',['data' =>$data]);   
}

My External Api Is : hris.kseb.in/osvtest/ksebltws/api.php/usrp/validateConsumerWS

My beriear Token : eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJvcnVtYW5ldC5rc2ViLmluIiwiYXVkIjoiYXBpOlwvXC9kZWZhdWx0IiwiaWF0IjoxNjA1NjgzMDUyLCJuYmYiOjE2MDU2ODMwNTQsImV4cCI6MTYwNTc2OTQ1MiwiZGF0YSI6eyJjbGllbnRJZCI6IjMwMTciLCJjbGllbnQiOiJVU1JQIiwib25saW5lQ2hhbm5lbCI6IlVTUlAifX0.3Y2Ns1d8CW9WkoyyU_sblHASJ6NUReBQGLqzlJMTY68

Custno : 1146360000000

how can i achieve this ???

when i am hitting req result of custno should come



via Chebli Mohamed

GET http://url/invoices/create_consignment_invoice/318 500 (Internal Server Error) in laravel

There is one page in our laravel project. which Hereis giving this error. We are not understanding why this error is coming.

I tried to dd() $consignments variable in controller it shows result but on blade console it gives this error

GET http://url/invoices/create_consignment_invoice/318 500 (Internal Server Error)

Here is Controller function

{

        $invoice = Invoice::find($id);
        // ->doesnthave('invoice_charges')
        // ->
        $consignments = Consignment::where('customer_id', $invoice->customer_id)->doesnthave('invoice_charges')->get();

       
            // $consignments = Consignment::where('customer_id', $invoice->customer_id)->doesnthave('invoice_charges')->get();
        // ->whereDate('created_at', '>', Carbon::now()->subDays(10))
        return view('web.admin.pages.misc.invoices.consignment_invoices.create', compact('consignments', 'invoice'));
    }

Route

Route::get('/create_consignment_invoice/{invoice_id}', 'Admin\Misc\InvoiceController@createConsignmentInvoice')->name('invoices.consignment.create');

invoice

public function invoice_charges()
    {
        return $this->hasOne('App\Models\Admin\InvoiceCharge', 'object_id')->where('model', 'Consignment');
    }


via Chebli Mohamed

mardi 17 novembre 2020

Custom Validator Rules in Laravel Return always message

I have a problem that I can't find a solution, in reality 2 problems.

The first problem is the following, I made a custom validation rule to validate the "NIF" (identity used in Portugal), until this point everything is working, the validation rule is working, the problem is the message that is returning, the message is always "The given data was invalid." but "Invalid NIF" should appear.

<?php

namespace App\Rules;

use Illuminate\Contracts\Validation\Rule;

class NifValidator implements Rule
{
    /**
     * Create a new rule instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Determine if the validation rule passes.
     *
     * @param  string  $attribute
     * @param  mixed  $value
     * @return bool
     */
    public function passes($attribute, $value)
    {
        $ignoreFirst = true;
        $nif = trim($value);
        \Log::info("Valida Rules NIF: " . $nif);
        //Verificamos se é numérico e tem comprimento 9
        if (!is_numeric($nif) || strlen($nif) != 9) {
            return false;
        } else {
            $nifSplit = str_split($nif);
            //O primeiro digíto tem de ser 1, 2, 5, 6, 8 ou 9
            //Ou não, se optarmos por ignorar esta "regra"
            if (
                in_array($nifSplit[0], [1, 2, 5, 6, 8, 9])
                ||
                $ignoreFirst
            ) {
                //Calculamos o dígito de controlo
                $checkDigit = 0;
                for ($i = 0; $i < 8; $i++) {
                    $checkDigit += $nifSplit[$i] * (10 - $i - 1);
                }
                $checkDigit = 11 - ($checkDigit % 11);
                //Se der 10 então o dígito de controlo tem de ser 0
                if ($checkDigit >= 10) {
                    $checkDigit = 0;
                }

                //Comparamos com o último dígito
                if ($checkDigit == $nifSplit[8]) {
                    \Log::info("VALIDA NIF  TRUE");
                    return true;
                } else {
                    \Log::info("VALIDA NIF  False");
                    return false;
                }
            } else {
                \Log::info("VALIDA NIF  false");
                return false;
            }
        }
    }

    public function validate($attribute, $value, $params)
    {
        return $this->passes($attribute, $value);
    }

    /**
     * Get the validation error message.
     *
     * @return string
     */
    public function message()
    {
        return ':attribute inválido';
    }
}

My AppServiceProvider.php

<?php

namespace App\Providers;

use Hyn\Tenancy\Environment;
use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Str;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        $env = app(Environment::class);

        if ($fqdn = optional($env->hostname())->fqdn) {
            config(['database.default' => 'tenant']);
        }

        // money format
        Str::macro('money', function ($price) {
            return number_format($price, 2, ',', '.');
        });

        \Validator::extend('nifvalidator', '\App\Rules\NifValidator@validate');
    }

    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }
}

My Controller

<?php

namespace App\Http\Controllers\Auth;

use App\Authentication\Register;
use App\Http\Controllers\Controller;
use Exception;

class RegisterController extends Controller
{
    use \App\Traits\Helpers\ResponseJSON;

    public function create()
    {
        try {
            $payload = request()->all();

            $rules = [
                'nif' => 'required',
                'name' => 'required',
                'email' => 'required|email',
                'password' => [
                    'required',
                    'string',
                    'min:8', // must be at least 8 characters in length
                    'regex:/[A-Za-z]/', // must contain at least one uppercase letter
                    'regex:/[0-9]/', // must contain at least one digit
                ],
                'country' => 'required',
            ];

            $messages = [
                'password.regex' => 'A password precisa ter no minimo 1 letra e 1 número',
            ];

            //portugal
            if (176 == $payload['country']) {
                // if (!Cliente::validaNif($payload['nif'])) {
                //     throw new Exception("register.nif_invalid");
                // }
                $rules['nif'] = "nifvalidator";
            }

            $this->validate(request(), $rules, $messages);

            
            return $this->responseJSON([], 'register.register_success');
        } catch (\Illuminate\Validation\ValidationException $validExcept) {
            return $this->responseJSON([], $validExcept->getMessage(), 401);
        } catch (Exception $except) {            
            return $this->responseJSON([], $except->getMessage(), 401);
        }
    }
}

The second problem is that if I noticed the controller I did a regex validation in the password field to identify if there is a letter or a number, I also customized the message that would appear in the regex field, but the message that returns is always the same "The given data was invalid.

To be honest, I don't know what to do anymore, everything I found on the internet I tried and it didn't work.

I really appreciate the help.



via Chebli Mohamed

Laravel 8: Update model's timestamps without saving other attributes

I have an issue with the touch() method. Here's the flow:

  1. I'm temporarily decrypting the field inside the model to send to the authorized user.
  2. Updating updated_at timestamp with new log entry to indicate that field was decrypted.
  3. Returning decrypted model with the response without saving it in DB.

The issue:

So, here's the problem: When I do $model->touch() it is saving the whole model (as expected as Laravel's only checking if updated_at column isDirty(), not the whole model, and then calling $this->save()).

Question:

Is there another method that I can use to just update the model's timestamps regardless of if other attributes have been changed?



via Chebli Mohamed

Laravel doesn't render "**head** and **body**" tags in blade

I have an HTML email template with head and body tags in my database table. I'm trying to render the actual HTML with the "head and body" tags in my blade.

I'm using {!! $data->email_body !!} to render the HTML. It does render the HTML version but the problem is, it automatically cuts off the head and body tags while rendering, showing the html data without these tags.

Is there any option to render the whole HTML "as is" without cutting off the "head and body" tags?



via Chebli Mohamed

Laravel 5.5 Flash Message not working in blade file after redirect

I want to logout if user is_active == 0 on login function My Code

LoginController.php

protected function authenticated(Request $request, $user)
{
    if($user->is_active == 0){
        Auth::logout();
        return redirect('/')->with(['errorMessage' => 'Your account is temporary blocked']);
    }
}

View Code:

@if(session('errorMessage'))
    <span class="alert alert-danger">
        
    </span>
@endif


via Chebli Mohamed

Cannot display image in vue.js

I'm saving image in following path :

storage\app\public\img\user_image

and saving image url like this in database:

/img/user_image/285070719.png

trying to display image like this:

 <img :src="'../app/public'+profile.image">

but the image does not display, Any solution to resolve this issue is highly appreciated.



via Chebli Mohamed

How to get Expiry date flag from pivot table Joining the parent table grouped by parent_id

I have a parent table with jobs and a pivot table with job provider (boards) and expiry dates.

Adjob table

id:1, job_title: Experienced full stack developer, .. .. location:Europe is_active:1

Boards table

id:1, adjob_id:1, board_name:Adzuna, expiry_date:2020-12-20,

id:2 adjob_id:1, board_name:Seek, expiry_date:2020-11-10,

id:3, adjob_id:1, board_name:Jora, expiry_date:2020-11-25,

This is the query used

$ads= Adjob::select([
            'adjobs.id',
            'adjobs.response',
            'adjobs.post_date',
            'adjobs.job_title',
            'adjobs.created_by',
            \DB::raw('(CASE 
                    WHEN (boards.board_name = "Adzuna" && (NOW() < boards.expiry_date && datediff(expiry_date,NOW()) <= 7)) THEN "1" 
                    WHEN (boards.board_name = "Jora" && (NOW() < boards.expiry_date && datediff(expiry_date,NOW()) <= 7)) THEN "1" 
                    WHEN (boards.board_name = "Seek" && (NOW() < boards.expiry_date && datediff(expiry_date,NOW()) <= 7)) THEN "1" 
                    ELSE "0" 
                    END) AS expiry')
            ])
            ->leftJoin('boards', 'adjobs.id', 'boards.adjob_id')
            
            ->where([['adjobs.active',1]])
            ->groupBy('adjobs.id')
            ->get();                    

But it is only checking the first values (i.e) Adzuna expiry only, because it is grouped by Parent table id i.e adjobs.id. How to check all the three expiry date using above the query.



via Chebli Mohamed

Laravel migrate fresh specific migration

I'm trying to migrate some database tables in my Laravel application. I'm using a third party library https://github.com/spatie/laravel-schedule-monitor which seems to break and requires re-migrating when upgrading. If I run php artisan migrate:fresh locally it'll work just fine, but amongst all of my other migrations I don't want to overwrite and dump the data in my other tables in a production environment.

I want to migrate:fresh a specific migration...

UPDATE

When trying to run the refresh command on a table, the below happens...

monitors



via Chebli Mohamed

How to use composite primary key in laravel 8?

I didn't use the migration files because I have preexisting tables in the database, I want to know how to force laravel to use my composite primary key.if there is any method to override. The composite primary key is (Tel + number_str ) This is my function in the model :

public function saveData(){
  $response = new ResponseModel(); 
                //Primary key(Tel + number_str )
                $reponse->Tel = '0123456789';//---> the first key
                $reponse->number_str = '1'; //---> the second key
    
                $reponse->view = '0';  
                $reponse->channal = '0';
                $reponse->save();
}

when I execute I have this error:

Yajra\Pdo\Oci8\Exceptions\Oci8Exception
Error Code : 904 
Error Message : ORA-00904: "ID": invalid identifier Position : 98 Statement : insert into "RESPONSE" ("TEL", "number_str", "view", "channal ") values (:p0, :p1, :p2, :p3) returning "ID" into :p4 Bindings : [0123456789,1,0,0,0]


via Chebli Mohamed

How to pass data id to modal?

i need to pass the dropdown id value once been selected. The id must be pass to modal.

This is my code for view :

<div class="panel panel-default">
    <div class="panel-heading">
        <h4></h4>
    </div>
    <div class="panel-body">
        <div class="form-horizontal">
            <label class="col-lg-2 control-label">{!! msg('lbl_education_level') !!}</label>
            <div class="col-lg-4">
                {!! Form::dropdown('education_level_id', $edulevelselection, '', 'class="select2-form edulevel"') !!}
            </div>
            <span>
                    {!! Form::buttonAdd('','#',[
                    'data-toggle' => 'modal',
                    'id' => 'education',
                    'data-title' => msg('lbl_new_academic_qualification'),
                    'data-target' => '#modal_global_form',
                    'data-url' => route('academic_qualification.create', [ 'id' => $staff_id] ),
                    'data-action' => route('academic_qualification.store'),
                    'data-size' => 'modal-lg',
                    'data-param' => '{ }'
                    ]) !!}
                </span>
        </div>
    </div>
</div>
@push('scripts')
<script type="text/javascript">

$('#education_level_id').change(function(e){
    var edulevelid = $('#education_level_id').val();
    console.log(edulevelid);
    $('#education').attr('data-param','{"education_level_id":'+edulevelid+'}');
})

</script>
@endpush

But the value i want is not show up, i do the dump() at the controller. it just show my id only. Supposedly from the dropdown form should include in the dump. This is the dump i make on the controller:

enter image description here



via Chebli Mohamed

Why Laravel Sanctum SPA Authentication always keep the user logged in?

I used Laravel Sanctum SPA authentication. I can log out the user but I am wondering why is it that the user is still logged in even when I close the browser. I don't even implement the remember me function.



via Chebli Mohamed

lundi 16 novembre 2020

How to send SMS using firebase in laravel

I am developing a laravel application,in which while user register, i want to send the registration code through SMS, i don't want to use any paid services.I heard about firebase free SMS gateway. Is there any option to send SMS through firebase



via Chebli Mohamed

Relation query undefined method

In my setting model class i have this

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

and in my user model class i have this

 public function settings()
    {
        return $this->belongsTo('App\settings', 'id');
    }

I tried both these queries, trying to get the user information but failed.

$data = DB::table('settings')
                        ->where('id', '=', $id)
                        ->get()
                        ->toArray();

and

$table = \App\settings::where('id', '=', $id);
        $query = $table->user()
                       ->get()
                       ->toArray();

I'm getting this error

Call to undefined method Illuminate\Database\Eloquent\Builder::user()

How do you do relation query? Sorry new to laravel here.



via Chebli Mohamed

Store data into database using request json string in laravel

I am having a table name Student ( id , name , division ). To store data into this table I am sending json string as a request to the api in laravel.

Request json string is,

{
"name":"abc",
"division":"a",
"city":"xyz"
}

Controller Code

 public function registerStudent(Request $request){

    $requestData = $request->json()->all(); 
    $studentModel = Student::create($requestData);

 }

Student Model

class Student extends Model
{
    protected $fillable = [
        'id', 'name','division'
    ];

   
}

When i execute this code , i get the following error,

Illuminate\Database\QueryException: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'city' in 'field list' (SQL: insert into `Student`... 

now my question here is, in what way I can store the data into database from json request with having extra keys into json object/array.



via Chebli Mohamed

Ayuda no funciona Laravel imdhemy/laravel-in-app-purchases verificar comprar de android en latravel

uso laravel 5.8 y estoy tratando de integrar mi backend con las compras de android he usado esta biblioteca de laravel llamada Laravel In-App purchase

y he recibido este error todo el tiempo, pues falta una clase que no se encuentra:

use Imdhemy\Purchases\Facades\Subscription;

alguien a usado esta clase y le a funcionado?



via Chebli Mohamed

Laravel route not found when route exists

When I try to access my laravel site I get this error in the console.

Laravel development server started: <http://127.0.0.1:8000>
[Mon Nov 16 10:39:15 2020] PHP Fatal error:  Uncaught InvalidArgumentException: Route [home] not defined. in /Users/threeaccents/code/src/gitlab.com/few/bodylove/vendor/laravel/framework/src/Illuminate/Routing/UrlGenerator.php:389
Stack trace:
#0 /Users/threeaccents/code/src/gitlab.com/few/bodylove/vendor/laravel/framework/src/Illuminate/Foundation/helpers.php(822): Illuminate\Routing\UrlGenerator->route('home', Array, true)
#1 /Users/threeaccents/code/src/gitlab.com/few/bodylove/storage/framework/views/e071ac62e490c49233841ae8b6b3906075bc0187.php(6): route('home')
#2 /Users/threeaccents/code/src/gitlab.com/few/bodylove/vendor/laravel/framework/src/Illuminate/View/Engines/PhpEngine.php(43): include('/Users/threeacc...')
#3 /Users/threeaccents/code/src/gitlab.com/few/bodylove/vendor/laravel/framework/src/Illuminate/View/Engines/CompilerEngine.php(59): Illuminate\View\Engines\PhpEngine->evaluatePath('/Users/threeacc...', Array)
#4 /Users/threeaccents/code/src/gitlab.com/few/bodylove/vendor/laravel/framework/src/Illuminate/View/View.php(142): Illuminate\Vi in /Users/threeaccents/code/src/gitlab.com/few/bodylove/vendor/laravel/framework/src/Illuminate/Routing/UrlGenerator.php on line 389
[Mon Nov 16 10:39:15 2020] PHP Fatal error:  Uncaught InvalidArgumentException: Route [home] not defined. in /Users/threeaccents/code/src/gitlab.com/few/bodylove/vendor/laravel/framework/src/Illuminate/Routing/UrlGenerator.php:389
Stack trace:
#0 /Users/threeaccents/code/src/gitlab.com/few/bodylove/vendor/laravel/framework/src/Illuminate/Foundation/helpers.php(822): Illuminate\Routing\UrlGenerator->route('home', Array, true)
#1 /Users/threeaccents/code/src/gitlab.com/few/bodylove/storage/framework/views/e071ac62e490c49233841ae8b6b3906075bc0187.php(6): route('home')
#2 /Users/threeaccents/code/src/gitlab.com/few/bodylove/vendor/laravel/framework/src/Illuminate/View/Engines/PhpEngine.php(43): include('/Users/threeacc...')
#3 /Users/threeaccents/code/src/gitlab.com/few/bodylove/vendor/laravel/framework/src/Illuminate/View/Engines/CompilerEngine.php(59): Illuminate\View\Engines\PhpEngine->evaluatePath('/Users/threeacc...', Array)
#4 /Users/threeaccents/code/src/gitlab.com/few/bodylove/vendor/laravel/framework/src/Illuminate/View/View.php(142): Illuminate\Vi in /Users/threeaccents/code/src/gitlab.com/few/bodylove/vendor/laravel/framework/src/Illuminate/Routing/UrlGenerator.php on line 389

But route home is clearly defined. I even set it at the top of my route file to make sure nothing else was overriding it.

routes/web.php
<?php

// New Home Page for App
Route::get('/', 'Web\HomeController@index')->name('home');

...

with php artisan route:list

+--------+----------------------------------------+--------------------------------------------------------------------------------------------+--------------------------------------------+------------------------------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Domain | Method                                 | URI                                                                                        | Name                                       | Action                                                                                         | Middleware                                                                                                                                                                        |
+--------+----------------------------------------+--------------------------------------------------------------------------------------------+--------------------------------------------+------------------------------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|        | GET|HEAD                               | .well-known/apple-developer-merchantid-domain-association                                  |                                            | App\Http\Controllers\Web\ApplePayDomainVerificationController                                  | web                                                                                                                                                                               |
|        | GET|HEAD                               | /                                                                                          | home                                       | App\Http\Controllers\Web\HomeController@index                                                  | web                                                                                                                                                                               |

Update

I've cleared route cache, deleted vendor folder, re-installed PHP but nothing seems to solve the issue.

I've tried it on my work laptop (same setup) and everything works. It seems to be an issue with my current station but I'm not sure what would be causing it. I'm using PHP 7.2 on a mac os 10.14.4

I also thought maybe it was an overall system issue but if I create a new laravel project everything works as expected so it does seem to be a project specific issue.



via Chebli Mohamed