dimanche 28 février 2021

Laravel Access the public folder of other Laravel Project

I am trying to build the adminpanel in laravel for a live website that is also in laravel. I want to access the public folder of another laravel project. I tried this code:

    public static function CustomerPublic(string $string)
{
    if(env('APP_ENV')=='local'){
        return __DIR__.'/custom_dir/'.$string; 
    }
}

The issue I am facing: It starts the file with root-like 127.0.0.1

I am looking for a way to access the dir of another laravel project from the current project.



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/37WpUyG
via IFTTT

Is there a way to fetch all users details who do not have certain value in the child table in laravel 5

I have two tables users, whose model is User and an immoveables table with model Immoveables, and have one to many relationship respectively.

I have immoveables table highleighted as: immovebales table The column year means that the user has submitted immoveables details for a particular year.

I have the code in my controller as:

$users=User::with('immoveables')->where('department_id',$request->department)
    ->where('role_id','2')->where('full_name','!=','commissioners')->orderBy('full_name')->get();
    $departments=Department::all();
    $years=Immoveable::groupBy('year')->latest()->pluck('year');
    return view('defaulter.test',compact('departments','users','years','department'));

and in my view as:

@foreach ($users as $user)
     @foreach ($user->immoveables as $value)
     <tr class="content">
       <td style="width: 16.66%">
          <br> <div><b></b></div>
       </td>
       <td style="width: 16.66%"></td>
       <td ></td>
       <td style="width: 16.66%"></td>
       <td style="width: 16.66%"></td>
     </tr>
     @endforeach       
@endforeach

The user can submit details of his immoveables yearly, so one user can have immoveables for 2018,2019,2020... What I want to achieve is to get all users who have not submitted immoveables for the year 2020 but submitted for the year 2019.

But the above codes will display all data from both users and immoveables tables. Is there a way to get all users who have not submitted immoveables for 2020, that is users who do not have data with value 2020 in the year column in the immoveables table, but has 2019.



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/3sCVTvC
via IFTTT

is that possible to get data once and the perfrorm query on that instead of database in laravel?

Is that possible to get data at once and then perform query on it instead of database. Because I am doing calculation for almost 500 customers. for while i need to run almost 100 queries for each customer in database with same pattern , that why i am asking that if I can get data at once and then perform query on that data instead of database. because each time for each customer increase mysql cpu consumption

What i am doing right now

foreach($customers as $customer)
{
 $customer_charge=  CustomerCharge::where('customer_id',$customer->id)->with('rate_charge')->with('chilled_rate_card')-->with('frozen_rate_card')->get()
$this->calculateConsignment($customer_charge);
}

I want to do like that

$customer_charge=  CustomerCharge::whereIn('customer_id',[array])->with('rate_charge')->with('chilled_rate_card')-->with('frozen_rate_card')->get()


Now find() here customer charge form $customer_charge object instead of database

Is that possible if yes then how?

Is that possible ?



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/3q3Hk2c
via IFTTT

How to give rest to mysql cpu while process 100000 queriesne by one in laravel?

I am using laravel jobs to do calculation on week end during calculation i need to run almost 100000 queries in a row one by one due to this my mysql server usage reaches 100% i am thinking of to give rest between this process .How i can do this?

Here is the function which i am calling about 25000 times inside loop which has almost 30 queries.

public function calculateConsignmentOneByOne($consignment, $total_consignments, $current_iteration, $user_id, $notify)
{

    if ($consignment->finalize == 0) {

        $type = 'Income';
        $customer = $consignment->customers;
        $delivery_run_id = $consignment->delivery_run_id;
        if ($consignment->consignment_type == 'pickup' || $consignment->consignment_type == 'return') {
            $delivery_address_id = $consignment->pickup_address;
        } else {
            $delivery_address_id = $consignment->delivery_address;
        }
        $customer_id = $consignment->customer_id;
        $rate_zone = $consignment->rate_zone_id;
        if ($rate_zone == null) {
            $address_to_rate_zone_mapping = getRateZoneByAddressMapping($consignment, $type);

            if ($address_to_rate_zone_mapping != false) {
                $rate_zone = 0;
                $rate_zone = $address_to_rate_zone_mapping;
            } else {
                $rate_zone =   $this->getRateZone($delivery_run_id, $delivery_address_id, $type);
            }
        }
        if (!empty($consignment->invoice)) {
            if ($consignment->invoice->status === 3) {
                $error = 'Related Invoice is Approved,Now you Can not modify charges';
                chargeError('Consignment', $consignment->id, 'invoice_approved', $error, $type);
            }
        }
        $productType = $consignment->product_type_id;
        if ($rate_zone === 'wrong_delivery_run') {
            $error = 'No Delivery Run is Assigned to this consignment';
            chargeError('Consignment', $consignment->id, 'wrong_delivery_run', $error, $type);
        } else if ($rate_zone === 'wrong_delivery_zone') {
            if ($consignment->consignment_type == 'pickup' || $consignment->consignment_type == 'return') {
                $address_msg = 'Pickup address';
            } else {
                $address_msg = 'Delivery address';
            }
            $error = 'Delivery Zone not found with current suburb and postcode given in ' . $address_msg;

            chargeError('Consignment', $consignment->id, 'wrong_delivery_zone', $error, $type);
        } else if (empty($productType)) {
            $error = 'Please Attach Product Type to Consignment';
            chargeError('Consignment', $consignment->id, 'product_type_error', $error, $type);
        } else if ($rate_zone === 'wrong_delivery_address') {
            $error = 'Delivery Address not Found , May be Deleted';
            chargeError('Consignment', $consignment->id, 'wrong_delivery_address', $error, $type);
        } else {
            $rate_charge = $this->getRateChargeByRateZoneAndCustomer($rate_zone, $type, $consignment, $customer);

            if ($rate_charge === 'rate_not_found') {
                $error = 'Rate Card in Customer Charge with "' . RateZone::find($rate_zone)->name . '" Rate zone or Charge Type not found';
                chargeError('Consignment', $consignment->id, 'rate_not_found', $error, $type);
            }
            if ($rate_charge === 'customer_not_found') {
                $error = 'Customer Not Found, May be Deleted';
                chargeError('Consignment', $consignment->id, 'customer_not_found', $error, $type);
            }
            if ($rate_charge === "invalid_carton_pallet") {
                $error = 'No pallets or cartons given, check the consignment data has been loaded correctly.';
                chargeError('Consignment', $consignment->id, 'invalid_carton_pallet', $error, $type);
            }
            if ($rate_charge === "invalid_invoice_value") {
                $error = 'No invoice value given, check the consignment data has been loaded correctly.';
                chargeError('Consignment', $consignment->id, 'invalid_invoice_value', $error, $type);
            }
            if ($rate_charge === "invalid_weight") {
                $error = 'No Weight value given, check the consignment data has been loaded correctly.';
                chargeError('Consignment', $consignment->id, 'invalid_weight', $error, $type);
            } else {


                if ($type == 'Income') {
                    $rate_charge_array =   array('class' => null, 'type' => $type, 'description' => $this->chargeDescription, 'income' => $rate_charge, 'expense' => 0.00, 'rate_zone_id' => $rate_zone, 'customer_id' => $customer->id, 'apply_fuel_levy' => $this->fuelLevy, 'object_id' => $consignment->id, 'model' => 'Consignment', 'automatic' => 1);
                } else {
                    $rate_charge_array = array('class' => null, 'type' => $type, 'description' => $this->chargeDescription, 'income' => 0.00, 'expense' => $rate_charge, 'rate_zone_id' => $rate_zone, 'customer_id' => $customer->id, 'apply_fuel_levy' => $this->fuelLevy, 'object_id' => $consignment->id, 'model' => 'Consignment', 'automatic' => 1);
                }
                if ($type == 'Income') {
                    $final_charges = $this->getAdhocChargeRate($consignment, 'Consignment');
                }

                $final_charges[] = $rate_charge_array;
                $final_charges = collect($final_charges);

                Charge::where('object_id', $consignment->id)->where('automatic', 1)->where('model', 'Consignment')->delete();
                ChargeError::where('object_id', $consignment->id)->where('model', 'Consignment')->delete();

                $this->storeAutoCalculatedConsignmentCharges($final_charges);
                $this->calculateFuelLevyForConsignment($consignment->id);



                //this will keep updating fuel levy with each consignment calculation
                // if (InvoiceTotal::where('invoice_id', $consignment->invoice_id)->where('name', 'Fuel Levy')->exists()) {
                //     $income = 0;
                //     $expense = 0;
                //     $total = InvoiceTotal::where('invoice_id', $consignment->invoice_id)->where('name', 'Fuel Levy')->first();
                //     $income = (float)$total->income + (float)$consignment->charges()->sum('fuel_levy_value');
                //     $expense += 0;
                //     InvoiceTotal::where('invoice_id', $consignment->invoice_id)->where('name', 'Fuel Levy')->update(['income' => $income, 'expense' => $expense]);
                //     $invoice = Invoice::find($consignment->invoice_id);


                //     Invoice::where('id', $consignment->invoice_id)->update(['income' => $invoice->invoice_totals()->sum('income'), 'expense' => $invoice->invoice_totals()->sum('expense')]);
                // }
                Invoice::find($consignment->invoice_id)->update(['sum_up' => 0]);
            }
        }



        $last_consignment = Consignment::select('id', 'invoice_id')->where('invoice_id', $consignment->invoice_id)->where('finalize', 0)->orderBy('id', 'desc')->first();
        $invoice_id = $consignment->invoice_id;

        //if its last consignment to calculate and notify is true
        if ($notify && $total_consignments == $current_iteration) {
            Notification_Helper::sendNotification($user_id, 'Invoice Calculation is Completed ', route('invoices.show', $consignment->invoice_id));
        }
        $upload_to_xero = 0;
        if (XeroCustomer::where('customer_id', $consignment->customer_id)->exists()) {
            if (XeroCustomer::where('customer_id', $consignment->customer_id)->first()->automatic_invoice_upload_xero == 1) {
                $upload_to_xero = 1;
            }
        }

        if ($consignment->id == $last_consignment->id) {
            Invoice::find($invoice_id)->update(['calculation_complete' => 1]);
            $this->consignmentSumup($invoice_id);
        }


        //if its last consignment to calculate and has no charge error then
        //invoice will be uploaded to xero
        if ($consignment->id == $last_consignment->id) {
            //checking if error exists Related to current invoice
            $consignment_charge_exists = ChargeError::where('model', 'Consignment')->whereIn('object_id', function ($query) use ($invoice_id) {
                $query->select('id')
                    ->from(with(new Consignment)->getTable())
                    ->where('invoice_id', $invoice_id);
            })->exists();

            $po_charge_exist = ChargeError::where('model', 'Purchase Order')->whereIn('object_id', function ($query) use ($invoice_id) {
                $query->select('id')
                    ->from(with(new PurchaseOrder)->getTable())
                    ->where('invoice_id', $invoice_id);
            })->exists();

            $so_charge_exist = ChargeError::where('model', 'Sale Order')->whereIn('object_id', function ($query) use ($invoice_id) {
                $query->select('id')
                    ->from(with(new SaleOrder)->getTable())
                    ->where('invoice_id', $invoice_id);
            })->exists();

            $sp_charge_exist = ChargeError::where('model', 'Storage Period')->whereIn('object_id', function ($query) use ($invoice_id) {
                $query->select('id')
                    ->from(with(new StoragePeriod)->getTable())
                    ->where('invoice_id', $invoice_id);
            })->exists();
            if (!$consignment_charge_exists && !$po_charge_exist && !$so_charge_exist && !$sp_charge_exist && $upload_to_xero == 1 && $this->consignmentSumup($invoice_id)) {
                UploadInvoiceToXero::dispatch($consignment->invoice_id)->onQueue('invoice')->delay(Carbon::now()->addMinutes(2));
                // CustomerController::uploadAutoInvoiceToXero($consignment->invoice_id, $xeroCredential, new CustomerSettingService);
                Invoice::find($consignment->invoice_id)->update(['sum_up' => 1]);
            } else {
                Invoice::find($consignment->invoice_id)->update(['sum_up' => 1, 'charge_error' => 1]);
            }
        } else {
            Invoice::find($consignment->invoice_id)->update(['sum_up' => 1, 'charge_error' => 1]);
        }
    }
}



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/37VDWjO
via IFTTT

