mstdmstd

mstdmstd

Member Since 3 Years Ago

Experience Points
16,230
Total
Experience

3,770 experience to go until the next level!

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

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

    Start Your Engines

    Earned once you have completed your first Laracasts lesson.

  • first-thousand Created with Sketch.

    First Thousand

    Earned once you have earned your first 1000 experience points.

  • 1-year Created with Sketch.

    One Year Member

    Earned when you have been with Laracasts for 1 year.

  • 2-years Created with Sketch.

    Two Year Member

    Earned when you have been with Laracasts for 2 years.

  • 3-years Created with Sketch.

    Three Year Member

    Earned when you have been with Laracasts for 3 years.

  • 4-years Created with Sketch.

    Four Year Member

    Earned when you have been with Laracasts for 4 years.

  • 5-years Created with Sketch.

    Five Year Member

    Earned when you have been with Laracasts for 5 years.

  • school-in-session Created with Sketch.

    School In Session

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

  • welcome-newcomer Created with Sketch.

    Welcome To The Community

    Earned after your first post on the Laracasts forum.

  • full-time-student Created with Sketch.

    Full Time Learner

    Earned once 100 Laracasts lessons have been completed.

  • pay-it-forward Created with Sketch.

    Pay It Forward

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

  • subscriber Created with Sketch.

    Subscriber

    Earned if you are a paying Laracasts subscriber.

  • lifer Created with Sketch.

    Lifer

    Earned if you have a lifetime subscription to Laracasts.

  • evangelist Created with Sketch.

    Laracasts Evangelist

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

  • chatty-cathy Created with Sketch.

    Chatty Cathy

    Earned once you have achieved 500 forum replies.

  • lara-veteran Created with Sketch.

    Laracasts Veteran

    Earned once your experience points passes 100,000.

  • 10k-strong Created with Sketch.

    Ten Thousand Strong

    Earned once your experience points hits 10,000.

  • lara-master Created with Sketch.

    Laracasts Master

    Earned once 1000 Laracasts lessons have been completed.

  • laracasts-tutor Created with Sketch.

    Laracasts Tutor

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

  • laracasts-sensei Created with Sketch.

    Laracasts Sensei

    Earned once your experience points passes 1 million.

  • top-50 Created with Sketch.

    Top 50

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

Level 4
16,230 XP
May
25
5 days ago
Activity icon

Replied to I Got 401 Error In Undelete Method Of Vue Request?

Trying yo debug this issue I use clone function for creating of credentials var, which I use in request.

        getClone: function (obj) {
            let copy = JSON.parse(JSON.stringify(obj))
            return copy
        },

also I added 2 varaibles to which authorization_1 and authorization_2 ro which I assign

                let credentials= this.getClone(this.credentialsConfig)
                credentials.headers.Authorization = 'Bearer ' + this.currentLoggedUserToken
                this.authorization_1= credentials.headers.Authorization
                console.log('removeTask credentials::')
                console.log(credentials)
                axios.delete(this.apiUrl + '/adminarea/tasks/' + id, credentials).then((/*response*/) => {

and

                let credentials= this.getClone(this.credentialsConfig)
                credentials.headers.Authorization = 'Bearer ' + this.currentLoggedUserToken
                this.authorization_2= credentials.headers.Authorization
                console.log('unremoveTask credentials::')
                console.log(credentials)
                axios.put(this.apiUrl + '/adminarea/tasks/' + id+"/unremove", credentials).then((/*response*/) => {

and outputing these authorization_1 and authorization_2 vars on the page I can compare their content and see that they have the same value like

‘Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwOi8vbG9jYWwtY3Rhc2tzLWFwaS5jb20vYXBpL2xvZ2luIiwiaWF0IjoxNTkwNDE3NzcxLCJleHAiOjE1OTA0MjEzNzEsIm5iZiI6MTU5MDQxNzc3MSwianRpIjoiSHRjQmNPbUQwbjhKVHlqbyIsInN1YiI6MSwicHJ2IjoiODdlMGFmMWVmOWZkMTU4MTJmZGVjOTcxNTNhMTRlMGIwNDc1NDZhYSJ9.A3lZqX2hEaYGYuBoh9rDzjcyg4jEVkBXANRhAiUyZ0c’

I just wanted to check that with assigning credentials.headers.Authorization was not cut/modified anyway...

I tried to modify routes/api.php that unremove method must be BEFORE resource, like:

Route::put('tasks/{id}/unremove', 'API\Admin\[email protected]_task'); 
Route::resource('tasks', 'API\Admin\TaskController'); ?

That did not help. I got the same 401 error.

Any ideas why error ?

May
24
6 days ago
Activity icon

Started a new Conversation I Got 401 Error In Undelete Method Of Vue Request?

Hello, I make @vue/cli 4.0.5 app with reading data from Laravel 7 Backend REST API and and with softly deletion functionality in frontend part I have 2 methods 1) delete row 2) undelete row Making similar implementation for both cases I got 401 error in 2) case and I can not find why.

  1. Deleting row(works ok):
            removeTask(id, task_name, soft_deletion/*, index*/) {
                console.log('removeTask soft_deletion::')
                console.log(soft_deletion)

                let confirm_message= "Do you want to delete permanently " + " '" + task_name + "' task ? It can not be restored !"
                if (soft_deletion) {
                    confirm_message= "Do you want to mark for deletion " + " '" + task_name +
                        "' task ? It would be unavailable in the app, but can be restored(undeleted) OR deleted permanently !"
                }

                if (!confirm(confirm_message)) {
                    return
                }

                let credentials= this.credentialsConfig
                credentials.headers.Authorization = 'Bearer ' + this.currentLoggedUserToken
                console.log('removeTask credentials::')
                console.log(credentials)

                axios.delete(this.apiUrl + '/adminarea/tasks/' + id, credentials).then((/*response*/) => {
                    this.loadTasks()
                    this.showPopupMessage('Tasks Editor', 'Task was '+(soft_deletion ? "softly" : "permanently")+' deleted successfully !'+( soft_deletion ?
                        "But you can restore it or delete permanently" : "" ), 'success')
                }).catch((error) => {
                    console.error(error)
                    this.showPopupMessage('Tasks Editor', 'Error deleting task : ' + error.response.data.message, 'error')
                })

            }, //removeTask(id, task_name, soft_deletion, index) {

and I see in console: https://imgur.com/a/e1vruhv

  1. Undeleting row (raise 401 error)
            unremoveTask(id, task_name/*, index*/) {
                console.log('unremoveTask id::')
                console.log(id)

                if (!confirm("Do you want to restore(undelete) " + " '" + task_name + "' task ?")) {
                    return
                }

                let credentials= this.credentialsConfig
                credentials.headers.Authorization = 'Bearer ' + this.currentLoggedUserToken

                console.log('unremoveTask credentials::')
                console.log(credentials)

                axios.put(this.apiUrl + '/adminarea/tasks/' + id+"/unremove", credentials).then((/*response*/) => {
                    this.loadTasks()
                    this.showPopupMessage('Tasks Editor', 'Task was deleted successfully', 'success')
                }).catch((error) => {
                    console.error(error)
                    this.showPopupMessage('Tasks Editor', 'Error deleting task !', 'error')
                })

            }, //unremoveTask(id, task_name, index) {

and I see in console L https://imgur.com/a/YJ5DKWM

I do not understand why error in 2)? credentialsConfig if in settings file src/app.settings.js :

export const settingCredentialsConfig = {
    withCredentials:true,
    headers: {
        'Content-Type': 'application/json',
        'Access-Control-Allow-Origin': '*',
        'Access-Control-Allow-Credentials':true
    }
}

and in my vue file :

<script>
    import {settingCredentialsConfig} from '@/app.settings.js'
    ...


data() {
    return {
    credentialsConfig: settingCredentialsConfig,
    ...

any time I got copy of credentialsConfig var and add token to it. In the console I see valid token headers.Authorization.

In /routes/api.php of my latavel app I have defined :

Route::group(['middleware' => 'jwt.auth',  'prefix' => 'adminarea', 'as' => 'adminarea.'], function ($router) {
    Route::resource('tasks', 'API\Admin\TaskController');
    Route::group([ 'prefix' => 'tasks'], function ($router) {
        Route::put('/{id}/unremove', 'API\Admin\[email protected]_task');

In case of incalid undelete url I got 404 error...

Why error and how it can be fixed?

Thanks!

May
22
1 week ago
Activity icon

Replied to How In Laravel 7 Notifications To Use Multiple Mail Driver?

This article 5 years ago. Seems format of config/mail.php has been changed from that time ? Or is this article is still valid could you please to point at issue ?

Activity icon

Started a new Conversation How In Laravel 7 Notifications To Use Multiple Mail Driver?

Hello, In laravel 7 app I use notifications for email sending, like:

    $newUser->notify(new SignupActivate($newUser, $site_name, $app_url));

Where app/Notifications/SignupActivate.php has :

<?php

namespace App\Notifications;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notification;

class SignupActivate extends Notification
{
    use Queueable;

    private $registeredUser;
    private $site_name;
    private $app_url;
    public function __construct($registeredUser, $site_name, $app_url)
    {
        $this->registeredUser= $registeredUser;
        $this->site_name= $site_name;
        $this->app_url= $app_url;
    }

    public function via($notifiable)
    {
        return ['mail'];
    }

    public function toMail($notifiable)
    {
        ...

And with mail returned in via method. I search a way to use Multiple Mail Driver in this Notification

as is written on the link : https://laravel.com/docs/7.x/notifications#customizing-the-mailer


public function toMail($notifiable)
{
    return (new MailMessage)
                ->mailer('postmark')
                ->line('...');

But it does not work for me.

On config/mail.php I set 2 mailers :

<?php

return [


    'default' => env('MAIL_MAILER', 'sendgrid'),


    'mailers' => [
        'mailtrap' => [
           ...
        ],

        'sendgrid' => [
           ...
        ],

        
    ],
   ...

They both work ok if to change value in 'default'

But making in app/Notifications/SignupActivate.php :

<?php

namespace App\Notifications;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notification;

class SignupActivate extends Notification
{
    use Queueable;

    private $registeredUser;
    private $site_name;
    private $app_url;
    public function __construct($registeredUser, $site_name, $app_url)
    {
        $this->registeredUser= $registeredUser;
        $this->site_name= $site_name;
        $this->app_url= $app_url;
    }

    public function via($notifiable)
    {
        return ['mail'];
    }

    public function toMail($notifiable)
    {

        return (new MailMessage)
            ->mailer('mailtrap') // ‘sendgrid’ does not work, 
            // if to enter some invalid value - it does not raise error - just ignored
            ->subject('Registration at ' . $this->site_name)
            ->line('Thanks for signup at '.$this->site_name.'!')
            ->line('To use our site, you must confirm your account at first.')
            ->action('Follow to Confirm Account', $url)
            ->line('Thank you for using our '.$this->site_name.' site !');
    }

    public function toArray($notifiable)
    {
        return [
            //
        ];
    }
}

What is wrong ? Seems I did like in docs...

Laravel Framework 7.11.0

Thanks!

May
20
1 week ago
Activity icon

Started a new Conversation Why Complicated Scope With Subquery Does Not Work

Hello,

In my Laravel 5.7/ mysql app I make request on a storage_spaces table, which has client_id field(can be empty) which is reference to clients table. Any client can has several emails and there is client_additive_emails table with fields client_id and email I need by $search value with email entered (like 'hgedsaemail3.com' value) get all storage_spaces whose clients has entered emails in client_additive_emails. I have a complcated request where $filter_search is one of the parameters and it fails to find valid rows by entered email:

        $storageSpacesCollection = StorageSpace
            ::getByStatus($filter_status)
            ->whereRaw('storage_spaces.id <= 8') // DEBUGGING
            ->getById($relatedStorageSpacesArray)
            ->getByLocationId($filter_location_id, 'warehouses')
            ->getByCapacityCategoryId($filter_capacity_category_id, 'storage_capacities')
            ->getByLevel($filter_level)
            ->getByNumber($filter_number, true)
            ->orderBy('storage_spaces.id', 'asc')
            ->getByStorageCapacityId($filter_storage_capacity_id)
            ->getByClientId($filter_client_id)
            ->getByColorId($filter_color_id)
            ->getBySearch($filter_search) // THAT IS COMPLICATED SCOPE

            ->leftJoin( 'storage_capacities', 'storage_capacities.id', '=', 'storage_spaces.storage_capacity_id' )
            ->leftJoin( 'warehouses', 'warehouses.id', '=', 'storage_spaces.warehouse_id' )
            ->leftJoin( 'clients', 'clients.id', '=', 'storage_spaces.client_id')

            ->select(
                "storage_spaces.*",
                \DB::raw( "CONCAT(storage_capacities.count, ' ', storage_capacities.sqft ) as storage_capacity_name" ),
                \DB::raw("( SELECT check_ins.job_ref_no FROM check_ins WHERE check_ins.storage_space_id=storage_spaces.id ORDER BY check_ins.id DESC limit 1 ) AS job_ref_no"),
                "warehouses.name as warehouse_name",
                "clients.id as client_id",
                \DB::raw( "CONCAT( clients.id, ' ', clients.full_name ) as client_full_name" ) )
            ->get();
search is impemented in scope with subquesry on emails search :
    public function scopeGetBySearch($query, $search = null)
    {
        if (empty($search)) {
            return $query;
        }
        $search_is_is_valid_float = with(new StorageSpace)->isValidFloat($search);

        $tb= with(new StorageSpace)->getTable();
        return $query->where(
            $tb.'.number',  $search
        ) ->orWhere(function ($query) use ($search, $tb, $search_is_is_valid_float) {
            $query->where( $tb.".notes",  'like',  '%'.$search.'%' )
                ->orWhere("clients.full_name", $search)
                ->orWhereRaw("(SELECT check_ins.job_ref_no FROM check_ins WHERE check_ins.storage_space_id=storage_spaces.id ORDER BY check_ins.id ASC LIMIT 1) = '".$search."'");

            if($search_is_is_valid_float) {
                $query->orWhere("storage_capacities.count", $search);
                $query->orWhere($tb . ".selling_range", $search);
                $query->orWhere($tb . ".actual_storage_rent", $search);
                $query->orWhere($tb . ".insurance_vat", $search);
            } // if($search_is_is_valid_float) {


            // THAT SUBQUERY DOES NOT WORK:
            $query->orWhereIn('storage_spaces.client_id', function($query) use ($search){
                $query->select('client_additive_emails.client_id')
                      ->from("client_additive_emails")
                      ->where('client_additive_emails.client_id', "clients.id")
                      ->where('client_additive_emails.email', $search);
            });

and in sql-trace I see :

   SELECT `storage_spaces`.*, CONCAT(storage_capacities.count, ' ', storage_capacities.sqft )     AS storage_capacity_name, (   SELECT check_ins.job_ref_no 
    FROM check_ins 
    WHERE check_ins.storage_space_id=storage_spaces.id 
    ORDER BY check_ins.id DESC limit 1 )     AS job_ref_no, `warehouses`.`name`     AS `warehouse_name`, `clients`.`id`     AS `client_id`, CONCAT( clients.id, ' ', clients.full_name )     AS client_full_name 
    FROM `storage_spaces` 
    LEFT JOIN `storage_capacities` on `storage_capacities`.`id` = `storage_spaces`.`storage_capacity_id` 
    LEFT JOIN `warehouses` on `warehouses`.`id` = `storage_spaces`.`warehouse_id` 
    LEFT JOIN `clients` on `clients`.`id` = `storage_spaces`.`client_id` 
    WHERE storage_spaces.id <= 8     AND (`storage_spaces`.`number` = 'hgedsaemail3.com'     OR (`storage_spaces`.`notes` like '%hgedsaemail3.com%'     OR `clients`.`full_name` = 'hgedsaemail3.com'     OR (  SELECT check_ins.job_ref_no 
    FROM check_ins 
    WHERE check_ins.storage_space_id=storage_spaces.id 
    ORDER BY check_ins.id ASC LIMIT 1) = 'hgedsaemail3.com'     OR `storage_spaces`.`client_id` in (  SELECT `client_additive_emails`.`client_id` 
    FROM `client_additive_emails` 
    WHERE `client_additive_emails`.`client_id` = 'clients.id'     AND `client_additive_emails`.`email` = 'hgedsaemail3.com'))) 
    ORDER BY `storage_spaces`.`id` asc 

I try to debug the subquery with client id = 1885(if to run sql above without $search value entered then storage_spaces with client_id= 1885 is returned)

select *
 FROM `client_additive_emails` 
    WHERE `client_additive_emails`.`client_id` = 1885    AND 
`client_additive_emails`.`email` = 'hgedsaemail3.com'

It returns 1 rows as I expected

But I do not see why my request does not work ?

Thanks!

May
19
1 week ago
Activity icon

Awarded Best Reply on How To Make Laravel Eloquent Request With 1 Filter On Many Fields

I found a decision addin in scope :

    ->orWhereRaw("(SELECT check_ins.job_ref_no FROM check_ins WHERE
       check_ins.storage_space_id=storage_spaces.id ORDER BY check_ins.id ASC LIMIT 1) = '".$search."'")

and that works for me.

Activity icon

Replied to How To Make Laravel Eloquent Request With 1 Filter On Many Fields

I found a decision addin in scope :

    ->orWhereRaw("(SELECT check_ins.job_ref_no FROM check_ins WHERE
       check_ins.storage_space_id=storage_spaces.id ORDER BY check_ins.id ASC LIMIT 1) = '".$search."'")

and that works for me.

May
18
1 week ago
Activity icon

Replied to How To Make Laravel Eloquent Request With 1 Filter On Many Fields

I try to create sql I need mannually. With Laravel request :

        $storageSpacesCollection = StorageSpace
            ::getByStatus($filter_status)
            ->whereRaw('storage_spaces.id <= 8') // DEBUGGING
            ->getById($relatedStorageSpacesArray)
            ->getByLocationId($filter_location_id, 'warehouses')
            ->getByCapacityCategoryId($filter_capacity_category_id, 'storage_capacities')
            ->getByLevel($filter_level)
            ->getByNumber($filter_number, true)
            ->orderBy('storage_spaces.id', 'asc')
            ->getByStorageCapacityId($filter_storage_capacity_id)
            ->getByClientId($filter_client_id)
            ->getByColorId($filter_color_id)
            ->getBySearch($filter_search)

            ->leftJoin( 'storage_capacities', 'storage_capacities.id', '=', 'storage_spaces.storage_capacity_id' )
            ->leftJoin( 'warehouses', 'warehouses.id', '=', 'storage_spaces.warehouse_id' )
            ->leftJoin( 'clients', 'clients.id', '=', 'storage_spaces.client_id')
            ->select(
                "storage_spaces.*",

                \DB::raw( "CONCAT(storage_capacities.count, ' ', storage_capacities.sqft ) as storage_capacity_name" ),

                \DB::raw("( SELECT check_ins.job_ref_no FROM check_ins WHERE check_ins.storage_space_id=storage_spaces.id ORDER BY check_ins.id ASC limit 1 ) AS job_ref_no"),

                "warehouses.name as warehouse_name",
                "clients.full_name as client_full_name")
            ->get();

And tracing I see sql statement with job_ref_no column :

   SELECT `storage_spaces`.*, CONCAT(storage_capacities.count, ' ', storage_capacities.sqft )     AS storage_capacity_name, (   SELECT check_ins.job_ref_no 
    FROM check_ins 
    WHERE check_ins.storage_space_id=storage_spaces.id 
    ORDER BY check_ins.id ASC limit 1 )     AS job_ref_no, `warehouses`.`name`     AS `warehouse_name`, `clients`.`full_name`     AS `client_full_name` 
    FROM `storage_spaces` 
    LEFT JOIN `storage_capacities` on `storage_capacities`.`id` = `storage_spaces`.`storage_capacity_id` 
    LEFT JOIN `warehouses` on `warehouses`.`id` = `storage_spaces`.`warehouse_id` 
    LEFT JOIN `clients` on `clients`.`id` = `storage_spaces`.`client_id` 
    WHERE storage_spaces.id <= 8     AND (`storage_spaces`.`number` = '999'     OR 
  
      (`storage_spaces`.`notes` like '%999%'     OR 
       `storage_spaces`.`selling_range` = '999'     OR 
       `storage_spaces`.`actual_storage_rent` = '999'     OR 
       `storage_spaces`.`insurance_vat` = '999') ) 
    ORDER BY `storage_spaces`.`id` asc 

I want to set filter on job_ref_no column manually :

   SELECT `storage_spaces`.*, CONCAT(storage_capacities.count, ' ', storage_capacities.sqft )     AS storage_capacity_name, (   SELECT check_ins.job_ref_no 
    FROM check_ins 
    WHERE check_ins.storage_space_id=storage_spaces.id 
    ORDER BY check_ins.id ASC limit 1 )     AS job_ref_no, `warehouses`.`name`     AS `warehouse_name`, `clients`.`full_name`     AS `client_full_name` 
    FROM `storage_spaces` 
    LEFT JOIN `storage_capacities` on `storage_capacities`.`id` = `storage_spaces`.`storage_capacity_id` 
    LEFT JOIN `warehouses` on `warehouses`.`id` = `storage_spaces`.`warehouse_id` 
    LEFT JOIN `clients` on `clients`.`id` = `storage_spaces`.`client_id` 
    WHERE storage_spaces.id <= 8     AND (`storage_spaces`.`number` = '999'     OR 
  
      (`storage_spaces`.`notes` like '%999%'     OR 
       `storage_spaces`.`selling_range` = '999'     OR 
       `storage_spaces`.`actual_storage_rent` = '999'     OR 
       `storage_spaces`.`insurance_vat` = '999' OR 
       job_ref_no = '999' )   // I added this line @
     ) 
    ORDER BY `storage_spaces`.`id` asc 

But I got error :

Error in query (1054): Unknown column 'job_ref_no' in 'where clause'

Which is valid way in raw sql and how it can be implemented with eloquent ?

May
17
1 week ago
Activity icon

Started a new Conversation How To Make Laravel Eloquent Request With 1 Filter On Many Fields

Hello,

In my Laravel 5.7/ mysql app I make request on a form with 10 filter inputs, one of them ($filter_search) if non empty must be compared with all fields(string, number, date, ref to fields of other tables) in resulting listing.

I made scope on this table fields:

    public function scopeGetBySearch($query, $search = null)
    {
        if (empty($search)) {
            return $query;
        }
        $tb= with(new StorageSpace)->getTable();
        return $query->where(
            $tb.'.number',  $search
        ) ->orWhere(function ($query) use ($search, $tb) {
            $query->where( $tb.".notes",  'like',  '%'.$search.'%' )
                ->orWhere($tb.".selling_range", $search)
                    ->orWhere($tb.".actual_storage_rent", $search)
                        ->orWhere($tb.".insurance_vat", $search)
//                            ->havingRaw("job_ref_no", $search)

        })

But I have a problem how can I set filter on job_ref_no field from other table :

     $storageSpacesCollection = StorageSpace
            ::getByStatus($filter_status)
            ->getById($relatedStorageSpacesArray)
            ->getByLocationId($filter_location_id, 'warehouses')
            ->getByCapacityCategoryId($filter_capacity_category_id, 'storage_capacities')
            ->getByLevel($filter_level)
            ->getByNumber($filter_number, true)
            ->orderBy('storage_spaces.id', 'asc')
            ->getByStorageCapacityId($filter_storage_capacity_id)
            ->getByClientId($filter_client_id)
            ->getByColorId($filter_color_id)
            ->getBySearch($filter_search)

//            ->havingRaw("job_ref_no = " . $filter_search)

            ->leftJoin( 'storage_capacities', 'storage_capacities.id', '=', 'storage_spaces.storage_capacity_id' )
            ->leftJoin( 'warehouses', 'warehouses.id', '=', 'storage_spaces.warehouse_id' )
            ->leftJoin( 'clients', 'clients.id', '=', 'storage_spaces.client_id')
            ->select(
                "storage_spaces.*",

                \DB::raw( "CONCAT(storage_capacities.count, ' ', storage_capacities.sqft ) as storage_capacity_name" ),

                \DB::raw("( SELECT check_ins.job_ref_no FROM check_ins WHERE // I got job_ref_no field in subquesry  check_ins.storage_space_id=storage_spaces.id ORDER BY check_ins.id ASC limit 1 ) AS job_ref_no"),

                "warehouses.name as warehouse_name",
                "clients.full_name as client_full_name")
            ->get();

havingRaw does not work both in the scope and in the request above if to uncomment it.

  1. I tried to use addSelect, like:

But with request :

        $storageSpacesCollection = StorageSpace
            ::getByStatus($filter_status)
            ->whereRaw('storage_spaces.id <= 8') // DEBUGGING
            ->getById($relatedStorageSpacesArray)
            ->getByLocationId($filter_location_id, 'warehouses')
            ->getByCapacityCategoryId($filter_capacity_category_id, 'storage_capacities')
            ->getByLevel($filter_level)
            ->getByNumber($filter_number, true)
            ->orderBy('storage_spaces.id', 'asc')
            ->getByStorageCapacityId($filter_storage_capacity_id)
            ->getByClientId($filter_client_id)
            ->getByColorId($filter_color_id)
            ->getBySearch($filter_search)

//            ->havingRaw("job_ref_no = " . $filter_search)

            ->leftJoin( 'storage_capacities', 'storage_capacities.id', '=', 'storage_spaces.storage_capacity_id' )
            ->leftJoin( 'warehouses', 'warehouses.id', '=', 'storage_spaces.warehouse_id' )
            ->leftJoin( 'clients', 'clients.id', '=', 'storage_spaces.client_id')
            ->select(
                "storage_spaces.*",
                \DB::raw( "CONCAT(storage_capacities.count, ' ', storage_capacities.sqft ) as storage_capacity_name" ),
                "warehouses.name as warehouse_name",
                "clients.full_name as client_full_name")
            ->addSelect([
                'job_ref_no' => CheckIn::selectRaw('job_ref_no')->whereColumn('check_ins.storage_space_id', 'storage_spaces.id'),
            ])
            ->get();

I got an error:

 local.ERROR: stripos() expects parameter 1 to be string, object given {"userId":11,"email":"[email protected]","exception":"[object] (ErrorException(code: 0): stripos() expects parameter 1 to be string, object given at /mnt/_work_sdb8/wwwroot/lar/the-box-booking/vendor/laravel/framework/src/Illuminate/Database/Query/Grammars/Grammar.php:1031)
[stacktrace]
#0 [internal function]: Illuminate\Foundation\Bootstrap\HandleExceptions->handleError(2, 'stripos() expec...', '/mnt/_work_sdb8...', 1031, Array)
#1 /mnt/_work_sdb8/wwwroot/lar/the-box-booking/vendor/laravel/framework/src/Illuminate/Database/Query/Grammars/Grammar.php(1031): stripos(Object(Illuminate\Database\Eloquent\Builder), ' as ')
#2 [internal function]: Illuminate\Database\Query\Grammars\Grammar->wrap(Object(Illuminate\Database\Eloquent\Builder))

Which way is valid ?

Thanks!

May
16
2 weeks ago
Activity icon

Replied to How To Make Filtering On Client In Blade Listing Written With Jquery?

Actually I mean something different : like table with data on client with custom Filter inputs and custom columns for rows of data. Are there something like that ?

May
15
2 weeks ago
Activity icon

Started a new Conversation How To Make Filtering On Client In Blade Listing Written With Jquery?

Hello,

In my Laravel 5.7/jquey 3/ bootstrap 4 / mysql app I make in user's editor listing of clients and buttons to give/revoke access to any user.

I fill div in user's editor :

     <div class="tab-pane active" id="pills-related-user-access-clients" role="tabpanel"
         aria-labelledby="pills-related-user-access-clients" style="border:3px dotted blue;">
         <div id="div_related_user_access_clients" style="border:2px dotted green;"></div>
     </div>

When javascript is run :

backendUser.prototype.getUserRelatedUserAccessClients = function (user_id) {
    if ( typeof user_id == "undefined" ) return
    var href = '/admin/get-user-related-user-access-clients/' + user_id;
    $.ajax({
        type: "GET",
        dataType: "json",
        url: href,
        success: function (response) {
            $("#div_related_user_access_clients").html(response.html);
        },
        error: function (error) {
            popupErrorMessage(error.responseJSON.message)
        }

    });

} // function uploadUserDetailsInfo(user_id) {

and I use blade template for listing:

@if(count($clientsList) == 0)
    <h4 class="card-subtitle pl-2 pb-2">Has no clients in the system yet</h4>
@else
    <h4 class="card-subtitle pl-2 pb-2">Has {{ count($clientsList) }} clients, {{ $selected_user_access_clients_count }} selected for this user. </h4>

    <div class="table-responsive" style="max-height: 900px; overflow-y:auto; width: 100% !important;">
        <table class="table table-bordered table-striped text-primary ">
            @foreach($clientsList as $next_key => $nextRelatedClient)
                <tr>
                    <td>
                        {{$nextRelatedClient->client_id }}::{{ $nextRelatedClient->full_name }}
                    </td>
                    <td>

                        @if( !empty($nextRelatedClient->is_checked) )
                            <a href="#" onclick="javascript:backendUser.clearUserAccessClientToUser({{$nextRelatedClient->client_id }},'{{$nextRelatedClient->full_name }}')">
                                <i class="fa fa-remove"></i>Revoke Access
                            </a>
                            <b>&nbsp;&nbsp;Selected</b>&nbsp;
                        @else
                            <a href="#" onclick="javascript:backendUser.attachUserAccessClientToUser({{$nextRelatedClient->client_id }},
                                '{{$nextRelatedClient->full_name }}')">
                                <i class="fa fa-paperclip"></i>Give Access
                            </a>
                        @endif

                    </td>

                </tr>
            @endforeach

        </table>
    </div>

@endif

Also I am going to add checkbox near with any client to make group operations. It works for me, but clients listing is rather big(more 1000 items). Are there some tools to make search filter on client's side(no on server) ? At least 1 input for client name but with possibility to add filter inputs/checkbox, selection ? Also if some filter is applied not to lose group selections I have at this moment.

Thanks!

May
10
2 weeks ago
Activity icon

Replied to How To Test Sendgrid Email With Mailtrap For Testing?

I founbd a link to video how to implement multiple mail drivers: https://www.youtube.com/watch?v=HCONO0cwsoI

I tried to follow it, but with I always got email at mailtrap.

Priorly, I worked with sendgrid and for this in file config/mail.php I wrote all sendgrid parameters. Now I want to write 2 emeil servers and fi=or this in .env I wrote:

MAIL_DRIVER=smtp
MAIL_HOST=smtp.mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=mailtrip_id
MAIL_PASSWORD=mailtrip_password

SENDGRID_HOST=smtp.sendgrid.net
SENDGRID_PORT=587
SENDGRID_ENCRYPTION=tls
SENDGRID_USERNAME=sendgrid_user
SENDGRID_PASSWORD=sendgrid_user_password

and I remade config/mail.php (I got a sample from https://github.com/laravel/laravel/blob/master/config/mail.php):

<?php
return [


    'driver' => env('MAIL_DRIVER', 'smtp'),


    'host' => env('MAIL_HOST', 'smtp.mailgun.org'),


    'port' => env('MAIL_PORT', 587),


    'from' => [
        'address' => env('MAIL_FROM_ADDRESS', '[email protected]'),
        'name' => env('MAIL_FROM_NAME', 'Example'),
    ],


    'encryption' => env('MAIL_ENCRYPTION', 'tls'),

    'username' => env('MAIL_USERNAME'),

    'password' => env('MAIL_PASSWORD'),

    'sendmail' => '/usr/sbin/sendmail -bs',

    'markdown' => [
        'theme' => 'default',

        'paths' => [
            resource_path('views/vendor/mail'),
        ],
    ],

    'log_channel' => env('MAIL_LOG_CHANNEL'),

    'mailers' => [
        'smtp' => [
            'transport' => 'smtp',
            'host' => env('MAIL_HOST'),
            'port' => env('MAIL_PORT'),
            'encryption' => env('MAIL_ENCRYPTION', 'tls'),
            'username' => env('MAIL_USERNAME'),
            'password' => env('MAIL_PASSWORD'),
            'timeout' => null,
            'auth_mode' => null,
        ],

        'sendgrid' => [
            'transport' => 'sendgrid',
            'host' => env('SENDGRID_HOST', 'smtp.sendgrid.net'),
            'port' => env('SENDGRID_PORT', 587),
            'encryption' => env('SENDGRID_ENCRYPTION', 'tls'),
            'username' => env('SENDGRID_USERNAME'),
            'password' => env('SENDGRID_PASSWORD'),
            'timeout' => null,
            'auth_mode' => null,
        ],

        'ses' => [
            'transport' => 'ses',
        ],

        'mailgun' => [
            'transport' => 'mailgun',
        ],

        'postmark' => [
            'transport' => 'postmark',
        ],

        'sendmail' => [
            'transport' => 'sendmail',
            'path' => '/usr/sbin/sendmail -bs',
        ],

        'log' => [
            'transport' => 'log',
            'channel' => env('MAIL_LOG_CHANNEL'),
        ],

        'array' => [
            'transport' => 'array',
        ],
    ],

];

I am not sure that this config file is valid? Are mail config parameters are read from mailers array ? Looks like default(mailtrip) mail config is used always. Is it invalid format ?

In my control I do:

        $email_mode= 'live';
//        $email_mode= 'debug';

        if( $email_mode== 'debug' ) {
            \Log::info( '-10 Send to mailtrap ::' );

            \Mail
                ::mailer('smtp')
                ->to('[email protected]') // DEBUG
                ->send(new TestEmail);  // 
            \Log::info( '-10 Send to mailtrap AFTER::' );
        }

        // sendgrid
        if( $email_mode== 'live') {
            \Log::info( '-11 Send to sendgrid ::' );
            \Mail
                ::mailer('sendgrid')
                ->to('[email protected]') // DEBUG
                ->send(new SendgridMail('emails/contact_us_was_sent', $newContactUs->author_email, '', $subject, $additiveVars, $attachFiles));
            \Log::info( '-11 Send to sendgrid AFTER::' );
        }

I check in logs that live flow is run but anyway I got email at mailtrap.

May
09
3 weeks ago
Activity icon

Started a new Conversation Search For Laravel Comments Plugin

Hello,

In my Laravel 5.7/jquey 3/ bootstrap 4 / mysql app I need to implement comments in product Editor. Are there some plugins or ready scripts? With features :

  1. Tree/listing view for comments
  2. User can answer comments
  3. User can edit/delete his own comments
  4. User/Superadmin can edit/delete all comments
  5. Additively some scopes to modify soem pieasers of code

Thanks!

May
04
3 weeks ago
Activity icon

Replied to With OAuth2 Implementation Failed To Get Service With Bearer Token

Sure my config/auth.php has:

    'guards' => [
        'web' => [
            'driver' => 'session',
            'provider' => 'users',
        ],

        'api' => [
//            'driver' => 'token',
            'driver' => 'passport',
            'provider' => 'users',
        ],
    ],

In app/Http/Kernel.php :

        'api' => [
            'throttle:60,1',
            'bindings',
        ],

Also I run: php artisan config:cache composer dump-autoload

		"laravel/framework": "^7.0",
		"laravel/passport": "^8.4",

Which parameters else have I to check ?

May
03
3 weeks ago
Activity icon

Started a new Conversation With OAuth2 Implementation Failed To Get Service With Bearer Token

Hello, I make In laravel 7 I OAuth2 Implementation with passport and in postman I managed to connect and to get access_token https://imgur.com/a/HR6cuvV

But I got error message "Unauthenticated." when try to get from my app with api : https://imgur.com/a/zA6Kodd

Where

http://local-votes.com/api/votes

is written in routes/api.php as :

//Route::get('votes', 'API\[email protected]');
// is run with  http://local-votes.com/api/votes

Route::group(['middleware' => [ 'auth:api']], function(){
    Route::apiResource('votes', '[email protected]');
});

As it is blade type app I used routes/web.php and only for this service I start using routes/api.php for my serice, so if to uncomment line:

Route::get('votes', 'API\[email protected]');

my control opens in browser ok

In sql trace I see line with null user in the 2nd request:

Time 7.84 : 
   SELECT * 
    FROM `vt2_oauth_access_tokens` 
    WHERE `id` = '9ccc3466f5e840c1c565cef1b6e2720a2e175f8fcc281863b2c3fac6bcb3eb8528670455d3f9fdfa' limit 1 
  
  
Time 14.63 : 
   SELECT * 
    FROM `vt2_users` 
    WHERE `id` is null limit 1 

In 1st request user from oauth_access_tokens yable is found. Setting passport in app/Providers/AuthServiceProvider.php I added :

use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
use Laravel\Passport\Passport;

class AuthServiceProvider extends ServiceProvider
{
    protected $policies = [
        'App\Model' => 'App\Policies\ModelPolicy',
    ];

    public function boot()
    {
        $this->registerPolicies();

        Passport::routes();
    }

and in app/User.php :

use Illuminate\Foundation\Auth\User as Authenticatable;

use DB;
use Illuminate\Support\Facades\Storage;
use Illuminate\Validation\Rule;

use Illuminate\Contracts\Auth\MustVerifyEmail;
...
class User extends Authenticatable implements MustVerifyEmail
{
    use Billable;
    use HasApiTokens, Notifiable;
    protected $table = 'users';
    protected $primaryKey = 'id';
    public $timestamps = false;

What did I miss ?

Thanks!

May
01
4 weeks ago
Activity icon

Replied to I Got Unable To Resolve PSR Request Error With GuzzleHttp Request

Installing package nyholm/psr7 on provider app salved the problem!

Apr
30
1 month ago
Activity icon

Started a new Conversation I Got Unable To Resolve PSR Request Error With GuzzleHttp Request

Hello, Implementing in my Laravel 7.6 app(at hosts at http://local-votes.com of my local OS) api for external api I want to make a test request from my other Laravel 6.17.1 app and reading here : https://laravel.com/docs/7.x/passport

Converting Authorization Codes To Access Tokens

I try to use this example:

        $request = request();
        $requestData= $request->all();

        $this->debToFile(print_r( $requestData,true),'  ImportController  -0 $requestData::');
        \Log::info( '-1 ImportController->votes $requestData ::' . print_r(  $requestData, true  ) );


        $http = new \GuzzleHttp\Client;

        $client_id= 3;  // client ID I made in my host app
        $client_secret= 'XXX'; // client secret I made in my host app

        $host= 'http://local-votes.com';
        $response = $http->post($host.'/oauth/token', [
            'form_params' => [
                'grant_type' => 'authorization_code',
                'client_id' => $client_id,
                'client_secret' => $client_secret,
                'redirect_uri' => $host.'/votes',
                'code' => 'code',
//                'code' => $request->code,
            ],
        ]);

But I got error :

Illuminate\Contracts\Container\BindingResolutionException: Unable to resolve PSR request. Please i (truncated...)
 {"userId":5,"exception":"[object] (GuzzleHttp\Exception\ServerException(code: 500): Server error: `POST http://local-votes.com/oauth/token` resulted in a `500 Internal Server Error` response:

Also I am not sure which values have I provide for fields 'client_secret' and 'code' ? Can it be the issue ?

How to fix this error ?

Thanks!

Activity icon

Replied to Cypress File Uploading Error With Cypress-file-upload

Have anybody uploaded files in cypress? Please, share your expierence...

Apr
28
1 month ago
Activity icon

Replied to How To Work In Laravel App With External App?

Thanks! Reading the provided link I try to setup common flow :

  1. Install passport

  2. with command

php artisan passport:client

genarate client and secret

  1. keep client ID and secret and send client ID/secret key to my client. Now we have only 1 client and no interface for automatic regestration

  2. reading https://laravel.com/docs/5.7/passport I see code block :

Route::get('/callback', function (Request $request) {
    $http = new GuzzleHttp\Client;

    $response = $http->post('http://your-app.com/oauth/token', [
        'form_params' => [
            'grant_type' => 'authorization_code', // Valid value? What is it ?
            'client_id' => 'client ID from step 3',
            'client_secret' => 'client secret from step 3',
            'redirect_uri' => 'http://example.com/callback',
            'code' => $request->code,
        ],
    ]);

Is redirect_uri parameter to control which must return my data in json format to client? I mean that in this API we do not visual redirecting in browser...

  1. In the docs I see that in my config/auth.php I have to change line:
  'driver' => 'passport',

Does it influence the rest parts of the app as I have blade formsd with

                {!! csrf_field() !!}

method used?

  1. I used laravel-cors for my REST API site protection to give access to requests of my site only permitted urls. Do I need it here with passwport? Would it be doubled protection and do we need it?
Activity icon

Started a new Conversation How To Work In Laravel App With External App?

Hello,

in my Laravel 5.7/mysql app I need to make services for external app(I do not know what is it written with)

  1. To read some data from my app by this external app with GET-request and
  2. The external app must write some data to my db with POST-request.

Which tools/scripts are there for this and how to make these requests safe?

Thanks!

Apr
27
1 month ago
Activity icon

Started a new Conversation How To Test Sendgrid Email With Mailtrap For Testing?

Hello, In my Laravel 7.6 app I use sendgrid for email sending with code in control like :

  \Mail
    ::to($newContactUs->author_email)->
   send(new SendgridMail('emails/contact_us_was_sent', $newContactUs->author_email, '', $subject, $additiveVars, $attachFiles));

with class in app/Mail/SendgridMail.php :

<?php

namespace App\Mail;

use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Queue\ShouldQueue;
use Sichikawa\LaravelSendgridDriver\SendGrid;
use App\Settings;
use App\Http\Traits\funcsTrait;

class SendgridMail extends Mailable
{
    use Queueable, SerializesModels;
    use SendGrid;
    use funcsTrait;

    private  $m_view_name;
    private  $m_to;
    private  $m_cc;
    private  $m_subject;
    private  $m_additiveVars;
    private  $m_attachFiles;

    public function __construct( $view_name, $to= [], $cc= '', $subject= '', $additiveVars= [], $attachFiles= [] )
    {
        $this->m_view_name= $view_name;
        $this->m_to= $to;
        $this->m_cc= $cc;
        $this->m_subject= $subject;
        $all_emails_copy      =   \Config::get('app.all_emails_copy');

        if ( empty($this->m_cc) and !empty($all_emails_copy)) {
            $this->m_cc= $all_emails_copy;
        }


        $additiveVars['site_home_url']         = \URL::to('/');
        $additiveVars['site_name']             = Settings::getValue('site_name');
        $additiveVars['noreply_email']         = Settings::getValue('noreply_email');
        $additiveVars['support_signature']     = Settings::getValue('support_signature');
        $additiveVars['medium_slogan_img_url'] = config('app.url').config('app.medium_slogan_img_url');

        $this->m_additiveVars= $additiveVars;
        $this->m_attachFiles= $attachFiles;
    }

    /**
     * Build the message.
     *
     * @return $this
     */
    public function build( )
    {
        $mailObject= $this
            ->view( $this->m_view_name)
            ->subject($this->m_subject)
            ->to([$this->m_to])
            ->cc([$this->m_cc])
            ->with( $this->m_additiveVars )
            ->sendgrid( $this->m_additiveVars );
        foreach( $this->m_attachFiles as $next_attach_file) {
            if ( file_exists($next_attach_file) ) {
                $mailObject->attach($next_attach_file);
            }
        }
        return $mailObject;
    }

}

and template resources/views/emails/contact_us_was_sent.blade.php:

...
<div class="wrapper">
	@inject('viewFuncs', 'App\library\viewFuncs')


	<h4 class="email_title">
		Hello, {!! $to_user_name !!} !
	</h4>
    ...

	@include( 'emails.app_footer')
	@include( 'emails.emails_style')
</div>

and it works for me now, but now with "Multiple Mail Drivers" I added mailtrap to my .env :

MAIL_DRIVER=smtp
MAIL_HOST=smtp.mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=NNNNNNNN
MAIL_PASSWORD=NNNNNNNN

and I want t use mailtrap while testing the app using the same template resources/views/emails/contact_us_was_sent.blade.php and switching from mailtrap to sendgrid as easy as possible.

I tried something like :

    \Mail::mailer('smtp')
    ->to($newContactUs->author_email)
    ->send( \Mail('emails/contact_us_was_sent', $newContactUs->author_email, '', $subject, $additiveVars, $attachFiles) );

But got error as \Mail does not support templates. Are there something to use support templates for mail Method? Some wrapper?

Thanks!

Apr
24
1 month ago
Activity icon

Started a new Conversation Cypress File Uploading Error With Cypress-file-upload

Hello,

In my vue/cli 4 / Bootstrap 4.3 app I use vue-upload-component component for files uploading and it works ok. I want to add cypress for testing file uploading and I added https://github.com/abramenal/cypress-file-upload/tree/v3.5.3 into my project, but failed with this testing. I have in vue file:


                        <file-upload
                                ref="upload"
                                v-model="imageFiles"
                                post-action="/post.method"
                                put-action="/put.method"
                                @input-file="inputFile"
                                @input-filter="inputFilter"
                                :multiple="false"
                                class="btn btn-outline-secondary btn-sm m-2 file-input-class"
                                data-cy="file-input"
                        >
                            <i :class="'action_link '+getHeaderIcon('upload')"></i>Upload image
                        </file-upload>

                        ...
                       const VueUploadComponent = require('vue-upload-component')
                       Vue.component('file-upload', VueUploadComponent)

and in my browser it is rendered into :

<span class="btn btn-outline-secondary btn-sm m-2 file-input-class file-uploads file-uploads-html5" data-cy="file-input">
    <i class="action_link fa fa-upload"></i>
    Upload image  
    <label for="file"></label> 
    <input type="file" name="file" id="file">
</span>

I cypress test file I do :

            import 'cypress-file-upload'
            describe('Admin category fileupload functionality', () => {
                ...
                const fileName = '/sample_images/sample.png';

                cy.contains('Image Preview/Upload')

                cy.fixture(fileName).then(fileContent => {
//                    cy.find('#file')
//                        .should('have.value', 'Invalid Text')

                    console.log('++Inside Tests cy::')
                    console.log(cy)

                    cy.get('#file').upload({ fileContent, fileName, mimeType: 'image/png' });
                });

But in the console I got error:

THEN  function(){}
TypeError: cy.get(...).upload is not a function

I see next ouput of cy var : https://imgur.com/a/O71JEFA

Also in testing code above to uncomment 2 lines :

                    cy.find('#file')
                        .should('have.value', 'Invalid Text')

I do not have should errors, as I expected, asnd I do not understand why ?

How to make file uploading testing?

  "axios": "^0.19.0",
   "cypress-file-upload": "^4.0.6",
   "file-saver": "^2.0.2",
   "vue": "^2.6.10",
   "vue-upload-component": "^2.8.20",

Thanks!

Apr
18
1 month ago
Activity icon

Replied to Invalid Sorting In Rows Of Laravel-datatables-oracle

Thanks for your hint! To switch ordering is not a way for me, but I found link: https://datatables.net/reference/api/column().order() That is similar what I need, but in my case the problem is that I format datetime field in php control's action. So sorting by datetime field is not sorted properly. If datatables has possibility to sort by datetime field and show this field formatted? If yes, please link...

Apr
17
1 month ago
Activity icon

Started a new Conversation Invalid Sorting In Rows Of Laravel-datatables-oracle

Hello, In my laravel 5.8 app using yajra/laravel-datatables-oracle 8 I make report sorted by 2 fields and I see that results are shown in different order. My control action is :

    public function get_check_out_history_dt_listing()
    {
        $request     = request();
        $requestData = $request->all();
        $filter_customer = !empty($requestData['filter_customer']) ? $requestData['filter_customer'] : '';
        $filter_check_out_datepicker_from = !empty($requestData['filter_check_out_datepicker_from']) ? $requestData['filter_check_out_datepicker_from'] : '';
        $filter_check_out_datepicker_till = !empty($requestData['filter_check_out_datepicker_till']) ? $requestData['filter_check_out_datepicker_till'] : '';

        $filter_check_out_datepicker_from = str_replace(',', '', $filter_check_out_datepicker_from);
        if ( !empty($filter_check_out_datepicker_from) ) {
            $filter_check_out_datepicker_from = Carbon::createFromFormat('d M Y', $filter_check_out_datepicker_from)->format('Y-m-d' );
        }

        $filter_check_out_datepicker_till = str_replace(',', '', $filter_check_out_datepicker_till);
        if ( !empty($filter_check_out_datepicker_till) ) {
            $filter_check_out_datepicker_till = Carbon::createFromFormat('d M Y', $filter_check_out_datepicker_till)->format('Y-m-d' );
        }

        $checkOutsCollection = CheckIn
            ::orderBy('check_ins.paid_through_date', 'asc') // The 2 fields I make sorting
            ->orderBy('storage_spaces.number', 'asc')
            ->getByStatus('O')  // O=>Check Out
            ->getByPaidThroughDate($filter_check_out_datepicker_from, '>=')
            ->getByPaidThroughDate($filter_check_out_datepicker_till, '<=')
            ->whereRaw( 'NOT ISNULL(check_ins.paid_through_date) ')
            ->leftJoin( 'clients', 'clients.id', '=', 'check_ins.client_id' )
            ->leftJoin( 'storage_spaces', 'storage_spaces.id', '=', 'check_ins.storage_space_id' )
            ->where( 'clients.full_name', 'like' , '%' . $filter_customer .'%' )
            ->select(
                "check_ins.id",
                "check_ins.check_in_date",
                "check_ins.paid_through_date",
                "check_ins.vat",
                "check_ins.job_ref_no as check_ins_job_ref_no",
                "clients.full_name as client_full_name",
                "clients.address as client_address",
                "storage_spaces.number as storage_spaces_number",
                "storage_spaces.status as storage_spaces_status",
                "check_ins.insurance_vat as storage_insurance_vat",
                "check_ins.vat as storage_actual_storage_rent"
            )
            ->get();

        return Datatables
            ::of($checkOutsCollection)     /*  Set format/labels for specific columns  */
            ->editColumn('storage_spaces_status', function ($storageSpace) {
                if (empty($storageSpace->storage_spaces_status)) {
                    return '';
                }
                return StorageSpace::getStorageSpaceStatusLabel($storageSpace->storage_spaces_status);
            })

            ->editColumn('storage_insurance_vat', function ($storageSpace) {
                if (empty($storageSpace->storage_insurance_vat)) {
                    return '';
                }
                return $this->formatCurrencySum($storageSpace->storage_insurance_vat);
            })

            ->editColumn('storage_actual_storage_rent', function ($storageSpace) {
                if (empty($storageSpace->storage_actual_storage_rent)) {
                    return '';
                }
                return $this->formatCurrencySum($storageSpace->storage_actual_storage_rent);
            })
            ->editColumn('check_in_date', function ($storageSpace) {
                if (empty($storageSpace->check_in_date)) {
                    return '';
                }
                return $this->getCFFormattedDate($storageSpace->check_in_date);
            })
            ->editColumn('paid_through_date', function ($storageSpace) {
                if (empty($storageSpace->paid_through_date)) {
                    return '';
                }
                return $this->getCFFormattedDate($storageSpace->paid_through_date);
            })
            ->make(true);
    } // get_check_out_history_dt_listing

and in related js file I run :

checkOutHistory.prototype.checkOutHistoryDataLoad = function () {
    Mustache.tags = ["<%", "%>"];

    var columnsData = []
    // columnsData[columnsData.length] = {data: 'id', name: 'id'}
    columnsData[columnsData.length] = {data: 'storage_spaces_number', name: 'storage_spaces_number'}
    columnsData[columnsData.length] = {data: 'storage_spaces_status', name: 'storage_spaces_status'}
    columnsData[columnsData.length] = {data: 'client_full_name', name: 'client_full_name'}
    columnsData[columnsData.length] = {data: 'client_address', name: 'client_address'}
    columnsData[columnsData.length] = {data: 'check_ins_job_ref_no', name: 'check_ins_job_ref_no'}
    columnsData[columnsData.length] = {data: 'check_in_date', name: 'check_in_date'}
    columnsData[columnsData.length] = {data: 'storage_actual_storage_rent', name: 'storage_actual_storage_rent'}
    columnsData[columnsData.length] = {data: 'storage_insurance_vat', name: 'storage_insurance_vat'}
    columnsData[columnsData.length] = {data: 'paid_through_date', name: 'paid_through_date'}


    oTable = $('#get-check-out-history-dt-listing-table').DataTable({
        processing: true,
        autoWidth: false,
        language: {
            "processing": "Loading Check Out History..."
        },
        serverSide: true,
        "lengthChange": true,
        "lengthMenu": this_backendLengthMenuArray,
        ajax: {                          // report/get-check-out-history-dt-listing
            url: this_backend_home_url + '/admin/report/get-check-out-history-dt-listing',
            data: function (d) {
                d.filter_customer = $("#filter_customer").val();
                d.filter_check_out_datepicker_from = $("#filter_check_out_datepicker_from").val();
                d.filter_check_out_datepicker_till = $("#filter_check_out_datepicker_till").val();
            },
        }, // ajax: {

        columns: columnsData,

        "drawCallback": function (settings, b) {
            var span_check_out_histories_records_count_content = $("#span_check_out_histories_records_count").html()

            if (typeof span_check_out_histories_records_count_content != "undefined") {
                $("#span_check_out_histories_records_count").html( ". Shows " + settings.json.data.length + " of " + settings.json.recordsFiltered + " box rooms" )
            } else {
                var $label = $("<label>").text(". Shows " + settings.json.data.length + " of " + settings.json.recordsFiltered + " box rooms").attr({
                    id: 'span_check_out_histories_records_count',
                    name: 'span_check_out_histories_records_count'
                });

                $(".dataTables_length > label ").append( $label );
            }

            $(".dataTables_info").css("display", "none")
            if (settings.json.recordsTotal <= settings.aiDisplay.length) { // we need to hide pagination block
                $(".dataTables_paginate").css("display", "none")
            } else {  // we need to show pagination block
                $(".dataTables_paginate").css("display", "block")
            }

        },

    }); // oTable = $('#get-check-out-history-dt-listing-table').DataTable({

}

When I check sql-trace I see that all rows are returned in valid order I set with orderBy in my control. That datatables changed ordering and I do not see where I do not set any ordering anymore in datatables... and how can I set it manually ?

Thanks!

Apr
15
1 month ago
Activity icon

Started a new Conversation How With Cypress Testing Vue/cli To Switch To Sqlite Db?

Looking at “Episode 39 - Learn Cypress with Laravel Integration” at https://laracasts.com/series/whatcha-working-on/episodes/39 there is an example of Laravel app testing with diferent .env file and switching to sqlite db. As I have @vue/cli 4 app with Laravel 6 Backend REST API and backend. I wonder if there is a way to test frontend part with cypress and switching Laravel 6 Backend app to sqlite db ?

Thanks!

Activity icon

Started a new Conversation How With Cypress Testing Vue/cli To Switch To Sqlite Db?

Looking at “Episode 39 - Learn Cypress with Laravel Integration” at https://laracasts.com/series/whatcha-working-on/episodes/39 there is an example of Laravel app testing with diferent .env file and switching to sqlite db. As I have @vue/cli 4 app with Laravel 6 Backend REST API and backend. I wonder if there is a way to test frontend part with cypress and switching Laravel 6 Backend app to sqlite db ?

Thanks!

Apr
13
1 month ago
Activity icon

Replied to How To Join Request On 2 Fields With OR Condition?

using Parameter Grouping I created a request :

        $storageSpacesCollection = StorageSpace
            ::where(function ($query) use ($report_date_from, $report_date_till) {
                $query->whereRaw("storage_spaces.check_in_date >= '" . $report_date_from . "' ")
                      ->whereRaw("storage_spaces.check_in_date < '" . $report_date_till . "' ") {

                $query->orWhereRaw("storage_spaces.check_out_date >= '" . $report_date_from . "' ")
                      ->whereRaw("storage_spaces.check_out_date < '" . $report_date_till . "' ") // ERROR POINTS AT THIS LINE

                };
                }
            )
            ->orderBy('storage_spaces.id', 'asc')
            ->leftJoin('storage_capacities', 'storage_capacities.id', '=', 'storage_spaces.storage_capacity_id')
            ->leftJoin('warehouses', 'warehouses.id', '=', 'storage_spaces.warehouse_id')
            ->leftJoin('clients', 'clients.id', '=', 'storage_spaces.client_id')
            ->select(
                "storage_spaces.*",
                \DB::raw("CONCAT(storage_capacities.count, ' ', storage_capacities.sqft ) as storage_capacity_name"),
                "warehouses.name as warehouse_name",
                "clients.full_name as client_full_name"
            )
            ->get()

But I got an error :

Cannot use object of type Illuminate\Database\Eloquent\Builder as array

Which syntax is valid ?

Activity icon

Replied to How To Join Request On 2 Fields With OR Condition?

Thanks! I try to implement it without scopes as :

        $storageSpacesCollection = StorageSpace
               ::where(function ($query) use ($report_date_from, $report_date_till){
                   $query->whereRaw("storage_spaces.check_in_date >= '" . $report_date_from . "' ")
                     ->whereRaw("storage_spaces.check_in_date < '" . $report_date_till . "' ")
                       ->orWhereRaw("storage_spaces.check_out_date >= '" . $report_date_from . "' ")
                       ->whereRaw("storage_spaces.check_out_date < '" . $report_date_till . "' ");
                })

and I see dql-trace :

  WHERE (storage_spaces.check_in_date >= '2020-1-01'      AND storage_spaces.check_in_date < '2020-2-01'      OR storage_spaces.check_out_date >= '2020-1-01'      AND storage_spaces.check_out_date < '2020-2-01' ) 
    ORDER BY `storage_spaces`.`id` asc 

It looks similar what I need. I think I need to add “(...)”, like :

    WHERE ( (storage_spaces.check_in_date >= '2020-1-01'      AND storage_spaces.check_in_date < '2020-2-01' (      OR ( storage_spaces.check_out_date >= '2020-1-01'      AND storage_spaces.check_out_date < '2020-2-01' ) ) 
    ORDER BY `storage_spaces`.`id` asc 

If there is way to make it ?

Apr
12
1 month ago
Activity icon

Started a new Conversation How To Join Request On 2 Fields With OR Condition?

Hello, In my laravel 5.8 app I need to make report by table storage_spaces with 2 fields check_in_date and check_out_date when year and monthes are entered. I make as:

        $report_year = (int)$requestData['report_year'];
        $report_month = (int)$requestData['report_month'];

        $report_date_from= $report_year.'-'.$report_month.'-01';
        if($report_month == 12) { // calculate from and till dates
            $report_month= 1;
            $report_year++;
        } else {
            $report_month++;
        }
        $report_date_till= $report_year.'-'.$report_month.'-01';

        $storageSpacesCollection = StorageSpace
            ...
            ->getByCheckInDate($report_date_from, ' >= ')
            ->getByCheckInDate($report_date_till, '< ')

            ->getByCheckOutDate($report_date_from, ' >= ')
            ->getByCheckOutDate($report_date_till, '< ')
            ...

As result I have invalid sql with several AND conditions :

   SELECT `storage_spaces`.*, 
    FROM `storage_spaces` 
    ...
    WHERE storage_spaces.check_in_date  >= '2020-1-01'      AND storage_spaces.check_in_date < '2020-2-01'      AND storage_spaces.check_out_date  >= '2020-1-01'      AND storage_spaces.check_out_date < '2020-2-01'  
    ORDER BY `storage_spaces`.`id` asc 

But the error is that between check_out_date and check_out_date must be OR condition, as any date withing start/end dates must be in report.

Scopes are defined in the model :

    public function scopeGetByCheckInDate($query, $filter_check_in_date_from = null, string $sign = null)
    {
        if ( ! empty($filter_check_in_date_from)) {
            if ( ! empty($sign)) {
                $query->whereRaw(DB::getTablePrefix().with(new StorageSpace)->getTable() . '.check_in_date ' . $sign . "'" . $filter_check_in_date_from . "' ");
            } else {
                $query->where(with(new StorageSpace)->getTable() . '.check_in_date', $filter_check_in_date_from);
            }
        }
        return $query;
    }

    public function scopeGetByCheckOutDate($query, $filter_check_out_date_from = null, string $sign = null)
    {
        if ( ! empty($filter_check_out_date_from)) {
            if ( ! empty($sign)) {
                $query->whereRaw(DB::getTablePrefix().with(new StorageSpace)->getTable() . '.check_out_date ' . $sign . "'" . $filter_check_out_date_from . "' ");
            } else {
                $query->where(with(new StorageSpace)->getTable() . '.check_out_date', $filter_check_out_date_from);
            }
        }
        return $query;
    }

Which is valid way to set OR condition ?

Thanks!

Apr
11
1 month ago
Activity icon

Awarded Best Reply on How With Bootstrap-colorpicker To Get Selected Color Only In Format “#ffffff”?

The decision is in additive format parameter :

    $('#cp_color').colorpicker({ 
        inline: false,
        container: true,
        format: 'hex',
Activity icon

Replied to How With Bootstrap-colorpicker To Get Selected Color Only In Format “#ffffff”?

The decision is in additive format parameter :

    $('#cp_color').colorpicker({ 
        inline: false,
        container: true,
        format: 'hex',
Apr
10
1 month ago
Activity icon

Started a new Conversation How With Bootstrap-colorpicker To Get Selected Color Only In Format “#ffffff”?

Hello, In my laravel 5.8 / "bootstrap": "^4.0.0" app I use I use bootstrap-colorpicker with sample : https://itsjavi.com/bootstrap-colorpicker/tutorial-p02_Advanced_Examples.html

and I want selecting color from picker always to get selected color in format “#ffffff”. But the problem is that periodically got value in rgb format : https://prnt.sc/rwqlqj Looks like it happens when I click on outer block selection. Are there some options to get selected color only in format “#ffffff” ?

I tried the example in link above like :

        $('#cp_color').colorpicker({ 
            popover: false,
            inline: false,
            container: true,
        })

            .on('colorpickerChange colorpickerCreate', function (e) {
                var colors = e.color.generate('tetrad');

                colors.forEach(function (color, i) {
                    var colorStr = color.string(),
                        swatch = e.colorpicker.picker
                            .find('.colorpicker-swatch[data-name="tetrad' + (i + 1) + '"]');

                    swatch
                        .attr('data-value', colorStr)
                        .attr('title', colorStr)
                        .find('> i')
                        .css('background-color', colorStr);
                });
            })
        ;

But failed and periodically I got invalid rgb value.

How to get selected color only in format “#ffffff” ? Thanks!

Apr
07
1 month ago
Activity icon

Started a new Conversation How With Cypress Get ID Of Inserted Row In CRUD Testing?

Using cypress("@vue/cli-plugin-e2e-cypress": "~4.2.0") in @vue/cli 4.0.5 app I make CRUD opearitions and adding new category :

    cy.get('#parent_id').select('1')


    cy.get('section.submit_form_category')
        .get('button.submit_button_category')
        .click()  // by submitting new category was added on server

    cy.url()
        .should('include', '/admin/categories/edit/')

    cy.contains('Edit category')

    cy.get('section.submit_form_category')
        .get('a.cancel_button_category')
        .click()


    cy.url()
        .should('include', '/admin/categories')
    cy.contains('Categories')  // opened listing of categories 

Next I need to delete this row and for this I need to get ID of a new category created above. If there is a way to make it ?

Thanks!

Apr
06
1 month ago
Activity icon

Awarded Best Reply on How To Use Vue-select With Cypress

Thanks for youe hint! I found a dicision with key down / enter keys sent :

        cy.get('#parent_id').click().type('{downarrow}{enter}')

That works for me!

Activity icon

Replied to How To Use Vue-select With Cypress

Thanks for youe hint! I found a dicision with key down / enter keys sent :

        cy.get('#parent_id').click().type('{downarrow}{enter}')

That works for me!

Apr
05
1 month ago
Activity icon

Replied to How To Use Vue-select With Cypress

With click on vue-select selection input is opened. But how can I make event "scroll Down" and click again?

Activity icon

Started a new Conversation How To Use Vue-select With Cypress

Using cypress in @vue/cli 4.0.5 app I faced a problem how to fill vue-select component

Searching in net I found this https://stackoverflow.com/questions/58298675/how-to-find-element-and-select-by-cypress-io-with-vue-js-v-select?noredirect=1&lq=1 branch, but the way proposed here does not work.

Having component defind :

    <v-select
            v-model="selection_parent_id"
            label="label"
            :options="categoriesLabels"
            id="parent_id"
            name="parent_id"
            class="form-control admin_control_input editable_field"
            placeholder="Select option"
            data-cy='select-input'
    ></v-select>

I tried to add line in cypress test :

    cy.get('[data-cy=select-input]').select('1')

and got error :

    CypressError: cy.select() can only be called on a <select>. Your subject is a: <div dir="auto" class="v-select form-control admin_control_input editable_field vs--single vs--searchable" id="parent_id" name="parent_id" data-cy="select-input">...</div>

I have:

    "vue": "^2.6.10",
    "vue-select": "^3.2.0",
    
    "@vue/cli-plugin-e2e-cypress": "~4.2.0",
    "@vue/cli-plugin-router": "^4.0.0",
    "@vue/cli-plugin-vuex": "^4.0.0",
    "@vue/cli-service": "^4.0.0",
    "bootstrap": "^4.3.1",
    "faker": "^4.1.0",
    "jquery": "^3.4.1",

Is there is a valid way ?

Thanks!

Apr
03
1 month ago
Activity icon

Started a new Conversation How To Make Cypress Different Test Depending On If There Are Rows

Hello, In @vue/cli 4.0.5 app making cypress for a bloc like

            <fieldset class="blocks m-1 p-1">
                <legend class="blocks block-wrapper-for-data-listing">Events&nbsp;</legend>
                <div class="table-responsive table-wrapper-for-data-listing" v-if="taskRow.events.length">

                    <table class="table table-striped table-data-listing">
                        ... <!--- DATA TABLE -->
                    </table>

                </div>

                <p class="alert alert-info m-1 p-1 wrapper-for-no-rows-data-listing" role="alert" v-if="!taskRow.events.length">
                    This task has no events yet!
                </p>

            </fieldset>

I want to make different conditions deending on if there are taskRow.events rows. I made rules when there are taskRow.eventsL :

        var view_event_details_found= false
        cy.get('.block-wrapper-for-data-listing')
            .get('.table-wrapper-for-data-listing')
            .then(listing => {
                alert( '::-1' )
                cy.get('.tr_view_event_details').find('.view_event_details').first().click()
                cy.contains('.modal-title', 'Event Details')
                view_event_details_found= true
            })

        alert( 'view_event_details_found::' + view_event_details_found )
        if (!view_event_details_found) {

        }

I tried when view_event_details_found = false to make other test on search “This task has no events yet!” text.

But I got error :

CypressError: Timed out retrying: Expected to find element: '.table-wrapper-for-data-listing', but never found it.
as without div with “.table-wrapper-for-data-listing” defined.

Which is valid way to make this test ?

Thanks!

Apr
02
1 month ago
Activity icon

Started a new Conversation Invalid Unique Validation With Additive User_id Field

Hello, In Laravel 6 I have table sda_user_props :

id	int(10) unsigned Auto Increment	
user_id	int(10) unsigned	
name	varchar(50)	
value	varchar(255)	
created_at	timestamp [CURRENT_TIMESTAMP]

with UNIQUE Index on fields user_id, name. I want to make a rule with array rules for unique pare user_id, name defined as :

        $userTable = with(new User)->getTable();
        $userPropTable = with(new UserProp)->getTable();
        $validationRulesArray = [
            'user_id' => ['required', "exists:{$userTable},id"],
            'name' => ['required', 'max:50'],
            'value' => ['required', 'max:255'],
        ];

        $validationRulesArray['name'][] =
            Rule::unique($userPropTable)->ignore($user_id, 'user_id')
               ->where(function ($query) use ($user_prop_id) {
                   return $query->where('name', $user_prop_id);
               });

But it does not work as expected. I log rules array and see:

array (
  'user_id' => 
  array (
    0 => 'required',
    1 => 'exists:users,id',
  ),
  'name' => 
  array (
    0 => 'required',
    1 => 'max:50',
    2 => 
    Illuminate\Validation\Rules\Unique::__set_state(array(
       'ignore' => 1,
       'idColumn' => 'user_id',
       'table' => 'user_props',
       'column' => 'NULL',
       'wheres' => 
      array (
      ),
       'using' => 
      array (
        0 => 
        Closure::__set_state(array(
        )),
      ),
    )),
  ),
  'value' => 
  array (
    0 => 'required',
    1 => 'max:255',
  ),
)  

And tracing I see invalid sql :

   SELECT count(*)     AS aggregate 
    FROM `sda_user_props` 
    WHERE `name` = 'A'     AND `user_id` <> '1'     AND (`name` is null) 

I suppose must be condition

`user_id` == '1'  // not <>

and what is this ibvalid condition :

AND (`name` is null) 

where 'A' - is entered text and user_id==1

Which is the valid way ?

Thanks!

Apr
01
1 month ago
Activity icon

Replied to In Vuecli /cypress Testing I I Have Cancelled Error On Post Request

In my top menu after admin successfully logged I show icon with class admin_access_rights So, the code below works for me :

        preventFormSubmitDefault("form")
        cy.get('button')
            .contains('Submit')
            .click()

        cy.wait(1500);
        // cy.wait('#nav_admin');

        cy.get('article').should('have.class', 'page_content_container')

        cy.get('div.top_nav_menu')
            .find('.admin_access_rights')
            .click()

        cy.visit('/admin/categories') // I want to test CRUD APPS

But if there is a way instead of delay in milliseconds, to waite untill some elements woul appear , like :

        // cy.wait(1500);
        cy.wait('#nav_admin');

So code abobe does not work for me...

Mar
31
1 month ago
Activity icon

Replied to In Vuecli /cypress Testing I I Have Cancelled Error On Post Request

Yes, if to comment line

 cy.visit('/admin/dashboard')

then it works. Actually I did not understand why ? I have only 1 redirect to admin/dashboard .

I check and see that any redirect with cy.visit after clicking on "submit" button is cancelled. Can it be salved?

Activity icon

Started a new Conversation In Vuecli /cypress Testing I I Have Cancelled Error On Post Request

Hello, I have @vue/cli 4.0.5 / vuex 3 app with data reading from Laravel 5 Backend REST API and I have problems testing under cypress when on Login form click on “Submit” button, as I have cancelled error : https://prnt.sc/rp71vb

Googling for decision I fround this https://stackoverflow.com/questions/60385480/cypress-canceling-an-api-request-upon-a-form-submit branch

and tried to fix it in tests/e2e/specs/admin_category_crud.js:

import faker from 'faker'
describe('Admin category CRUD functionality', () => {
    it('Category test', () => {
        // cy.visit('/')

        cy.visit('/login')

        const test_email= '[email protected]'
        const test_password= '111111'

        cy.get('#email')
            .clear()
            .type(test_email)
            .should('have.value', test_email)


        cy.get('#password')
            .clear()
            .type(test_password)
            .should('have.value', test_password)


        preventFormSubmitDefault("form")
        cy.get('button')
            .contains('Submit')
            .click()

        cy.visit('/admin/dashboard')

        cy.get('article').should('have.class', 'page_content_container')

    })


})

function preventFormSubmitDefault(selector) {
    // alert( 'preventFormSubmitDefault::' )
    cy.get(selector).then(form$ => {

        // alert( 'form$::' )

        form$.on("submit", e => {
            // alert( 'e::' )
            e.preventDefault();
        });
    });
}

But even caslling preventFormSubmitDefault method I still jave the same error /If to uncomment alerts in preventFormSubmitDefault - I see them, but I am not sure if this method depends on my login form ?

src/views/auth/Login.vue:


<template>
	<article class="page_content_container raised_page_content_container">

		<div class="page_content col-sm-12 col-md-8 p-2 m-0 mx-auto">
			<ValidationObserver ref="loginObserverForm" v-slot="{handleSubmit}">
				<form class="login" @submit.prevent="handleSubmit(onSubmit)">
					<div class="card">

						<h3 class="card-header"><i :class="'i_link '+getHeaderIcon('login')"></i>Login</h3>
						<div class="card-body card-block">

							<dl class="block_2columns_md m-3"> <!-- email FIELD DEFINITION -->

								<dt class="key_values_rows_label_13">
									<label class="col-form-label" for="email">Email:</label>
								</dt>
								<dd class="key_values_rows_value_13">

									<ValidationProvider
											name="Email"
											rules="required|email"
											v-slot="{ errors }"
									>
										<div class="input-group">
											<div class="input-group-addon">
												<i :class="'i_link '+getHeaderIcon('email')"></i>
											</div>
											<input
													v-model="loginData.email"
													name="email"
													id="email"
													class="form-control editable_field"
													placeholder="Your email address"
													autocomplete=off
											>
										</div>

										<p class="input_group_addon_validation_error">{{ clearErrorMessage(errors[0]) }}</p>
									</ValidationProvider>

								</dd>

							</dl> <!-- <dt class="block_2columns_md m-0"> email FIELD DEFINITION -->

							<dl class="block_2columns_md m-3"> <!-- password FIELD DEFINITION -->

								<dt class="key_values_rows_label_13">
									<label class="col-form-label" for="password">Password:</label>
								</dt>
								<dd class="key_values_rows_value_13">

									<ValidationProvider
											name="Password"
											rules="required"
											v-slot="{ errors }"
									>
										<div class="input-group">
											<div class="input-group-addon">
												<i :class="'i_link '+getHeaderIcon('password')"></i>
											</div>

											<input type="password"
											       v-model="loginData.password"
											       id="password"
											       name="password"
											       class="form-control editable_field"
											       placeholder="Your password"
											       autocomplete=off
											>
										</div>

										<p class="input_group_addon_validation_error">{{ clearErrorMessage(errors[0]) }}</p>
									</ValidationProvider>

								</dd>

							</dl> <!-- <dl class="block_2columns_md m-0"> password FIELD DEFINITION -->

						</div> <!-- <div class="card-body card-block"> -->

						<section class="card-footer row_content_right_aligned">
							<button type="reset" class="btn btn-danger btn-sm m-2">
								<i :class="'i_link '+getHeaderIcon('cancel')"></i>Reset
							</button>
							<button type="submit" class="btn btn-success btn-sm m-2 ml-4 mr-4 a_link">
								<i :class="'i_link '+getHeaderIcon('save')"></i>Submit
							</button>
						</section>

						<router-link to="/forgot_password?">Forgot Password?</router-link>

					</div> <!-- <div class="card"> -->

				</form>


				<fieldset class="blocks" v-if="demo_version">
					<legend class="blocks">
						<i :class="getHeaderIcon('demo-info')"></i>Demo info&nbsp;
					</legend>

					<p class="pre-formatted description-text" style="overflow-y: scroll; max-height: 200px; ">
						AAAFor this demo you can use <strong>[email protected]</strong>/<strong>111111</strong> credentials, which has extended admin's and
						manager's
						functionality or<br>
						<strong>[email protected]</strong>/<strong>111111</strong>, which has no extended admin's functionality
					</p>

				</fieldset>


			</ValidationObserver>

		</div> <!-- page_content -->

	</article> <!-- page_content_container -->
</template>

<script>
    import {bus} from '../../../src/main'
    import appMixin from '@/appMixin'

    import {ValidationObserver, ValidationProvider, extend} from 'vee-validate'
    import * as rules from 'vee-validate/dist/rules';

    Object.keys(rules).forEach(rule => {
        extend(rule, rules[rule]);
    });

    export default {
        name: 'loginPage',
        mixins: [appMixin],

        components: {
            ValidationObserver, ValidationProvider
        },

        data() {
            return {
                loginData: {
                    email: '[email protected]',
                    password: '111111'
                },
                demo_version: process.env.VUE_APP_DEMO_VERSION
            }
        },

        created() {
            bus.$on('authLoggedSuccess', (user) => {
                this.$store.dispatch('retrieveTaskAssignedToUsers');
                this.$store.dispatch('retrieveUserSkills');
                this.$store.dispatch('retrieveUserGroups');
                this.showPopupMessage('Login', 'Successful login !', 'success')
	            console.log('-1 authLoggedSuccess::')

	            // this.$router.push({path: '/admin/categories'}); // DEBUGGING
            })

            bus.$on('authLoggedError', () => {
                this.showPopupMessage('Login', 'Login error!', 'warn')
            })
        }, //  created() {

        beforeDestroy() {
            bus.$off('authLoggedSuccess')
            bus.$off('authLoggedError')
        },

        mounted() {
            this.setAppTitle('Authentication', 'Login', bus);
        }, // mounted() {

        methods: {
            onSubmit() {

                this.$refs.loginObserverForm.validate().then(success => {
                    if (!success) {
                        return;
                    }
                    this.$store.dispatch('login', this.loginData)
                        .then(() => this.$router.push('/'))
                        .catch(error => console.log(error))
                    this.$nextTick(() => {
                        this.$refs.loginObserverForm.reset();
                    });
                });
            } // onSubmit

        }, // methods: {

    }

</script>

When I test the app in browser it works ok ?

How can it be fixed ?

    "axios": "^0.19.0",
    "core-js": "^3.3.2",
    "vue": "^2.6.10",
    "vuex": "^3.0.1"
    ...
    "@vue/cli-plugin-e2e-cypress": "~4.2.0",

Thanks!

Mar
29
2 months ago
Activity icon

Started a new Conversation Vue/cli App Running Dev Mode Periodically Stops React To My Modifications

Hello, working with @vue/cli 4.0.5 in dev mode I periodically see that my browsers stops react to my modifications in my PhpStorm 2019.2.3 when command

yarn run serve
is run

The same issue with

npm run serve

In the console (Kubuntu 18.04) I see :

 DONE  Compiled successfully in 6951ms                                                                                                        3:07:23 PM


  App running at:
  - Local:   http://localhost:8080/ 
  - Network: unavailable

  Note that the development build is not optimized.
  To create a production build, run yarn build.

and to apply modifications of my files I have to exit the console with CTRL+C and run again :

yarn run serve

I checked and see this is not browser's problem , as I have it in many browsers. In package.json :

{
  "name": "ctasks",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "serve": "vue-cli-service serve",
    "build": "vue-cli-service build",
    "lint": "vue-cli-service lint"
  },
  "dependencies": {
    "axios": "^0.19.0",
    "babel-helper-vue-jsx-merge-props": "^2.0.3",
    "core-js": "^3.3.2",
    "file-saver": "^2.0.2",
    "font-awesome": "^4.7.0",
    "moment": "^2.24.0",
    "moment-timezone": "^0.5.27",
    "v-money": "^0.8.1",
    "vee-validate": "^3.1.0",
    "vue": "^2.6.10",
    "vue-avatar": "^2.1.8",
    "vue-focus": "^2.1.0",
    "vue-js-modal": "^1.3.31",
    "vue-nav-tabs": "^0.5.7",
    "vue-notification": "^1.3.20",
    "vue-router": "^3.1.3",
    "vue-select": "^3.2.0",
    "vue-the-mask": "^0.11.1",
    "vue-upload-component": "^2.8.20",
    "vue-wysiwyg": "^1.7.2",
    "vue2-datepicker": "^3.3.0",
    "vue2-filters": "^0.8.0",
    "vuex": "^3.0.1"
  },
  "devDependencies": {
    "@vue/cli-plugin-babel": "^4.0.0",
    "@vue/cli-plugin-router": "^4.0.0",
    "@vue/cli-plugin-vuex": "^4.0.0",
    "@vue/cli-service": "^4.0.0",
    "bootstrap": "^4.3.1",
    "jquery": "^3.4.1",
    "node-sass": "^4.12.0",
    "popper.js": "^1.16.0",
    "sass-loader": "^8.0.0",
    "vue-template-compiler": "^2.6.10",
    "vue2-collapse": "^1.0.15"
  }

I found some commands to check ports :

sudo lsof -i -P -n | grep LISTEN
systemd       1            root   60u  IPv6  17395      0t0  TCP *:6600 (LISTEN)
apache2     937        www-data    4u  IPv6  27488      0t0  TCP *:80 (LISTEN)
systemd-r   993 systemd-resolve   13u  IPv4  22192      0t0  TCP 127.0.0.53:53 (LISTEN)
apache2    1203        www-data    4u  IPv6  27488      0t0  TCP *:80 (LISTEN)
cupsd      1312            root    6u  IPv6  25197      0t0  TCP [::1]:631 (LISTEN)
cupsd      1312            root    7u  IPv4  25198      0t0  TCP 127.0.0.1:631 (LISTEN)
apache2    1473        www-data    4u  IPv6  27488      0t0  TCP *:80 (LISTEN)
apache2    1506        www-data    4u  IPv6  27488      0t0  TCP *:80 (LISTEN)
mpd        1595             mpd    4u  IPv6  17395      0t0  TCP *:6600 (LISTEN)
sshd       1682            root    3u  IPv4  33180      0t0  TCP *:22 (LISTEN)
sshd       1682            root    4u  IPv6  33182      0t0  TCP *:22 (LISTEN)
mysqld     1714           mysql   43u  IPv4  27532      0t0  TCP 127.0.0.1:3306 (LISTEN)
apache2    2524            root    4u  IPv6  27488      0t0  TCP *:80 (LISTEN)
apache2    2539        www-data    4u  IPv6  27488      0t0  TCP *:80 (LISTEN)
teamviewe  3015            root   11u  IPv4  30448      0t0  TCP 127.0.0.1:5939 (LISTEN)
docker-pr  3356            root    4u  IPv6  30714      0t0  TCP *:8089 (LISTEN)
kdeconnec  3859           serge   14u  IPv6  34329      0t0  TCP *:1716 (LISTEN)
ktorrent   3966           serge   18u  IPv6  35381      0t0  TCP *:6881 (LISTEN)
dropbox    4020           serge   99u  IPv4  40312      0t0  TCP 127.0.0.1:17600 (LISTEN)
dropbox    4020           serge  105u  IPv4  41567      0t0  TCP 127.0.0.1:17603 (LISTEN)
java       7527           serge  222u  IPv4  53080      0t0  TCP 127.0.0.1:6942 (LISTEN)
java       7527           serge  397u  IPv4  55373      0t0  TCP 127.0.0.1:63342 (LISTEN)
apache2   11583        www-data    4u  IPv6  27488      0t0  TCP *:80 (LISTEN)
apache2   11587        www-data    4u  IPv6  27488      0t0  TCP *:80 (LISTEN)
node      15154           serge   23u  IPv4 516204      0t0  TCP *:8080 (LISTEN)
apache2   26577        www-data    4u  IPv6  27488      0t0  TCP *:80 (LISTEN)
apache2   26594        www-data    4u  IPv6  27488      0t0  TCP *:80 (LISTEN)
apache2   28504        www-data    4u  IPv6  27488      0t0  TCP *:80 (LISTEN)


# sudo netstat -tulpn | grep LISTEN                                                                  
tcp        0      0 127.0.0.1:3306          0.0.0.0:*               LISTEN      1714/mysqld         
tcp        0      0 127.0.0.1:63342         0.0.0.0:*               LISTEN      7527/java           
tcp        0      0 0.0.0.0:8080            0.0.0.0:*               LISTEN      15154/node          
tcp        0      0 127.0.0.1:5939          0.0.0.0:*               LISTEN      3015/teamviewerd    
tcp        0      0 127.0.0.53:53           0.0.0.0:*               LISTEN      993/systemd-resolve 
tcp        0      0 0.0.0.0:22              0.0.0.0:*               LISTEN      1682/sshd           
tcp        0      0 127.0.0.1:631           0.0.0.0:*               LISTEN      1312/cupsd          
tcp        0      0 127.0.0.1:6942          0.0.0.0:*               LISTEN      7527/java           
tcp        0      0 127.0.0.1:17600         0.0.0.0:*               LISTEN      4020/dropbox        
tcp        0      0 127.0.0.1:17603         0.0.0.0:*               LISTEN      4020/dropbox        
tcp6       0      0 :::6600                 :::*                    LISTEN      1/init              
tcp6       0      0 :::80                   :::*                    LISTEN      937/apache2         
tcp6       0      0 :::1716                 :::*                    LISTEN      3859/kdeconnectd    
tcp6       0      0 :::22                   :::*                    LISTEN      1682/sshd           
tcp6       0      0 ::1:631                 :::*                    LISTEN      1312/cupsd          
tcp6       0      0 :::8089                 :::*                    LISTEN      3356/docker-proxy   
tcp6       0      0 :::6881                 :::*                    LISTEN      3966/ktorrent       

# sudo lsof -i:8080
COMMAND     PID  USER   FD   TYPE DEVICE SIZE/OFF NODE NAME
chromium-  7577 serge   47u  IPv4 520534      0t0  TCP localhost:48192->localhost:http-alt (ESTABLISHED)
node      15154 serge   23u  IPv4 516204      0t0  TCP *:http-alt (LISTEN)
node      15154 serge   30u  IPv4 520535      0t0  TCP localhost:http-alt->localhost:48192 (ESTABLISHED)
# sudo nmap -sTU -O localhost:8080 

Starting Nmap 7.60 ( https://nmap.org ) at 2020-03-26 15:18 EET
Failed to resolve "localhost:8080".
WARNING: No targets were specified, so 0 hosts scanned.
Nmap done: 0 IP addresses (0 hosts up) scanned in 0.19 seconds

But I do not know is there is something usefull in these info and can be helpfull my problem ?

Thanks!

Mar
28
2 months ago
Activity icon

Replied to Making Bootstrap Datetimepicker To Select Only Time Got Invalid Date Format Error

Yes, I payed attention at this. But which of them is corresponding to this https://eonasdan.github.io/bootstrap-datetimepicker/#time-only which I have to iuse and looks like I have to remove the rest ?

Activity icon

Started a new Conversation Making Bootstrap Datetimepicker To Select Only Time Got Invalid Date Format Error

Hello, In laravel 6, Bootstrap / Jquery app I want to make bootstrap-datetimepicker with time only selection as in this https://eonasdan.github.io/bootstrap-datetimepicker/#time-only example

and with blade code :

                <div class="form-group row">
                    <label class="col-form-label col-md-6">Time<small>(utc) </small></label>
                    <div class="col-md-6">
                        <div class="input-group date" id="time_utc">
                            <input type="text" class="form-control"/>
                            <span class="input-group-addon">
                                <span class="glyphicon glyphicon-time"></span>
                            </span>
                        </div>
                    </div>
                </div>

I open modal with several fields and datetimepicker, which I want to show only as time picker (as in link above):

  $('#add_noon_report').on('click', function () {
    $('#add_noon_report_lat').val('')
    $('#add_noon_report_lng').val('')
    $('#add_noon_report_lat_degrees').val('')
    ...
    $('#datereported_utc').val('')
    $('#time_utc').val('6:20')  // I TRIED DIFFERENT FORMAT OF DEFAULT VALUE - BUT EMPTY PREDERABLE
    // $('#time_utc').val('6:20 PM')
    // $('#time_utc').val(null)



    $('#add-noon-report-modal').modal('toggle')
    $('#datereported_utc').datetimepicker({
      todayHighlight: true,
      autoclose: true,
      format: 'yyyy-mm-dd hh:ii'
    }).on('change', function () {
    })

    $('#time_utc').datetimepicker({
      format: 'LT'
    });

  }); // $('#add_noon_report').on('click', function () {

But I got error in console :

app.js:10140 Uncaught Error: Invalid date format.
    at Object.parseFormat (app.js:10140)
    at new Datetimepicker (app.js:8655)
    at HTMLDivElement.<anonymous> (app.js:10043)
    at Function.each (app.js:69700)
    at jQuery.fn.init.each (app.js:69535)
    at jQuery.fn.init.$.fn.datetimepicker (app.js:10038)
    at HTMLButtonElement.<anonymous> (trip-details.js:1078)
    at HTMLButtonElement.dispatch (app.js:74570)
    at HTMLButtonElement.elemData.handle (app.js:74377)

In package.json I have :

        "jquery": "^3.3.1",
        "jquery-form": "^4.2.2",
        "jquery-ui": "^1.12.1",
        "jquery-validation": "1.19.0",


        "bootstrap": "^4.4.1",
        "bootstrap-datepicker": "^1.8.0",
        "bootstrap-daterangepicker": "^3.0.3",
        "bootstrap-datetime-picker": "^2.4.4",
        "bootstrap-datetimepicker": "^0.0.7",

Any ideas how to fix this error ?

Mar
27
2 months ago
Activity icon

Started a new Conversation Why Rollback Raise Cannot Drop Index Error?

Hello, in my laravel 5.7 app I need to add table and reference in other table to created table. I made 2 migration files and migrate command runs ok

but running rollback I have an error :

$ php artisan migrate
Migrating: 2020_03_08_162307_create_colors_table
Migrated:  2020_03_08_162307_create_colors_table
Migrating: 2020_03_08_162642_add_color_storage_spaces_table
Migrated:  2020_03_08_162642_add_color_storage_spaces_table
[email protected]:/mnt/_work_sdb8/wwwroot/lar/BoxBooking2$ php artisan migrate:rollback
Rolling back: 2020_03_08_162642_add_color_storage_spaces_table

   Illuminate\Database\QueryException  : SQLSTATE[HY000]: General error: 1553 Cannot drop index 'storage_spaces_color_id_foreign': needed in a foreign key constraint (SQL: alter table `storage_spaces` drop index `storage_spaces_color_id_foreign`)

  at /mnt/_work_sdb8/wwwroot/lar/BoxBooking2/vendor/laravel/framework/src/Illuminate/Database/Connection.php:664
    660|         // If an exception occurs when attempting to run a query, we'll format the error
    661|         // message to include the bindings with SQL, which will make this exception a
    662|         // lot more helpful to the developer instead of just the database's errors.
    663|         catch (Exception $e) {
  > 664|             throw new QueryException(
    665|                 $query, $this->prepareBindings($bindings), $e
    666|             );
    667|         }
    668| 

  Exception trace:

  1   Doctrine\DBAL\Driver\PDOException::("SQLSTATE[HY000]: General error: 1553 Cannot drop index 'storage_spaces_color_id_foreign': needed in a foreign key constraint")
      /mnt/_work_sdb8/wwwroot/lar/BoxBooking2/vendor/doctrine/dbal/lib/Doctrine/DBAL/Driver/PDOStatement.php:119

  2   PDOException::("SQLSTATE[HY000]: General error: 1553 Cannot drop index 'storage_spaces_color_id_foreign': needed in a foreign key constraint")
      /mnt/_work_sdb8/wwwroot/lar/BoxBooking2/vendor/doctrine/dbal/lib/Doctrine/DBAL/Driver/PDOStatement.php:117

  Please use the argument -v to see more details.

The files are :

 2020_03_08_162307_create_colors_table.php :
 <?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateColorsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('colors', function (Blueprint $table) {
            $table->smallIncrements('id');
            $table->string('color', 10)->unique();
            $table->string('title', 50)->unique();
            $table->enum('status', [ 'BU', 'UDL', 'UBPNCI', 'R'     , 'NPC'  , 'AUWN' , 'A'  ])->nullable()->comment(', BU=>Booked Units / Client Checked-In already, UDL=>Units Double Locked, UBPNCI - Unit Booked/Paid, not check-in, R - Reserved, AUWN - Available Units with notes (For repair, with water leakage, under maintenance & etch...), NPC - Non Paying Clients,    A=>Available');

            $table->timestamp( 'created_at')->useCurrent();
        });
        Artisan::call('db:seed', array('--class' => 'AdColorsWithInitData'));
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('colors');
    }
}

2020_03_08_162642_add_color_storage_spaces_table.php:

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class AddColorStorageSpacesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {

        Schema::table('storage_spaces', function (Blueprint $table) {
            $table->smallInteger(   'color_id'  )->unsigned()->nullable()->after("status");
            $table->foreign(   'color_id'  )->references('id')->on('colors')->onDelete('RESTRICT');

        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('storage_spaces', function (Blueprint $table) {
            $sm = Schema::getConnection()->getDoctrineSchemaManager();
            $indexesFound = $sm->listTableIndexes('storage_spaces');

            if(array_key_exists("storage_spaces_color_id_foreign", $indexesFound)) {
                $table->dropUnique("storage_spaces_color_id_foreign");
            }

            $table->dropColumn('color_id');
        });

    }
}

I tried to remove storage_spaces_color_id_foreign in down method, but failed.

Which is the valid way ?

Thanks!

Mar
25
2 months ago
Activity icon

Started a new Conversation Using Leaflet.PolylineDecorator I Got Read Property 'dash' Of Undefined

Hello, In Laravel 6/blade/jquery 3/leaflet app I want to add direction icons to Polyline with https://github.com/bbecquet/Leaflet.PolylineDecorator I installed it with npm and in resources/js/app.js I imported leaflet:

require('./bootstrap');

require('jquery');

window.Vue = require('vue');
export const bus = new Vue()

import 'leaflet-polylinedecorator';
import 'leaflet-rotatedmarker';

But I got error

 Cannot read property 'dash' of undefined

trying to use in blade form example :

@section('scripts')

    <link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/leaflet.css"
          integrity="sha512-xwE/Az9zrjBIphAcBb3F6JVqxf46+CDLwfLMHloNu6KEQCAWi6HcDUbeOfBIptF7tcCzusKFjFw2yuvEpDL9wQ=="
          crossorigin=""/>
    <script src="https://unpkg.com/[email protected]/dist/leaflet.js"
            integrity="sha512-gZwIG9x3wUXg2hdXF6+rVkLF/0Vi9U8D2Ntg4Ga5I5BZpVkVxlJWbSQtXPSiUTtC0TjtGOmxa1AJPuV0CPthew=="
            crossorigin=""></script>

 
    <script>

 
            var polyline = new L.Polyline(polylinePoints, {
            });
            polyline.addTo(mymap);
             var decorator = L.polylineDecorator(polyline, {
                patterns: [
                    {offset: 0, repeat: 20, symbol: L.Symbol.dash({pixelSize: 10})}
                ]
            }).addTo(mymap);

            // zoom the map to the polyline
            mymap.fitBounds(polyline.getBounds());

In console I see that L.Symbol is undefined. What did I miss ?

Thanks!

Mar
22
2 months ago
Activity icon

Started a new Conversation How Pass More Param To EditColumn Method

Hello, in my laravel 5.7 app with yajra/laravel-datatables-oracle 8 in control I need to add more parameters to editColumn method and I failed like with wrong syntax:

      $colorsCollection            = Color
           ::orderBy('colors.title', 'asc')
           ->get();

       $datatablesCollection = Datatables
           ::of($storageSpacesCollection ) using ($colorsCollection)

           ...

           ->editColumn('id', function ($storageSpace) with ($colorsCollection){
               $current_storage_space_color = '';
               $current_storage_space_title = '';
/*                $colorsCollection            = Color
                   ::orderBy('colors.title', 'asc')
                   ->get();*/

How can I do this ? Thanks!