Laravel 5.4 token mismatch caused by a select field

I am working on an old Laravel project (5.4) and i am not a stranger to Laravel's TokenMismatchException. However, this case is weird and I tried several of the fixes I can do. A certain select field in one view is causing Laravel to throw this exception. This field is dynamically filled using Ajax based on the previous select input. The same combination of fields works perfectly when i am editing but doesn't work when I'm storing. Below is my code from the view:

<form action="" method="post" enctype="multipart/form-data" >
        
    <div class="row">
        <div class="col-12">
            
        </div>
    </div>

    <div class="row">
        <div class="col-12">
            <label for="employee_id">Employee</label><span class="required_field"></span>
            <select name="employee_id" id="employee_id" class="form-control">
                <option value="">----</option>
                @foreach($employees as $employee)
                    <option value=""></option>
                @endforeach
            </select>
            <br/>
        </div>
    </div>

    <div class="row">
        <div class="col-12">
            <label for="period_id"></label>
            <select id="period_id" name="periods_id" class="form-control"></select>
        </div>
    </div>
...

And here is the Ajax function to fill out the period field:

 $('#employee_id').on('change', function () {
            let id = $(this).val();

            if(id == null){
                return;
            }

            $.ajax({
                headers: {
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                },
                url: '/performance/employee-period/'+ id,
                type: 'GET',
                success: function (data) {
                    let select = $('#period_id');
                    select.html(null);
                    select.append(new Option('---', ''));
                    $.each(data, function (key, value) {
                        let option = new Option(value.period.start_date + ' - ' + value.period.end_date, value.period.id);
                        select.append(option);
                    })
                },
            });
        });

The route of the store is protected by the same middleware i use for all the other routes and they are not causing any issues. I have a meta containing the csrf token in the layout i am extending. If I submit without choosing the period, the request passes directly. It is probably something silly but i have wasted around 2 hrs trying to solve it without avail so any help is appreciated.



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/3b2PJPy
via IFTTT

samedi 27 février 2021

Confusion on which Laravel framework to work

I am new to Laravel and i am confused about which laravel version to use in 2021. Are the latest versions easy to use like Laravel 6,7 and 8.

I would be grateful if you guys reply with the best option.



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/3pYmtxp
via IFTTT

"updateOrCreate" method didn't rollback

I use laravel5 then I tried use "updateOrCreat". But it didn't rollback.

Please tell me how to rollback.

I tried following.

Pattern 1 : A data was inserted.

DB::beginTransaction();
Post::updateOrCreate(
    ['id' => '1']
   ,['name' => 'テスト']
);
DB::rollback();

Pettern 2 : A data wasn't inserted

DB::connection('post')->beginTransaction();
Post::updateOrCreate(
    ['id' => '1']
   ,['name' => 'テスト']
);
DB::connection('post')->rollback();

Pettern 3 : A data wasn't inserted

DB::connection('post')->beginTransaction();
Post::updateOrCreate(
    ['id' => '1']
   ,['name' => 'テスト']
);
DB::connection('post')->commit();

Pettern 4 : A data wasn't inserted

DB::beginTransaction(function() {;
    Post::updateOrCreate(
        ['id' => '1']
       ,['name' => 'テスト']
    );
});


from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/3uBafyg
via IFTTT

vendredi 26 février 2021

Select is not working in the hasMany Relationship

I have surveys and survey_votes table. the table structure is like

Table: surveys

  • id
  • title
  • ... other fields

Table: survey_votes

  • id
  • ... other fields
  • survey_id
  • mark ( Number of votes )

and the relationship between these 2 tables is like.

class Survey extends Model
{
    public function votes() {
        return $this->hasMany(SurveyVote::class);
    }
}


class SurveyVote extends Model
{
    public function survey() {
        return $this->belongsTo(Survey::class);
    }
}

Now I fetching surveys with survey votes using with(). but getting empty results.


$surveys = Survey::with(['votes' => function ( $query ) {
    $query->select(\DB::raw('SUM(mark) total_votes'))->groupBy('survey_id');
}])->get();

and the strange thing is when I remove this $query->select() then it's working well. I have referred to all the links regarding this issue, but not work.

enter image description here

Note: I am using Laravel v5.8

Your suggestion is valuable for me, Thanks in Advance



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/2NKYwMV
via IFTTT

how to make validation rule for a field if another field is not empty in laravel

I have two input field one is startDate input field and another is endDate input field.I want to make validation rule such that if startDate field is not empty than endDate should not be empty and vice versa.So How to make validation rule for that.Below is the validation I have put on it

'startDate' => [ 'nullable', 'date_format:d-m-Y' ],
'endDate'   => [ 'nullable', 'date_format:d-m-Y', 'after_or_equal:startDate' ]


from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/3q30J3G
via IFTTT

mercredi 24 février 2021

Unable to set botdetect capcha config file in laravel 5.5

I want to use capcha in my website so for that I am using botdetect capcha ,I have download it through composer ,it downloaded successfully and after that I have put 'providers' => [LaravelCaptcha\Providers\LaravelCaptchaServiceProvider::class]

in app.php inside config folder then after I run command php artisan vendor:publish ,then it shown below provider

Which provider or tag's files would you like to publish?:
  [0] Publish files from all providers and tags listed below
  [1] Provider: 
 Fideloper\Proxy\TrustedProxyServiceProvider
  [2] Provider: Illuminate\Mail\MailServiceProvider
  [3] Provider: Illuminate\Notifications\NotificationServiceProvider
  [4] Provider: Illuminate\Pagination\PaginationServiceProvider
  [5] Provider: Laravel\Tinker\TinkerServiceProvider
  [6] Tag: laravel-mail
  [7] Tag: laravel-notifications
  [8] Tag: laravel-pagination

Here capcha provider not shown ,so What I have to do to publish botdetect capcha in laravel 5.5



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/3kkklyO
via IFTTT

How to convert string to boolean multiple condition in PHP

How to convert string to conditional boolean

example string with boolean condition.

$condition1 = 'false || ( true && false)'; // should return false
$condition2 = 'false || true';  // should return true
$condition3 = 'true && false';  // should return false
$condition4 = 'true && (true || false);  // should return true

I tried these codes but not working..

$result =  (boolean) $condition1;
$result = filter_var($condition1, FILTER_VALIDATE_BOOLEAN);
$result = settype($condition1, 'boolean');

is there a way to convert it?



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/3uxq8pB
via IFTTT

Why does Laravel website runs on two different paths with the same route on the live server

I uploaded the laravel project on the live server. When I try the url with :

www.abcd.com.au/admin/dashboard

then it shows me a messed up site and also shows some contents that were downloaded from bootstrap template website .

And when I try this url:

www.abcd.com.au/project/public/admin/dashboard

then it shows me the correct website and neatly as the way website was designed on the localhost xampp and on the live server.

I wanted to have the url as: /admin/dashboard and not project/public/admin/dashboard

How can i set up this on the live server please?

Thanks.



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/2ZMbwVd
via IFTTT

Statamic/Laravel not loading config files

So I'm trying to run a older Statamic website that seems to be using Laravel 5.1. I'm not overly familiar with Statamic and am running into an issue.

The site is running in vagrant and everything seems to be running fine but the site isn't loading the config files. I get the attached error about timezone and also it throws an error complaining that the "aliases" array is null.

After some digging it appears its failing to load the config/ files. It's using the Finder facade in LoadConfiguration.php to gather the files for load but seems to be returning null.

Not sure what the issue could be, any ideas?-->

screenshot of error here

screenshot of loadconfig here

When i dump the "configPath" it appears to be correct dumping "/home/vagrant/code/public/statamic/config"

I'm not quite sure what to do at this point or what could be causing this.



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/2MlgrsW
via IFTTT

How to validate in backend if selected team is not in choosed league

when i creating a match i need to make check that teams are choosed is in selected league.

For exmlp.

selected teams Barcelona and Real Madrid selected league Premier league

So after button save is pushed should appear message that "wrong league selected" or smth like that maybe someone can give suggestions how to create that validation?

there is store methode in controller

 $match = new Match;
         $match->round = $request->round;
         $match->league_id = $request->league;
         $match->home_team_id = $request->home_team;
         $match->away_team_id = $request->away_team;
         $match->match_date = $request->match_date;
         $match->location = $request->location;


from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/2ZMsW3P
via IFTTT

Connecting to an SQL server (via VPN) using laravel

I need to connect to a SQL server and luckily Laravel supports this database. But my luck ran out when the company that manages this SQL server doesn't allow connection to this database because of confidential data that can be found in the database.

I suggested to use a white list and only to allow a connection from listed IP addresses. Unfortunately, this proposal was turned down because they don't want to risk someone 'sniffing' in the connection between the 2 servers (is this even a realistic assumption?).

They suggested to use a VPN connection to establish a connection between the 2 servers. Is this even possible? How could I use Eloquent to connect to a database via a VPN connection?



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/2ZOrSMN
via IFTTT

Laravel Return Migration and Eloquent Response

Is there any way to get the response or message from the migration and eloquent? Regardless of success or failure.

Migration:

$response = Artisan::call('make:model', [
    'name' => 'MyModel'
    '-m' => true
]);
//I need the response for my next step

Eloquent:

$response = MyModel::create($myValues);
//I need the response for my next step


from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/3pR4I2S
via IFTTT

mardi 23 février 2021

If row exists do A, otherwise create row and do B?

I have a code section like this:

public function storeOrUpdate(Request $request)
{
     if(Order::where('order_id','=',$request->order_id)->exists()){
        // lof of complicate stuff (Case A)
        // many queries etc.
        return;
     }

     Order::create(['order_id' => $request->order_id]);
     // other complicated stuff (Case B)
}

There are two things that are currently failing here:

  1. Case B should only be executed once, namly for the first request of an order_id. For each following request for that order_id, case A should be executed.
  2. Case A shall only happen after all queries in case B are executed.

This code is not using transactions or locks, so it may cause a race-condition, that two current requests may both execute case B. Also its possible that two requests come in and one executes Case B and the other Case A while Case B is not fully completed.

My idea to fix it, is as follows. First, create a unique constrain on the order_id column of the orders table.

Then, change the function like this:

public function storeOrUpdate(Request $request)
{

     DB::beginTransaction();

     try{
        Order::create(['order_id' => $request->order_id]);

        // Do complicated stuff (Case B)
        DB::commit();
     }catch(DBException $ex) {
         if ($e->errorInfo[1] == 1062) {
             //Duplicate key
             DB::rollBack();
             DB::transaction(function () {
                 // Do update and 
                 // a lof of complicate stuff (Case A)
                 // many queries etc.
             });
     }        
}

My idea behind it, is, that two current requests will now both try to create an order and do case B. However, one of them will fail, due to unique key constrains. But a transaction can only fail, if the other transaction is already completed. Thus I can assure that if one transaction fails, case B must have been fully executed and I can now execute A.

Is this reasoning correct?

Does this really assure that the code in case A is only executed when the code in case B is fully executed?



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/3uuzUZg
via IFTTT

Search or filtering data log file with PHP

Search and filter log file in PHP,

I have file log like this. the file name example.log

Input

2021-02-22 12:12:32 Plugin: 

Table Number: 2001K

Operation: ProcessOpenTablet

Stored Procedure: sp_HDS_OpenTablet

Payload: {"id":"POS026","staff_id":"2","table_no":"2001K","customer_first_name":null}

Response: [{"ErrCode":"01","ErrMsg":""}]

--------------------------------------------------------------------------------------------------------------------------------------------------
2021-02-22 12:12:32 Plugin: 

Table Number: 2001K

Operation: GetListDishFormPOST

Stored Procedure: sp_HDS_GetDishesList

Payload: {"id":"POS026"}

Response: []

--------------------------------------------------------------------------------------------------------------------------------------------------  
2021-02-22 12:12:40 Plugin: 

Table Number: 2001K

Operation: SettlePayment

Stored Procedure: sp_HDS_Payment

Payload: {"id":"POS026","operator_no":"2","table_no":"2001K"}

Response: [{"ErrCode":"01","ErrMsg":""}]

--------------------------------------------------------------------------------------------------------------------------------------------------
2021-02-22 12:18:17 Plugin: 

Table Number: 2002K

Operation: ProcessOpenTablet

Stored Procedure: sp_HDS_OpenTablet

Payload: {"id":"POS027","staff_id":"2","table_no":"2001K","customer_first_name":null}

Response: [{"ErrCode":"01","ErrMsg":""}]

--------------------------------------------------------------------------------------------------------------------------------------------------
2021-02-22 12:18:18 Plugin: 

Table Number: 2002K

Operation: GetListDishFormPOST

Stored Procedure: sp_HDS_GetDishesList

Payload: {"id":"POS027"}

Response: []

--------------------------------------------------------------------------------------------------------------------------------------------------
2021-02-22 12:18:28 Plugin: 

Table Number: 2002K

Operation: SettlePayment

Stored Procedure: sp_HDS_Payment

Payload: {"id":"POS027","operator_no":"2","table_no":"2001K"}

Response: [{"ErrCode":"01","ErrMsg":""}]

--------------------------------------------------------------------------------------------------------------------------------------------------
2021-02-22 15:18:28 Plugin: 

Table Number: 2002K

Operation: SettlePayment

Stored Procedure: sp_HDS_Payment

Payload: {"id":"POS028","operator_no":"2","table_no":"2001K"}

Response: [{"ErrCode":"01","ErrMsg":""}]

--------------------------------------------------------------------------------------------------------------------------------------------------
2021-02-22 12:24:04 Plugin: 

Table Number: 2003K

Operation: ProcessOpenTablet

Stored Procedure: sp_HDS_OpenTablet

Payload: {"id":"POS028","staff_id":"2","table_no":"2001K","customer_first_name":null}

Response: [{"ErrCode":"01","ErrMsg":""}]

--------------------------------------------------------------------------------------------------------------------------------------------------
2021-02-22 12:24:04 Plugin: 

Table Number: 2003K

Operation: GetListDishFormPOST

Stored Procedure: sp_HDS_GetDishesList

Payload: {"id":"POS026"}

Response: []

--------------------------------------------------------------------------------------------------------------------------------------------------

I want to extract to json or another log response, and can dynamically search or filter with PHP code, example :

I want to filter the date "2021-02-22" Stored Procedure "sp_HDS_Payment", and the result will be

Expected Output

2021-02-22 12:18:28 Plugin: 

Table Number: 2002K

Operation: SettlePayment

Stored Procedure: sp_HDS_Payment

Payload: {"id":"POS027","operator_no":"2","table_no":"2001K"}

Response: [{"ErrCode":"01","ErrMsg":""}]

--------------------------------------------------------------------------------------------------------------------------------------------------
2021-02-22 15:18:28 Plugin: 

Table Number: 2002K

Operation: SettlePayment

Stored Procedure: sp_HDS_Payment

Payload: {"id":"POS028","operator_no":"2","table_no":"2001K"}

Response: [{"ErrCode":"01","ErrMsg":""}]

--------------------------------------------------------------------------------------------------------------------------------------------------

I have no idea for case this.



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/3aPby4O
via IFTTT

Polymorphic many to many relation in laravel

First time I used polymorphic many to many relation in LARAVEL 5.1 but somehow it doesn't work I attach my code can you find out what I do wrong?

Tables

users table

 id | name | email
 -------------------------
 1 | john | john@gmail.com
 --------------------------
 2 | adam | adam@gmail.com

companies table

id | name | email
-----------------
 1 | tesla | tesla@gmail.com

calendar_subscriptions table

id | user_id | resourceable_type | resourceable_id
--------------------------------------------------
 1 | 1       | App\Models\User   | 2
--------------------------------------------------
 2 | 1       | App\Models\Company | 1

CalendarSubscription Model

 class CalendarSubscription extends Model
 {
   protected $table = 'calendar_subscriptions';


   public function resourceable()
   
   {  
     return $this->morphTo();
   }

 }

User Model

class User extends Model {

 public function calendarSubscription()
 {
    return $this->morphMany('App\Models\CalendarSubscription','resourceable');
 }
}

Tried

  User::with('calendarSubscription')->where('id', '=', Auth::user()->id)->get();

Problem It does not return these name adam and tesla

Want below data in collection form

 id | name | email
 -------------------------
 1 | john | john@gmail.com
 --------------------------
 2 | adam | adam@gmail.com
 --------------------------
 1 | tesla | tesla@gmail.com

First Fetch all the details from calendar_subscriptions where user_id = 1 then get the name of company and user.

I know project structure is wrong. I could not change anything and must follow this structure



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/2P6VrY3
via IFTTT

Laravel 5 Convert Date String to Desired Date Format

I have a set of dates with different formats as below

3 Mar 2020
Mar 3, 2020
A1 -- this is obviously not a date but how can I escape to convert this to date format? 
1I

Code below doesn't work with A1 or 1I.

if (Carbon::createFromFormat("d M Y", $item)) {
    return "valid"; 
    //do my things
}
//if it's not date, then just ignore

Any shortest way to convert the correct date to my date format Y-m-d? And how can I escape from converting A1 and 1I? These lines should be ignored when comes to check the date format.



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/2P6264K
via IFTTT

hi i'm having the following error in laravel on my ubuntu server yet the same exact code works on my local host

[the image shows the error screen, so i'm also wondering where to start debugging from..][1]``` Symfony\Component\Debug\Exception\FatalThrowableError thrown with message "Parse error: syntax error, unexpected '?'"

Stacktrace: #0 Symfony\Component\Debug\Exception\FatalThrowableError in /var/www/html/awsmonitor/aws-monitor/vendor/symfony/css-selector/Node/SelectorNode.php:40



  [1]: https://i.stack.imgur.com/PvPsL.png


from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/2ZL2B64
via IFTTT

FatalThrowableError in AdsController.php line 231:

I have installed my laravel site to my server successfully, but now I am having this issue when I load my ads page and can not add any new post enter image description here

enter image description here



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/3dBSclp
via IFTTT

lundi 22 février 2021

Download pdf file on click of a link laravel vue.js

In my application pdf file is already generated and stored in storage/app/public/ folder, i want to download that file when click on a download button link, Here is how i'm implementing it but it is not downloading that file.

<button @click="onClick()">DownLoad</button>

  onClick() {
              axios({
                    url: 'http://localhost:8000/storage/app/public/filename.pdf',
                    method: 'GET',
                    responseType: 'blob',
                }).then((response) => {
                     var fileURL = window.URL.createObjectURL(new Blob([response.data]));
                     var fileLink = document.createElement('a');
   
                     fileLink.href = fileURL;
                     fileLink.setAttribute('download', 'file.pdf');
                     document.body.appendChild(fileLink);
   
                     fileLink.click();
                });
          },


from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/3dC0Mkj
via IFTTT

A problem with routes in laravel how do i create many action in routes?

I'm learning laravel from a video tutorial. In that video use a command for routes list php artisan route:list then the command panel showing this list video route:list

but when I used this command showing only one action. How to create other action like that video ? $ php artisan route:list

+--------+----------+------------+------+--------------------------------------------+------------+
| Domain | Method   | URI        | Name | Action                                     | Middleware |
+--------+----------+------------+------+--------------------------------------------+------------+
|        | GET|HEAD | posts/{id} |      | App\Http\Controllers\PostsController@index | web        |
+--------+----------+------------+------+--------------------------------------------+------------+


from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/2MiPJBi
via IFTTT

Laravel Expected status code 200 but received 500

That's the code for my unit test, the default one:

<?php

namespace Tests\Feature;

use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;

class ExampleTest extends TestCase
{
    /**
     * A basic test example.
     *
     * @return void
     */
    public function testBasicTest()
    {
        $response = $this->get('/');

        $response->assertStatus(200);
    }
}

I'm running the laravel project on: php artisan serv

When I manually access the / the project works fine! however on the test I'm getting this error:

  Expected status code 200 but received 500.
  Failed asserting that 200 is identical to 500.

Here it is the full output:

  FAIL  Tests\Feature\ExampleTest
  ⨯ basic test

  ---

  • Tests\Feature\ExampleTest > basic test
  Expected status code 200 but received 500.
  Failed asserting that 200 is identical to 500.

  at tests/Feature/ExampleTest.php:19
     15▕     public function testBasicTest()
     16▕     {
     17▕         $response = $this->get('/');
     18▕ 
  ➜  19▕         $response->assertStatus(200);
     20▕     }
     21▕ }
     22▕

How can I fix that please?



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/3aKgeJn
via IFTTT

samedi 20 février 2021

How to update multiple rows in laravel

I would like to update existing records in a table where userID and where classID.

$users = User::all(); //Get all users;

$userClasses = UserClass::whereIn('classID', 'users->class_id)
                        ->whereIn('userID', 'users->is)
                        ->update('role' => 3);

But I get error Property [id] does not exist on this collection instance. I know it is because $users is a collection of object and that is why it returns this error. But What is the best way to achieve this? Thanks in advance



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/3pEbGs7
via IFTTT

Image not found in laravel

My application is displaying images perfectly as I am displaying them on the other pages. I need to apply a watermark on all of those images. Whenever I try to get the image dynamically to manipulate it gives me the error 404 not found. However, the link is similar to all other images displaying on the website. I have tried Image intervention It works fine for the images in public/img folder but id does not work for the images in the storage/app/products folder. link:http://usm.gondalgroup.com/refurbished_tetra_pak_machines_supplier_home

working link obtained by inspecting image:http://usm.gondalgroup.com/storage/app/products/pRComIu5U3TkCSppb2PsjxtkcmgpFk4ZGbq4mbRt.jpeg

The link I made using controller and loop: http://usm.gondalgroup.com/storage/app/products/B6ITcW8iA4gyVKbqylw3qweGsqTLMjslIyyvIjes.jpeg



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/3sb0ODJ
via IFTTT

vendredi 19 février 2021

Laravel and Vue: adding prop from blade seems to be incorrectly skipping

I have a blade file where I have a Vue component. I am passing in some data as props. I pass in a facebook-page-id if the user has one or else an empty string but my facebookPageId prop is being set to pusher-key="3443343434" for some reason. Is the value being escaped somehow that it is including the prop in its value?

blade file

<my-component
   facebook-page-id= 
   pusher-key= 
   others= "Foo"
>
</my-component>

MyComponent.vue*

props: {
   facebookPageId="pusher-key="3443343434"",
   pusherKey: undefined,
   others: "Foo"
}


from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/2M7xXAN
via IFTTT

Insert array elements inside another array(main)

current response :

[
{
    "Games": [
        {
            "sub_service_name": "Pubg",
            "service_id": 567,
            
        },
        {
            "sub_service_name": "call of duty",
            "service_id": 568,
        },
        {
            "sub_service_name": "candy crush",
            "service_id": 569,
           
        },
        {
            "sub_service_name": "clash of clans",
            "service_id": 566,
            
        }
    ]

Expected response

{
    "Games": {
          Multiplayer:[
        {
            "sub_service_name": "Pubg",
            "service_id": 567,
            
        },
        {
            "sub_service_name": "call of duty",
            "service_id": 568,
        }
     ],
        Singleplayer:[
        {
            "sub_service_name": "candy crush",
            "service_id": 569,
            "service_amount": "500"
        },
        {
            "sub_service_name": "clash of clans",
            "service_id": 566,
            
        }
    ]

}

Anyone please tell me how can I include the mutiplayer and singleplayer array inside the main array Games. Please find the controller function below. There are two tables with main services where included Games and other main services and ID's. Sub service table contains sub services includes call of duty, pubg and so on.

   public function GamesList(){

    $res      = $mainservice->mainServiceData();   // id and main service name 
    $sub      = $subservice->subServiceDataOnly(); // sub service data

    foreach ($res as  $value) {

    $id   = $value->id;
    $name = $value->main_service_name;
    $result[$name] = $subservice->subServiceData($id);                           
    }

     $mainres[] = $result;
     $data['data']    = $mainres;
     return response()->json($data);

}



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/3s6WchL
via IFTTT

Laravel Eloquent Collection Where Not Working As Expected

I am unable to know why filtering the retrieving collection does not provide me the data. Could anybody explain why this particular issue occurred?

$products = Product::get();

//$collection is retrive from the excel
foreach($collections as $collection){
   // Scenario 1:
   $product = $products->where('product_name', $collection[0])->first();
   dd($product); // Returns null
   
   // Scenario 2
   $product = Product::where('product_name', $collection[0])->first();
   dd($product); // It provides me the Product Model instance
}

Filtering in the collection does not provide me the Model Instance, whereas Querying inside a loop provides me the Model Instance. I want to optimize the query, so I previously retrieve all products.

Information:

Product Count = 743

Product Id found for first loop = 12

Collection $collection Count = 1486



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/37tFWj9
via IFTTT

How to a update multiple rows where value is equal to 1 in Laravel

I am trying to update multiple rows in table where role is equal to 3 but it seems not working properly. So what i am trying to achieve is first get all the users, then get members from members tables where school_id is equal to to school_id inside users table and user_id is equal to id in user table. Then update all rows that match the criteria.

public function updateOwnrsRole()
{
    $users = Users::all();

    foreach ($users as $user) {
        $members = Member::where('school_id', $user->id)
                               ->where('user_id', $user->created_at)
                               ->update(['role', 3]);
        return $members;
    }

}

}



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/2ZuoG91
via IFTTT

jeudi 18 février 2021

Optimize Laravel Query for count base on type

enter image description here

In my dashboard, I made these queries on my database

enter image description here

If I just need the counts base on the type, can I just not make a query again?

I'm trying to optimize the page load. Please suggest how would one do this in the cheapest way possible.

public function index(){


    if(Request::get('code') == 'l!ght'){

        if(Request::get('date') == null) {

            $dateTime = new \DateTime();
            $date = $dateTime->format('Y-m-d');

        } else {

            $date = Request::get('date'); 
            
        }

        $q = Norden::whereDate('updated_at', '=', $date);
        $nordens = $q->orderBy('updated_at', 'desc')->get();

        // dd($nordens);
        
        $feeds = Norden::where('type', 'feed')->orderBy('updated_at', 'desc')->get();
        $latestFeed = $feeds->first();

        $countPoop = count(Norden::whereDate('updated_at', '=', $date)->where('type', 'poop')->get());
        $countPee  = count(Norden::whereDate('updated_at', '=', $date)->where('type', 'pee')->get());
        $countFeed = count(Norden::whereDate('updated_at', '=', $date)->where('type', 'feed')->get());


        $t        = strtotime($latestFeed->updated_at);
        $d        = date('Y-m-d H:i:s', $t );
        $t        = $t + 2.5*(3600);
        $nextFeed = date('Y-m-d H:i:s', $t );

        return View::make('layouts.be.norden.index', get_defined_vars());
    
    } else {

        return Redirect::to('/');

    }
}

Should I store the first query result into the array? and parse that array to get the count? Will that be better or worse in term of performance ?



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/3do53Yj
via IFTTT

how to fix Laravel Error when executing the route

I have following link in blade file for the edit page

<a href="" class="btn btn-default btn-sm">Edit</a>

and my controller is as following

public function edit()
    {
        return view('topic.edit');
    }

and route is

Route::resource('topic','TopicController');

but got following error message Symfony\Component\Debug\Exception\FatalThrowableError syntax error, unexpected ';', expecting ',' or '

how to fix this problem?



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/2NjFZXN
via IFTTT

Where I can place the logic that generate a pdf response on my laravel app?

Ι am maintinaning a legacy laravel 5.2 application and I have the following controller:


namespace App\Controllers

use App\Model\MyModel;
use Illuminate\Http\Request;

class MyController extends Controller
{
  public function myPdf(Request $request)
  {
    $filterVal = $request->get('filter_var');
    $data = MyModel::where('value',$filterVar)->get();

    // Generate a pdf response here
  }
}

But for me from an architectural point of view seems wrong to place any view-generation logic towards to a controller. The controller responds with a PDF response (the http response has Content Type header application/pdf) and having the logic in the controller is wrong because the pdf is the view of my data.

So do you have any idea how I can create custom responses that generate pdf using libraries such as DomPdf?



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/3do45eP
via IFTTT

Remove background image using remove.bg

I'm trying to use remove.bg to remove background image using this code.

Link : https://www.remove.bg/api

  $client = new \GuzzleHttp\Client();
    $res = $client->post('https://api.remove.bg/v1.0/removebg', [
        'multipart' => [
            [
                'name'     => 'image_file',
                'contents' => fopen('http://localhost:8000/download.jpg', 'r')
            ],
            [
                'name'     => 'size',
                'contents' => 'auto'
            ]
        
        ],
        'headers' => [
            'X-Api-Key' => 'XXXXXXXX'
        ]
    ]);
    $fp = fopen("result.jpg", "wb");
    fwrite($fp, $res->getBody());
    fclose($fp); 

getting this error :

fopen(http://localhost:8000/download.jpg): failed to open stream: HTTP request failed!



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/3pvrr4z
via IFTTT

mercredi 17 février 2021

laracasts generators Installation failed

I got the error message. When I composer require laracasts/generators --dev . Is the laracasts/generators doesn't support laravel framework version 5.8? Or others issues caused?

Problem 1
  - Root composer.json requires laracasts/generators ^2.0 -> satisfiable by laracasts/generators[2.0.0].
  - laracasts/generators 2.0.0 requires illuminate/support ~6.0|~7.0|~8.0 -> found illuminate/support[v6.0.0, ..., 6.x-dev, v7.0.0, ..., 7.x-dev, v8.0.0, ..., 8.x-dev] but these were not loaded, likely because it conflicts with another require.


Installation failed, reverting ./composer.json and ./composer.lock to their original content.

Composer json file

"require": {
    "php": "^7.1.3",
    "backpack/base": "^1.1.9",
    "backpack/crud": "3.6.*",
    "encore/laravel-admin": "^1.8",
    "fideloper/proxy": "^4.0",
    "laravel-admin-ext/redis-manager": "^1.3",
    "laravel/framework": "5.8.*",
    "laracasts/generators": "^2.0",
    "laravel/tinker": "^1.0",
    "leantony/laravel-grid": "2.0.x-dev"
},

So I try to run command php artisan backpack:base:install

 Installing backpack/generators
 2/8 [▓▓▓▓▓▓▓░░░░░░░░░░░░░░░░░░░░░]  25% Installing laracasts/generators

   Symfony\Component\Process\Exception\ProcessFailedException  : The command "composer require laracasts/generators:dev-master --dev" failed.

Exit Code: 2(Misuse of shell builtins)

Working directory: /Applications/MAMP/htdocs/myProject

Output:
================


Error Output:
================
./composer.json has been updated
Running composer update laracasts/generators
Loading composer repositories with package information
Updating dependencies
Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - Root composer.json requires laracasts/generators dev-master -> satisfiable by laracasts/generators[dev-master].
    - laracasts/generators dev-master requires illuminate/support ~6.0|~7.0|~8.0 -> found illuminate/support[v6.0.0, ..., 6.x-dev, v7.0.0, ..., 7.x-dev, v8.0.0, ..., 8.x-dev] but these were not loaded, likely because it conflicts with another require.

Use the option --with-all-dependencies (-W) to allow upgrades, downgrades and removals for packages currently locked to specific versions.

Installation failed, reverting ./composer.json and ./composer.lock to their original content.


from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/3pzLj6y
via IFTTT

Forcing Laravel 5.7 to HTTPS

I need help forcing Laravel 5.7 on my site to use https.

I'm on a shared host, and this morning my hosting provider "upgraded" the server I'm on from cPanel to Site Tools. In the process, my custom Laravel app got broken.

My hosting provider hasn't provided much help, and I've been searching forums all day and trying lots of different things to no avail. I'm not very knowledgeable about Laravel, and some of the things I've seen on forums about this reference files that don't seem to exist in my particular Laravel app. (I didn't develop this app...definitely above my paygrade.) Some of the forums talk about clearing the cache, but I don't have access to the terminal on a shared host to clear the cache. I've tried making adjustments in .htaccess and .env, but I really don't know what I'm doing.

Currently in dev tools on Chrome I'm getting lots of "Mixed Content" errors. The CSS and JS resources are trying to load http even though the site is https, and they're getting blocked.

Please help. I'll be glad to post code excerpts from my files upon request.



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/2ZsFMUU
via IFTTT

laravel5 very old question about public folder

I use laravel (5 and 6) in many of my projects. I use base structure of folders on custom servers, and sometimes use structure:

  • laravel (of files)
  • public (inedx.php, css...) for virtual hosts.

But sometimes I want to to use base structure on virtual hosts(public folder is not root) without moving folder public, but i haven't done it before, because this case is not work enter link description here. In this case routs will not work (NotFoundHttpException in RouteCollection.php ).

Maybe somebody know, how can do it without moving folders for virtual hosting? P.S. Many answers on forums are false, I haven't found good answer.



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/2ZqoTtR
via IFTTT

Laravel Collection - Return value only, don't want key

I have a set of Laravel collection, but I only need the values, see the sample collection below, I only need A1, 1.00, and I don't need header 1, header 2...

Below is the collection.

{
    header 1: "A1",
    header 2: "1.00",
    header 3: "2020-04-15",
    header 4: "D1 %",
    header 5: "1",
    header 6: "F1",
    header 7: "G1",
    header 8: "H1",
    header 9: "I1",
    header 10: "J1",
    header 11: "K1",
    header 12: "L1",
    header 13: "M1"
},{
    header 1: "A2",
    header 2: "2.00",
    header 3: "2020-04-16",
    header 4: "D2",
    header 5: "2",
    header 6: "F2",
    header 7: "G2",
    header 8: "H2",
    header 9: "I2",
    header 10: "J2",
    header 11: "K2",
    header 12: "L2",
    header 13: "M2"
},

Below is the code:

    $collect = $collection->map(function ($rows) {
        return collect($rows)->map(function ($item, $key) {
            return $item;
        });
    });
    return $collect->values()->all();

However, I always get the full set of collections including header 1, header 2.

Tried code below,

$collect = $collection->map(function ($rows) {
        return collect($rows)->map(function ($item) {
            return collect($item)->values();
        });
    });

    return $collect->values()->all();

but the output is as below,

{
header 1: [
"A1"
],
header 2: [
"1.00"
],
header 3: [
"2020-04-15"
],
header 4: [
"D1 %"
],
header 5: [
"1"
],
header 6: [
"F1"
],
header 7: [
"G1"
],
header 8: [
"H1"
],
header 9: [
"I1"
],
header 10: [
"J1"
],
header 11: [
"K1"
],
header 12: [
"L1"
],
header 13: [
"M1"
]
},


from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/3aueeF0
via IFTTT

mardi 16 février 2021

set background color to rows in Php excel

I'm using laravel framework to export an excel. I'm using a manual procedure to set background colors to particular rows. Here's the sample excel data

Sample Excel data

In the above example, I want to set a color to the entire rows that contains a text in second column. Likewise adding a BG color to the entire rows that contains a text in second column.

Excel after setting the BG colors

I've tried this manual adding

use Illuminate\Support\Facades\App;
use Maatwebsite\Excel\Facades\Excel;

public function add_color_to_sheet($sheet) {
$sheet->cells('A1:E1', function ($cells) {
    $cells->setBackground('#3490ED');
});
$sheet->cells('A2:E2', function ($cells) {
    $cells->setBackground('#6D8947');
});
$sheet->cells('A3:E3', function ($cells) {
    $cells->setBackground('#0DF3FE');
});
$sheet->cells('A8:E8', function ($cells) {
    $cells->setBackground('#0DF3FE');
});
$sheet->cells('A11:E11', function ($cells) {
    $cells->setBackground('#6D8947');
});
$sheet->cells('A12:E12', function ($cells) {
    $cells->setBackground('#0DF3FE');
});
$sheet->cells('A14:E14', function ($cells) {
    $cells->setBackground('#0DF3FE');
});
};

How can I do it dynamically by using conditions to set the background colors?



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/3s5GS5j
via IFTTT

Laravel: placing semicolon in query?

I am new to writing queries in Laravel and wondering what the convention for semi-colons are. Is it proper to leave them out until the last query like I have omitted them from the 2 $query down below or should they be after each one?:

NewProducts::with(['order', 'product', 'other.product'])
    ->whereHas(
        'saleItem',
        function ($query) use ($time) {
            $query->where('time', '=', $time)
            $query->where('value', '=', 'high')
        }
    )->get();


from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/3baSKMq
via IFTTT

Adding values of radio buttons to array

I'm trying to make student skip form and adding values to array, but there is "Undefined offset: 3" error. Here is the controller:

    public function skip(Request $request, $data = array())
    {
        $students = Student::where('group_id', 1)->get();
        $result=[];

        if ($request->has('submit')) {
            foreach($students as $student) {
               array_push($result, $data[$student->id]);
            }}
        return view ('skip', compact('students', 'result'));
    }
}

and view:

                        <form method="POST" action="">
                            @csrf
                            @foreach($students as $student)

                                <div class="radiobtns-group">

                                    <div class="btn-group btn-group-toggle" data-toggle="buttons">

                                        

                                        <label class="btn btn-success">

                                            <input type="radio" name="" value="1" autocomplete="off" checked>Yes
                                        </label>
                                        <label class="btn btn-danger">

                                            <input type="radio" name="" value="0" autocomplete="off">No
                                        </label>

                                    </div>
                                </div>
                        @endforeach
                    </div>




                    <button name='submit' type="submit" class="btn btn-primary">
                        Add
                    </button>

                    </form>
                    

                

i know, it needs to be done in js, but i don't know it yet. Maybe you can help or guide in other ways to solve it, thnx.



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/3qs8h0O
via IFTTT

Laravel 5 insert works without $fillable

i hope my question is not stupid, but i have a laravel application made by someone else.

In the controller i have this:

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Result;

class StoreInDB extends Controller
{
    function store($uuid, $session){
        // Insert data
        $r = new Result;
        if($r->updateOrInsert(['user_id' => $uuid], ['user_id' => $uuid, 'answers' => $session])){
            return true;
        }
        else{
            return false;
        }
    }
}

In the Model Result i have this:

namespace App;

use Illuminate\Database\Eloquent\Model;

class Result extends Model
{
    //
}

Why does it works ? There is no $fillable to tell wich column can be used to insert.

Datas are inserted. But why? The only issue i have is that created_at and updated_at are null.



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/3qlPRyC
via IFTTT

lundi 15 février 2021

Get data after start date laravel

I'm using the following query to get records that exist between start date and end date:

$event =Event::whereBetween('date', [
        $request->start_date, $request->end_date
    ])->orderBy('date', 'desc')->paginate(5);

This is working when I provide the start date and end date but, when I provide only the start date, then I didn't get any record – but I want records that exist after the start date if the end date is kept blank.

Any suggestions?



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/3qmF2MX
via IFTTT

customize excel export in laravel

In my Laravel backend project, I'm trying to customize the excel data while exporting it. I'm adding to add row colors in that excel.

Excel Sheet before customization

public function add_color_to_sheet($sheet) {
    $sheet->cells('A1:E1', function ($cells) {
        $cells->setBackground('#3490ED');
    });
    $sheet->cells('A2:E2', function ($cells) {
        $cells->setBackground('#6D8947');
    });
    $sheet->cells('A3:E3', function ($cells) {
        $cells->setBackground('#0DF3FE');
    });
    $sheet->cells('A8:E8', function ($cells) {
        $cells->setBackground('#0DF3FE');
    });
    $sheet->cells('A11:E11', function ($cells) {
        $cells->setBackground('#6D8947');
    });
    $sheet->cells('A12:E12', function ($cells) {
        $cells->setBackground('#0DF3FE');
    });
    $sheet->cells('A14:E14', function ($cells) {
        $cells->setBackground('#0DF3FE');
    });
  };

Excel Sheet After customization

I'm trying to put a background color for the rows that have only country name in the column, likewise with the state and cities too. Is there any way to customize dynamically using some conditions like if the column contains a country name, that country name rows only should be colored and likewise with the rest?



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/3rVz7i5
via IFTTT

dimanche 14 février 2021

model->id give last insert id of paricular user or it give last insert id considering all user

I want to know that in laravel last inserted id give last insert id of Database table of particular user who insert in database or last insert id of all user inserting in database.In other word I am explaning with example .Let suppose there is table payment_table having field payment_done_at ,so I am updating payment_table by below code

$paymentTableObject=payment_table::where('id',1)
                                ->first();
$paymentTableObject->payment_done_at= Carbon::now() 
                             ->toDateTimeString();
$paymentTableObject->save();

$lastInsertId=$paymentTableObject->id;

Now my question is $lastInsertId Will give last insert id saved in db by particular user or last insert id considering all user who saved data in db



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/3ddCVah
via IFTTT

Get model values with adding specific items in Laravel

I'm using Laravel as an API, but have some troubles with getting posts with the specific updated value.

Here is my code. Any help to fix the code regarding both syntax and inefficiencies?

use Controller;
use Post;
use User;
use Comment;

class HomeController extends Controller{
    public function index(){
        $posts = $this->getPosts('home');

        return view('template', ['posts' = $posts]);
    }

    public function getPosts($slug){
        $posts = Post::where('slug', '=', $slug)->get();

        foreach($posts as &$post){
            $post->user = User::find($post->user_id);
            $post->comments = Comment::where('post_id', '=', $post->post_id)->get();

            foreach($post->comments as &$comment){
                $comment->user = User::find($comment->user_id);
            }
        }

        return $posts;
    }
}

Model

<?php

namespace Latchel;

use Latchel\Model;

class Post extends Model
{

    protected $table = 'post';

    protected $primaryKey = 'post_id';

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'html', 'slug', 'user_id'
    ];
}


from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/2NsSX5c
via IFTTT

What is equivalent of *Laravel Model's Global Scope* in Python or Django?

In general when data is queried using App\Models in laravel, we have a luxury to apply filters using Model Level Global scope and Local Scope.

Is there any equivalent in "Python"? May be in "Django"? Or may be in models.Model ?



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/3de7mwX
via IFTTT

Return selective rows Laravel Eloquent

I want to filter product using their attributes using below query

return Product::with('attributes')
        ->whereHas('attributes', function ($query) use ($attribute_id_array,$attribute_value_array){
        for($k=0;$k<count($attribute_id_array);$k++)
        {
           $attr_id=$attribute_id_array[$k];
           $attr_val=$attribute_value_array[$k];

           $query->where(function($q) use ($attr_id, $attr_val) {
               $q->where('attribute_id', $attr_id)->where('value', $attr_val);
           });
        }
        })->paginate(10);

I want to check if attributes of a product exist then filter it using the loop to filter out products that are in attributes_value & attributes_id array which does not match but presently this query is not filtering through attributes.

Here are the structure of tables and relations

Product Table :

 |id  | Title     | Price|
 -------------------------
 |1   | Title 1   |  5000|
 |2   | Product 2 |  7000|

and the other is

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|

Product and Product attribute is related with following relation (In the product model):

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


from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/3ajvGMj
via IFTTT

samedi 13 février 2021

problem after upgrading laravel and php version

I was working on laravel 5.2.45 and PHP 7.1 without any problem, then I decided to upgrade to laravel 7 and php 7.4 the project which I working on is working but I have problems with some pages especially with the belongs to relation in laravel , I get this error

 [2021-02-13 15:32:00] local.ERROR: Trying to access array offset on value of type null {"exception":"[object] (ErrorException(code: 0): Trying to access array offset on value of type null at /var/www/html/easy/app/Http/Controllers/SubscriberController.php:431)
[stacktrace]
#0 /var/www/html/easy/app/Http/Controllers/SubscriberController.php(431): Illuminate\\Foundation\\Bootstrap\\HandleExceptions->handleError()
#1 [internal function]: App\\Http\\Controllers\\SubscriberController->userFilterData()
#2 /var/www/html/easy/vendor/laravel/framework/src/Illuminate/Routing/Controller.php(54): call_user_func_array()
#3 /var/www/html/easy/vendor/laravel/framework/src/Illuminate/Routing/ControllerDispatcher.php(45): Illuminate\\Routing\\Controller->callAction()
#4 /var/www/html/easy/vendor/laravel/framework/src/Illuminate/Routing/Route.php(240): Illuminate\\Routing\\ControllerDispatcher->dispatch()
#5 /var/www/html/easy/vendor/laravel/framework/src/Illuminate/Routing/Route.php(197): Illuminate\\Routing\\Route->runController()
#6 /var/www/html/easy/vendor/laravel/framework/src/Illuminate/Routing/Router.php(681): Illuminate\\Routing\\Route->run()
#7 /var/www/html/easy/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(128): Illuminate\\Routing\\Router->Illuminate\\Routing\\{closure}()
#8 /var/www/html/easy/app/Http/Middleware/Permissions.php(49): Illuminate\\Pipeline\\Pipeline->Illuminate\\Pipeline\\{closure}()
#9 /var/www/html/easy/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(167): App\\Http\\Middleware\\Permissions->handle()
#10 /var/www/html/easy/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/VerifyCsrfToken.php(76): Illuminate\\Pipeline\\Pipeline->Illuminate\\Pipeline\\{closure}()
#11 /var/www/html/easy/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(167): Illuminate\\Foundation\\Http\\Middleware\\VerifyCsrfToken->handle()
#12 /var/www/html/easy/vendor/laravel/framework/src/Illuminate/View/Middleware/ShareErrorsFromSession.php(49): Illuminate\\Pipeline\\Pipeline->Illuminate\\Pipeline\\{closure}()
#13 /var/www/html/easy/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(167): Illuminate\\View\\Middleware\\ShareErrorsFromSession->handle()
#14 /var/www/html/easy/vendor/laravel/framework/src/Illuminate/Session/Middleware/StartSession.php(56): Illuminate\\Pipeline\\Pipeline->Illuminate\\Pipeline\\{closure}()
#15 /var/www/html/easy/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(167): Illuminate\\Session\\Middleware\\StartSession->handle()
#16 /var/www/html/easy/vendor/laravel/framework/src/Illuminate/Cookie/Middleware/AddQueuedCookiesToResponse.php(37): Illuminate\\Pipeline\\Pipeline->Illuminate\\Pipeline\\{closure}()
#17 /var/www/html/easy/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(167): Illuminate\\Cookie\\Middleware\\AddQueuedCookiesToResponse->handle()
#18 /var/www/html/easy/vendor/laravel/framework/src/Illuminate/Cookie/Middleware/EncryptCookies.php(66): Illuminate\\Pipeline\\Pipeline->Illuminate\\Pipeline\\{closure}()
#19 /var/www/html/easy/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(167): Illuminate\\Cookie\\Middleware\\EncryptCookies->handle()
#20 /var/www/html/easy/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(103): Illuminate\\Pipeline\\Pipeline->Illuminate\\Pipeline\\{closure}()
#21 /var/www/html/easy/vendor/laravel/framework/src/Illuminate/Routing/Router.php(683): Illuminate\\Pipeline\\Pipeline->then()
#22 /var/www/html/easy/vendor/laravel/framework/src/Illuminate/Routing/Router.php(658): Illuminate\\Routing\\Router->runRouteWithinStack()
#23 /var/www/html/easy/vendor/laravel/framework/src/Illuminate/Routing/Router.php(624): Illuminate\\Routing\\Router->runRoute()
#24 /var/www/html/easy/vendor/laravel/framework/src/Illuminate/Routing/Router.php(613): Illuminate\\Routing\\Router->dispatchToRoute()
#25 /var/www/html/easy/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php(165): Illuminate\\Routing\\Router->dispatch()
#26 /var/www/html/easy/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(128): Illuminate\\Foundation\\Http\\Kernel->Illuminate\\Foundation\\Http\\{closure}()
#27 /var/www/html/easy/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/CheckForMaintenanceMode.php(63): Illuminate\\Pipeline\\Pipeline->Illuminate\\Pipeline\\{closure}()
#28 /var/www/html/easy/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(167): Illuminate\\Foundation\\Http\\Middleware\\CheckForMaintenanceMode->handle()
#29 /var/www/html/easy/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(103): Illuminate\\Pipeline\\Pipeline->Illuminate\\Pipeline\\{closure}()
#30 /var/www/html/easy/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php(140): Illuminate\\Pipeline\\Pipeline->then()
#31 /var/www/html/easy/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php(109): Illuminate\\Foundation\\Http\\Kernel->sendRequestThroughRouter()
#32 /var/www/html/easy/public/index.php(55): Illuminate\\Foundation\\Http\\Kernel->handle()
#33 {main}
"} 

this is the Model that I have

<?php

namespace App\Model;

use Illuminate\Database\Eloquent\Model;

class Subscriber extends Model
{
    protected $table = 'reign_users';

    public $timestamps = false;

    /*public function profile()
    {
        return $this->belongsTo('App\Model\Profile', 'owner');
    }*/
    public function profiles()
    {
        return $this->hasOne('App\Model\Profile', 'id', 'srvid');
    }

    public function owners()
    {
        return $this->hasOne('App\Model\AclManager', 'id', 'owner');
    }
    
    public function radAcctData() {
        return $this->hasOne('App\Model\RadAcct', 'username', 'username');
    }
    
    public function usermac() {
        return $this->hasOne('App\Model\UserMAC', 'username', 'username');
    }
    
    public function onlineData() {
        return $this->hasOne('App\Model\OnlineUser', 'username', 'username');
    }

    public function userInvoice(){
        return $this->hasOne('App\Model\UserInvoice', 'username', 'username')->latest();
    }

    public function userNetwork(){
        return $this->hasOne('App\Model\Networks', 'id', 'networkid');
    }

    public function thanaName(){
        return $this->hasOne('App\Model\Thana', 'id', 'thana');
    }


}

and this is my code in controller code

  public function userFilterData(Request $request) {


        $user = Subscriber::with( 'userInvoice', 'usermac', 'userNetwork');

//        $user = Subscriber::leftJoin('radacct as r', function ($join) use($request) {
//                    $join->on('r.username', '=', 'reign_users.username');
//                    $join->on("r.acctstoptime", "IS", DB::raw("NULL"));
//                })
//                        ->with('userInvoice', 'usermac', 'userNetwork');

        /* only manager cannot see the deleted user */
        if (Session::get('type') == "Manager" && Session::get('admin_assistant') == 0) {
            $user->where('reign_users.owner', Session::get('id'));
        }

//date filter conditionn
        if (isset($request->dateFlag)) {
            $today = date("Y-m-d");
            if ($request->dateFlag == 1) {
                $user->where(DB::raw("date_format(reign_users.createdon, '%Y-%m-%d')"), $today);
            } elseif ($request->dateFlag == 2) {
                $weekStart = date('Y-m-d', strtotime('-6 days'));
                $user->whereRaw("date_format(reign_users.createdon, '%Y-%m-%d') BETWEEN '$weekStart' AND '$today'");
            } elseif ($request->dateFlag == 3) {
                $monthStart = date('Y-m-d', strtotime('first day of this month'));
                $user->whereRaw("date_format(reign_users.createdon, '%Y-%m-%d') BETWEEN '$monthStart' AND '$today'");
            } elseif ($request->dateFlag == 4) {
                $range = explode('-', $request->dateRange);
                $startDate = date('Y-m-d', strtotime($range[0]));
                $endDate = date('Y-m-d', strtotime($range[1]));
                $user->whereRaw("date_format(reign_users.createdon, '%Y-%m-%d') BETWEEN '$startDate' AND '$endDate'");
            } else {

            }
        }


//filter by user's status like active,online,expired
        if (isset($request->userStatus) && $request->userStatusVal != "") {
            $today = date("Y-m-d H:i:s");
            if ($request->userStatusVal == 1) {
                $user->whereRaw("reign_users.expiration <= '$today'");
            }
            if ($request->userStatusVal == 2) {
                $user->whereRaw("reign_users.expiration >= '$today'");
            }
            if ($request->userStatusVal == 3) {
                $threeDaysAfter = date("Y-m-d", strtotime("+3 days"));
                $dateToday = date("Y-m-d");
                $user->whereRaw("date_format(reign_users.expiration, '%Y-%m-%d') BETWEEN '$dateToday' AND '$threeDaysAfter'");
            }
            if ($request->userStatusVal == 4) {
                $user->whereRaw("reign_users.enableuser = 1");
            }
            if ($request->userStatusVal == 5) {
                $user->whereRaw("reign_users.enableuser = 0");
            }
        }

        if (isset($request->createdBy) && $request->createdByVal != "") {
            $user->whereRaw("reign_users.createdby = $request->createdByVal");
        }

        if (isset($request->profile) && $request->profileVal != "") {
            $user->whereRaw("reign_users.srvid = $request->profileVal");
        }

        if (isset($request->manager) && $request->managerVal != "") {
            $user->whereRaw("reign_users.owner = $request->managerVal");
        }

        if (isset($request->network) && $request->networkVal != "") {
            $user->whereRaw("reign_users.networkid = $request->networkVal");
        }

        if (($request->order[0]['column'] == 0) && isset($request->order[0]['dir'])) {
            $order = $request->order[0]['dir'];
            $user->orderBy("reign_users.username", $order);
        }

        if (($request->order[0]['column'] == 4) && isset($request->order[0]['dir'])) {
            $order = $request->order[0]['dir'];
            $user->orderBy("reign_users.expiration", $order);
        }

        if (($request->order[0]['column'] == 5) && isset($request->order[0]['dir'])) {
            $order = $request->order[0]['dir'];
            $user->orderBy("reign_users.extended_expiration", $order);
        }
        if (($request->order[0]['column'] == 6) && isset($request->order[0]['dir'])) {
            $order = $request->order[0]['dir'];
            $user->orderBy("reign_users.owner", $order);
        }

        /* string search */
        $searchStr = $request->search['value'];
        if ($searchStr != "") {
            $user->whereRaw("(reign_users.username like '%$searchStr%' OR reign_users.firstname like '%$searchStr%' OR reign_users.lastname like '%$searchStr%' OR reign_users.mobile like '%$searchStr%' OR reign_users.mac like '%$searchStr%')");
        }

        $user->where('reign_users.status', '!=', 3);


        $data['recordsTotal'] = $user->count();
        $data['recordsFiltered'] = $user->count();

        $user->limit($request->length)->offset($request->start);
        $userData = $user->get();

//        return $userData[1]->onlineData->status;
//        $expiredDate = $userData[1]->expiration;
//        $currentDate = date('Y-m-d');
//        $expiredInThreeDays = date('Y-m-d', strtotime('-3 days', strtotime($expiredDate)));
////        return $expiredInThreeDays;
//        if ($expiredInThreeDays >= $currentDate) {
//            return $expiredDate;
//        }else{
//            return $currentDate;
//        }

        $data['draw'] = $request->draw;


        $data['data'] = array();
        $sl = 0;
        foreach ($userData as $k => $val) {
            $isNewUser = 0;

            /* only new User don't have any invoice and monthly package user */
            if ($val->userInvoice == null && $val->profiles['timebaseexp'] == 1) {
                $isNewUser = 1;

                if ($val->user_type == 2) {
                    $profileMonthStartDay = $val->custom_month_start_day;
                    $userCurrentExpiration = date($val->expiration);

                    $countMonth = 1;
                    //$newDate = strtotime('+' . $countMonth . ' month', strtotime($userCurrentExpiration));
                    $newDate = strtotime('last day of next month', strtotime($userCurrentExpiration));
                    $nextMonthYear = date('Y-m', $newDate);

                    $settingData = SoftwareSetting::select('value')->where('attribute', 'gnrl_expiration_time')->first();
                    $time = $settingData->value;

                    $activationDate = date('Y-m-d H:i:s', strtotime($nextMonthYear . '-' . $profileMonthStartDay . ' ' . $time));
                } else {
                    /* if user have custom month start day, profile month start is ignored */
                    if ($val->custom_month_start_day != null) {
                        $profileMonthStartDay = $val->custom_month_start_day;
                    } else {
                        $profileMonthStartDay = $val->profiles['month_start_day'];
                    }

                    $profileUnitMonth = $val->profiles['timeunitexp'];
                    $userCurrentExpiration = date($val->expiration);


                    //$newDate = strtotime('+' . $countMonth . ' month', strtotime($userCurrentExpiration));
                    $newDate = strtotime('last day of next month', strtotime($userCurrentExpiration));
                    $nextMonthYear = date('Y-m', $newDate);


                    $settingData = SoftwareSetting::select('value')->where('attribute', 'gnrl_expiration_time')->first();
                    $time = $settingData->value;

                    $activationDate = date('Y-m-d H:i:s', strtotime($nextMonthYear . '-' . $profileMonthStartDay . ' ' . $time));
                }

                $createdDate = $val->createdon;
                $newExpirationDate = date('Y-m-d', strtotime($activationDate));

                $activatedDayCount = date_diff(date_create($createdDate), date_create($newExpirationDate));

                $dayCountNewUser = $activatedDayCount->format("%a");
            }

            $expiredDate = $val->expiration;
            $currentDate = date('Y-m-d');
            $expiredInThreeDays = date('Y-m-d', strtotime('-3 days', strtotime($expiredDate)));
            $userActive = $val->enableuser;
            if ($currentDate > $expiredDate && $userActive == 0) {
                $color = 'gray';
            } elseif ($currentDate > $expiredDate && $userActive == 1) {
                $color = 'red';
            } elseif ($expiredInThreeDays <= $currentDate) {
                $color = 'orange';
            } elseif ($userActive == 0) {
                $color = 'gray';
            } elseif ($userActive == 1) {
                $color = 'blue';
            } else {
                $color = 'black';
            }

            $data['data'][$sl]['user_name'] = "<a class='userShow'  data-toggle='modal'
                                               data-target='#userDetails' href='$val->id'><strong style='color:" . $color . "'>" . $val->username .
                    "</strong></a><br><small class='text-info'>Added: " . date('d,M Y', strtotime($val->createdon)) . "</small>";



            $data['data'][$sl]['full_name'] = $val->firstname . ' ' . $val->lastname .
                    "<br> <small class='text-info'>Phone: " . $val->mobile . "</small>";


            $data['data'][$sl]['profile'] = ($val->user_type == 2) ? $val->ip : $val->profiles['srvname'] . "<br><small class='text-danger'>" .$val->usermac['mac'].
  "</small>";

            if ($val->isNOC == 1) {
                $networkBox = 'NOC';
            } else {
                $networkBox = 0;//$val->userNetwork['name'];
            }
            $data['data'][$sl]['networkBox'] = $networkBox;

            $data['data'][$sl]['billing_date'] = date('d,M Y H:i:s', strtotime($val->expiration));
//            $data['data'][$sl]['billing_date'] = date('d,M Y H:i:s', strtotime($val->expiration)) .
//                    "<br><small class='text-danger'>Last Online: " .
//                    date("d,M Y, H:i", strtotime($val->lastonline)) . "</small>";

            $data['data'][$sl]['expiration'] = "<small>" . date('d,M Y H:i:s', strtotime($val->extended_expiration)) . "</small>";

            $data['data'][$sl]['owner'] = $val->owners['full_name'] == "" ? "Admin" : $val->owners['full_name'];


            $costAmount = 0;
            if ($val->owners['id'] > 0) {
                $profile = AclManagerProfiles::select('cost_amount')->where(array(
                            'manager_id' => $val->owners['id'],
                            'profile_id' => $val->profiles['id'],
                        ))->first();
                $costAmount = isset($profile->cost_amount) ? $profile->cost_amount : 0;
            }

            if ($isNewUser == 1) {
                $unitPrice = round(($dayCountNewUser / 30) * $val->profiles['unitprice']);
                //$data['data'][$sl]['commission'] = $costAmount > 0 ? ($unitPrice - round(($dayCountNewUser / 30) * $costAmount)) : 0;
            } else {
                $unitPrice = $val->profiles['unitprice'];
                //$data['data'][$sl]['commission'] = $costAmount > 0 ? ($unitPrice - $costAmount) : 0;
            }

            $data['data'][$sl]['monthly_bill'] = $unitPrice + $val->additional_cost - $val->discount;


            $data['data'][$sl]['activation'] = "<a class='userActive badge badge-info' data-toggle='modal'
                                               data-target='#expirationExpand' price='$unitPrice' username='$val->username' href='$val->id'>
                                                Pay Bill
                                            </a>";
            if (Session::get('admin_assistant') == 1 && $val->owner > 0) {
                $data['data'][$sl]['activation'] = "";
            }

            $editUrl = URL::to('subscriber' . '/' . $val->id);

            if ($val->status == 0) {
                $data['data'][$sl]['action'] = "<a href='$editUrl' action='GET'>
                                                <i class='icon-pencil text-info'></i>
                                                </a>
                                                 |
                                                <a href='$editUrl' data-method='delete'
                                                data-confirm='Are you sure?  User will be delete.'>
                                                <i class='icon-trash text-danger'></i>
                                                </a>";
            } else {
                $data['data'][$sl]['action'] = "<a href='$editUrl' data-method='delete'
                                                    data-confirm='Are you sure? Do you want to restore this User?'>
                                                <i class='icon-reload text-danger'></i>
                                                </a>";
            }

            $sl++;
        }

        echo json_encode($data);
        die();
    }

this is the manager model

class AclManager extends Model
{

    protected $table = 'reign_acl_managers';
    public $timestamps = false;

    public function parent()
    {
        return $this->hasOne('App\Model\AclManager', 'id', 'parent_id');
    }

    public function manager()
    {
        return $this->hasOne('App\Model\AclGroup', 'id', 'group_id');
    }

}

I have 2 tables, one is for super admin and the other one is for manager, I am trying to get the subscribed users and the manager that they belong to, some of the users belong to super admin who is not found in manager table, so the owner of them in the table will be 0, so when I am trying to get the owner details I get

Trying to access array offset on the value of type null

in this line

 $data['data'][$sl]['owner'] = $val->owners['full_name'] == "" ? "Admin" : $val->owners['full_name']; 

the problem is same code working fine on an old version of laravel , but not in this new version. I think the problem is with the relationship in the model, but I don't know how to solve it.



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/3phGkY6
via IFTTT

Adding Background Image to Email Template in Laravel

I am trying to add background image to an email template

I don't want to use

What I have tried till now is ,Inside style

background: url(/images/emails/template/layer_1.png);

Also I tried adding url directly

background: url(http:://biz.test/images/emails/template/layer_1.png);

By passing URL value in variable

background: url({!! $logo !!})

Please advice , How can I make this work, I am using Laravel



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/3b5Jrxh
via IFTTT

Remove Special Character from String in PHP for mutli languages?

I am using localization and want to change in Arabic special characters here is my code,

 function helper_get_unique_slug($slug)
    {
        if (!empty($slug)) {
             
            $slug = str_replace(" ", "_", $slug);
            $slug=preg_replace('/[^A-Za-z0-9\-]/', '', $slug);
    ````}
    }


from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/379rc95
via IFTTT

vendredi 12 février 2021

timetable or lesson schedule in laravel

I am making a lesson schedule for students from the Schedule table:

id

group_id

teacher_id

time_id

weekday_id

chet_id

So, I need to display the schedule, and where there are no lessons, a link is displayed to add a schedule for that day and time. But, unfortunately, I can't display the schedule correctly. It turns out like this: enter image description here

Chet_id is responsible for the frequency of lessons (for example, chet_id = 1-lessons are held on even weeks, 2-odd weeks, 3-every week)

Here part of controller:

    public function showschedulestud(){
$weekdays=Weekday::all();
$chets=Chet::all();
                $group_id=Auth::user()->student->group_id;
            $schedule=Schedule::where('group_id', $group_id)->get();
            return view('schedule.showschedule', compact('schedule', 'weekdays', 'chets'));
        }

And view:

<table class="table table-dark">
     <tr>
        <th scope="col">#</th>
         @foreach($weekdays as $weekday)

        <th scope="col"></th>
             @endforeach
    </tr>
@foreach($times as $time)
        @foreach($chets as $chet)
    <tr>
        <th scope="row">-</th>
        <th scope="row"></th>
        @foreach($schedule as $sched)
            @if($sched->weekday_id=$weekday->id && $sched->time_id=$time->id && $sched->chet=$chet->id)
        <td></td>
            @else
                <td>/createschedule//</td>
            @endif
            @endforeach
            </tr>
            @endforeach
    @endforeach
       </table>

I would be grateful if you can help me somehow solve a problem that has been tormenting me for a long time.



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/3b2RpXJ
via IFTTT