trifek

trifek

Member Since 1 Year Ago

Experience Points
4,570
Total
Experience

430 experience to go until the next level!

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

  • Complete a lesson — 100pts
  • Create a forum thread — 50pts
  • Reply to a thread — 10pts
  • Leave a reply that is liked — 50pts
  • Receive a "Best Reply" award — 500pts
Lessons Completed
0
Lessons
Completed
Best Reply Awards
0
Best Reply
Awards
  • start 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.

  • community-pillar Created with Sketch.

    Community Pillar

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

Level 1
4,570 XP
Nov
19
2 weeks ago
Activity icon

Replied to Search Results In Laravel

Can I use it in "normal" mysql without additional components / software etc (normal hosting)?

Nov
18
2 weeks ago
Activity icon

Replied to Search Results In Laravel

It's help. This code working. Thank you :)

Activity icon

Replied to Search Results In Laravel

error: "message": "Argument 1 passed to App\Http\Controllers\Cms\ProductController::App\Http\Controllers\Cms\{closure}() must be an instance of App\Http\Controllers\Cms\Builder, instance of Kalnoy\Nestedset\QueryBuilder given, called in /var/www/psCMS2/www/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Builder.php on line 238", "exception": "TypeError",

Activity icon

Replied to Search Results In Laravel

No, I haven't result :(

Activity icon

Replied to Search Results In Laravel

$searchWords = explode(' ', $request->search);

        $categories = Category::select('id', 'value')
            ->where(function($query, $searchWords) {
                foreach ($searchWords as $word)
                {
                    $query->where('value', 'like', '%'.$word.'%');
                }
            })
            ->active()
            ->orderby('value', 'asc')
            ->get();

It's return: { "message": "Too few arguments to function App\Http\Controllers\Cms\ProductController::App\Http\Controllers\Cms\{closure}(), 1 passed in /var/www/psCMS2/www/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Builder.php on line 238 and exactly 2 expected", "exception": "ArgumentCountError",

Activity icon

Replied to Search Results In Laravel

this is not working :(

Activity icon

Replied to Search Results In Laravel

exactly :) All words or a part of them (volkswagen => volk)

Activity icon

Replied to Search Results In Laravel

yes. The user can enter more than 2 words (or 1)

Activity icon

Started a new Conversation Search Results In Laravel

Hi, I have small problem.

I have this code:

public function getSelect2(Category $category, Request $request)
    {
        $searchQuery = str_replace(' ', '%', $request->search);

        if (strlen($request->search) < 4) {
            return [];
        }


        $categories = Category::select('id', 'value')
            ->orWhere('value', 'like', '%' . $searchQuery . '%')
            ->active()
            ->orderby('value', 'asc')
            ->get();
}

I have record in my DB: 'volkswagen drzwi'. When I have string: volk drzwi - I have result.

When I have string: drzwi volk - I have no results.

How can I repair my code?

Please help me

Nov
06
3 weeks ago
Activity icon

Started a new Conversation Displaying An Image While The Movie Is Loading

Hi, I am beginner webdeveloper. I have a problem with the movie on the website, the movie takes about 15MB and it takes a long time to load on GSM connections. I know it can be compressed - I already did that. Now I want to display an image on the website, and when the movie is loaded, I hide the image and display the movie.

I made a code like this:

    <div class="cover-video cover-video-splash">
      <video width="100%" height="1080" autoplay loop muted class="cover-video-splash-video">
        <source src="{{ES::asset('/assets/front/videos/header/hp.mp4')}}" type='video/mp4'>
        <source src="{{ES::asset('/assets/front/videos/header/hp.webm')}}" type='video/webm' >
        <source src="{{ES::asset('/assets/front/videos/header/hp.ogv')}}" type='video/ogg; codecs="theora, vorbis"'/>
        <p>@lang('main.no-video')</p>
      </video>
    
    </div>
    
    
    
    <style>
      .cover-video-splash{
          background-image: url('/assets/front/videos/header/splash.jpg');
          height: 1070px;
          background-position: center;
          background-repeat: no-repeat;
          background-size: cover;
      }
    </style>
    
    $( document ).ready(function() {
      $(".cover-video-splash-video").on("loadstart", function() {
        this.show();
      });
    });

But it doesn't really work because fiom freezes the page anyway. How can this be on

Nov
05
4 weeks ago
Activity icon

Replied to Calculating The Time Difference In Laravel

I am doing some old course :(

Activity icon

Started a new Conversation Calculating The Time Difference In Laravel

Hi, I am beginner webdeveloper.

I make my website in Laravel 5.8.

This is my Model and migration:

    class Timecycle extends Model
    {
    
        protected $fillable = [
            'case_id',
            'timecycleable_id',
            'timecycleable_type',
            'status',
            'worked_time'
        ];
    
        protected $casts = [
            'id' => 'int',
            'case_id' => 'int',
        ];
    
        protected $dates = [
            'created_at',
            'updated_at'
        ];
    
        public function stopwatch()
        {
            return $this->morphTo();
        }
    
    
    Schema::create('timecycles', function (Blueprint $table) {
                $table->increments('id');
                $table->integer('timecycleable_id');
                $table->string('timecycleable_type');
                $table->integer('case_id')->unsigned();
                $table->foreign('case_id')->references('id')->on('case_instances')->onDelete('cascade');
                $table->boolean('status')->default(0);
                $table->integer('worked_time')->default(0);
                $table->timestamps();
            });

Controller:

    public function sync()
    {
        $activeStopwatches = $this->getActiveStopwatches();
        foreach ($activeStopwatches as $activeStopwatch) {
            foreach ($activeStopwatch->timeCycle as $timeCycle) {
                $newTime = now() - $timeCycle->updated_at;
                $timeCycle->update(['worked_time' => $timeCycle->worked_time + $newTime]);
            }
        }
    }
    
    public function getActiveStopwatches()
        {
            return $this->stopwatch::with(['timeCycle' => function ($q) {
                $q->where('status', 1);
            }, 'caseInstance'])
                ->where('user_id', Auth()->user()->id)
                ->whereHas('timeCycle', function ($q) {
                    $q->where('status', 1);
                })
                ->get();
        }

I have a method that displays the current stopwatches: getActiveStopwatches. Works correctly. In the sync () function, I'd like to update the worked_time. So: current time - last update date, save the result to worked_time.

Is this entry for calculations correct? The time I want to save (the $ newTime variable) is to be expressed in seconds.

Please help me

Nov
03
1 month ago
Activity icon

Started a new Conversation How To Install A Classy JS Script On A Page?

Hi, I am beginner webdeveloper. I have small problem with installation JS on webpage.

I add on my webpage:

    <script type="module" src="{{ES::asset('assets/front/plugins/analytics-manager/event-bus.js')}}"></script>
        <script type="module" src="{{ES::asset('assets/front/plugins/analytics-manager/analytics-manager.js')}}"></script>

My code:

  1. analytics-manager.js:
    import EventBus from "./event-bus.js";
    
    class AnalyticsManager {
        constructor() {
            this._bus = EventBus;
            this._listeners = {
                gtag: null,
                fbq: null
            };
            this._stacks = {
                gtag: [],
                fbq: []
            };
            this._data = {};
        }
    
    
        bootstrap() {
            this._data = this._extractData();
            this._checkIfPresent('gtag', true);
            this._checkIfPresent('fbq', true);
    
            this._bus.on('analytics-manager.push', (...payload) => this.send(...payload));
    
            return this;
        }
    
    
        send(dataId) {
            if (typeof this._data[dataId] === 'undefined') {
                return;
            }
    
            this._pushFbq(this._data[dataId]);
            this._pushGtag(this._data[dataId]);
        }
    
        _pushFbq(data) {
            if (!this._listeners.fbq) {
                this._stacks.fbq.push(data);
                return this;
            }
    
            let payload = {};
    
            payload[data.category] = data.label;
            this._listeners.fbq('trackCustom', data.action, payload);
    
            return this;
        }
    
    
        _pushGtag(data) {
            if (!this._listeners.gtag) {
                this._stacks.gtag.push(data);
                return this;
            }
            let payload = {
                event_category: data.category,
                event_label: data.label
            };
    
            if (data.value !== undefined && data.value !== null) {
                payload.value = data.value;
            }
    
            this._listeners.gtag('event', data.action, payload);
    
            return this;
        }
    
    
        _checkIfPresent(listener, recheck = false, delay = 500) {
            if (typeof this._listeners[listener] === 'undefined') {
                return this;
            }
    
            if (typeof window[listener] === 'function') {
                this._listeners[listener] = window[listener];
    
                while (this._stacks[listener].length) {
                    this.send(this._stacks[listener].shift());
                }
            } else if (recheck) {
                this._delayedCheckIfPresent(listener, 500);
            }
    
            return this;
        }
    
    
        _delayedCheckIfPresent(listener, delay = 500) {
            window.setTimeout(() => {
                this._checkIfPresent(listener, true, delay * 2);
            }, delay);
        }
    
        _extractData() {
            try {
                return JSON.parse(
                    document.querySelector('script[type="application/json"][id="analytics-data"]').textContent
                );
            } catch (e) {
                return {};
            }
        }
    }
    
    EventBus.on('filter-selected.checkbox', (element) => {
        const dataId = element.dataset.analyticsId;
    
        if (!dataId) {
            console.warn('Undefined element data id', element);
            return;
        }
    
        if (element.checked) {
            return EventBus.emit('analytics-manager.push', dataId);
        }
    });
    
    EventBus.on('filter-selected.select', (element) => {
        try {
            const option = Array.from(element.options).find(option => option.value.toString() === element.value.toString());
            const dataId = option.dataset.analyticsId;
    
            if (!dataId) {
                console.warn('Undefined element data id', element, option);
                return;
            }
    
            EventBus.emit('analytics-manager.push', dataId);
        } catch (e) {
        }
    });
    
    EventBus.on('filters-expanded', (element) => setTimeout(() => {
        try {
            const isOpen = element.classList.contains('open');
            const dataId = element.dataset.analyticsId;
    
            if (!dataId) {
                console.warn('Undefined element data id', element);
                return;
            }
    
            if (isOpen) {
                EventBus.emit('analytics-manager.push', dataId);
            }
        } catch (e) {
        }
    }, 1000));
    
    window.addEventListener('load', () => {
        const manager = new AnalyticsManager;
    
        manager.bootstrap();
    });
  1. event-bus.js:
    class EventBus {
        constructor() {
            this._events = {}
        }
    
        on (event, callback) {
            if(Array.isArray(event)) {
                event.forEach(ev => this.on(ev, callback));
            } else {
                if(!this._events[event]) {
                    this._events[event] = [];
                }
    
                this._events[event].push(callback);
            }
    
            return this;
        }
    
        once (event, callback) {
            function on () {
                this.off(event, on);
                callback.apply(this, arguments);
            }
    
            on.callback = callback;
            this.on(event, on);
    
            return this;
        }
    
        off (event, callback) {
            if (!arguments.length) {
                this._events = Object.create(null);
                return this;
            }
    
            if(Array.isArray(event)) {
                event.forEach(ev => this.off(ev, callback));
                return this;
            }
    
            let callbacks = this._events[event];
    
            if(!callbacks) {
                return this;
            }
    
            if(!callback) {
                this._events[event] = [];
                return this;
            }
    
            let cb;
            let i = callbacks.length;
    
            while(i--) {
                cb = callbacks[i];
    
                if(cb === callback || cb.fn === callback) {
                    callbacks.splice(i, 1);
                    break;
                }
            }
    
            return this;
        }
    
        emit (event, ...payload) {
            let callbacks = this._events[event];
    
            if(callbacks) {
                callbacks.forEach(callback => callback(...payload))
            }
    
            return this
        }
    
        registerElementListener (element) {
            const [domEvent, busEvent] = (`${element.dataset.eventBus}:`).split(':');
    
            if(!domEvent || !busEvent) {
                console.warn('EventBus DOM Element binding data is incomplete.', element);
                return;
            }
    
            element.addEventListener(domEvent, () => this.emit(busEvent, element));
        }
    }
    
    const bus = new EventBus
    
    document.querySelectorAll('[data-event-bus]').forEach(element => bus.registerElementListener(element))
    
    // export default bus
    export default EventBus

The problem is the error that appears to me after starting the page with the JS script added like this: Uncaught TypeError: EventBus.on is not a function

  • in line: EventBus.on('filter-selected.checkbox', (element) => {

When I comment this I have error: EventBus.on('filter-selected.select', (element) => {

It works fine on another page.

How to fix it? Please help.

Nov
02
1 month ago
Activity icon

Replied to Problem With Search In Laravel Equivalent

Exactly, it's not one string. In the database I have this string: "AUDI - TT - 8N (1998-2006) - UKŁAD WYDECHOWY - ELEMENTY MOCUJĄCE". searches for "audi układ" - but I have no results. Search terms are separated by other words.

I make this code:

public function getSelect2(Category $category, Request $request)
    {
        $searchQuery = str_replace(' ', '%', $request->search);
        if (strlen($searchQuery) < 4) {
            return [];
        }

        $categories = Category::select('id', 'value')
            ->where('category_name', 'like', '%' . $searchQuery . '%')
            ->orWhere('description', 'like', '%' . $searchQuery . '%')
            ->orWhere('keywords', 'like', '%' . $searchQuery . '%')
            ->orWhere('content', 'like', '%' . $searchQuery . '%')
            ->orWhere('value', 'like', '%' . $searchQuery . '%')
            ->active()
            ->orderby('order', 'asc')
            ->get();
        $response = array();
        foreach ($categories as $item) {
            $response[] = array(
                "id" => $item->id,
                "text" => $item->value
            );
        }
        return $response;
    }


It works, but I don't know if it is optimal and will it be a universal solution?

Oct
31
1 month ago
Activity icon

Replied to Problem With Search In Laravel Equivalent

Thank you for your answer. Could it be fixed on my code? Here I have everything in the "value" column. I do not need to search through relations :)

Activity icon

Started a new Conversation Problem With Search In Laravel Equivalent

Hi, I am beginner in Laravel. I use in my project Laravel 8 and MySQL. I have problem with search.

I have this model and migration:

    class Category extends Model
    {
        use ScopeActiveTrait,
            NodeTrait,
            HasSlug,
            SoftDeletes;
    
        protected $guarded = ['id'];
    
        protected $fillable = [
            'category_name',
            'description',
            'keywords',
            'content',
            'enable',
            'photo',
            'order',
            'slug',
            '_lft',
            '_rgt',
            'parent_id',
            'value'
        ];
    
        public $timestamps = false;
    
        protected $dates = [
            'deleted_at'
        ];
    
        protected $casts = [
            'order' => 'integer',
            'enable'=>'boolean'
        ];
    
        /**
         * Get the options for generating the slug.
         */
        public function getSlugOptions() : SlugOptions
        {
            return SlugOptions::create()
                ->generateSlugsFrom('category_name')
                ->slugsShouldBeNoLongerThan(160)
                ->saveSlugsTo('slug');
        }
    
    }
    
    public function up()
        {
            Schema::table('categories', function (Blueprint $table) {
                $table->text('value')->after('parent_id')->nullable();
            });
        }
    
    Schema::create('categories', function (Blueprint $table) {
                $table->id();
                $table->string('category_name', 155);
                $table->string('description', 155)->nullable();
                $table->string('keywords', 155)->nullable();
                $table->longText('content')->nullable();
                $table->boolean('enable')->default(false);
                $table->string('photo', 155)->nullable();
                $table->bigInteger('order')->default(0);
                $table->string('slug', 160)->nullable();
                $table->softDeletes();
                NestedSet::columns($table);
                $table->engine = "InnoDB";
                $table->charset = 'utf8mb4';
                $table->collation = 'utf8mb4_unicode_ci';
            });

I use this component: kalnoy/nestedset.

I have in column categories.value this:

    AUDI - TT - 8N (1998-2006) - UKŁAD WYDECHOWY - ELEMENTY MOCUJĄCE

When I try search in my DB by this:

    public function getSelect2(Category $category, Request $request)
        {
            if ($request->search != '' && strlen($request->search) >= 4) {
                $categories = Category::select('id', 'value')
                    ->where(function ($query) use ($request) {
                        $query->orWhere('category_name', 'like', '%' . $request->search . '%');
                        $query->orWhere('description', 'like', '%' . $request->search . '%');
                        $query->orWhere('keywords', 'like', '%' . $request->search . '%');
                        $query->orWhere('content', 'like', '%' . $request->search . '%');
                        $query->orWhere('value', 'like', '%' . $request->search . '%');
                    })->active()
                    ->orderby('order', 'asc')
                    ->get();
                $response = array();
                foreach ($categories as $item) {
                    $response[] = array(
                        "id" => $item->id,
                        "text" => $item->value
                    );
                }
                return $response;
            }
        }

When I write in input: Audi - I have results. When I write: 'audi układ' - i haven't result :(

How can I repair it?

Oct
28
1 month ago
Activity icon

Replied to How Return Values From Function In Php And Laravel

yes, I have. problem with result in outside my function. When I run yours code I have: []

When I run this code:

$categories = Category::select('id', 'category_name')
                ->orWhere('category_name', 'like', '%' . $request->search . '%')
                ->orWhere('description', 'like', '%' . $request->search . '%')
                ->orWhere('keywords', 'like', '%' . $request->search . '%')
                ->orWhere('content', 'like', '%' . $request->search . '%')
                ->orWhere('path', 'like', '%' . $request->search . '%')
                ->active()
                ->chunk(500, function ($categories) {
                    foreach ($categories as $item) {
                        $response[] = [
                            "id" => $item->id,
                            "category_name" => $item->category_name
                        ];
                        dd($response);
                    }
                });

in dd i have result. I need this outside

Activity icon

Replied to How Return Values From Function In Php And Laravel

Thank you :) I have very large DB and I better performance I try use chunk(). it's a good idea?

Activity icon

Started a new Conversation How Return Values From Function In Php And Laravel

Hi I make my project in Laravel 8. I have this code:

$categories = $category->orderby('order', 'asc')
                ->select('id', 'category_name')
                ->where('category_name', 'like', '%' . $request->search . '%')
                ->orWhere('description', 'like', '%' . $request->search . '%')
                ->orWhere('keywords', 'like', '%' . $request->search . '%')
                ->orWhere('content', 'like', '%' . $request->search . '%')
                ->orWhere('path', 'like', '%' . $request->search . '%')
                ->active()
                ->chunk(500, function ($categories) {
                    $response = array();
                    foreach ($categories as $item) {
                         $response[] = array(
                            "id" => $item->id,
                            "category_name" => $item->category_name,
//                            "path" => $item->path
                        );
                    }
                });
            dd($categories);

I need save records to categories. I have 100 records, but in. DD it's not visible.

How can I repair it?

Activity icon

Started a new Conversation Laravel Equivalent Allowed Memory Size Of 268435456 Bytes Exhausted (tried To Allocate 76546048 Bytes)

Hi, I have problem with Laravel. I have project in Laravel 8. In my DB table I have 167.000 records. I have https://www.jstree.com on my webpage and I must generate for this component json.

I make this code:


public function categoryTree(Category $category, SelectedProductCategory $selectedProductCategory, Request $request)
    {
        $tree = Cache::remember('categories', 31536000, function () use ($category) {
            return $category->select(['id', 'category_name', 'parent_id', 'order', '_lft', '_rgt'])->active()->orderBy('order', 'ASC')->get();
        });

        $nodes = $this->generateJsTree($tree->toTree(), ($request->exists('id')) ? $selectedProductCategory->where('product_id', $request->input('id'))->orderBy('id', 'ASC')->get() : null);
        return $nodes;

    }


    private function generateJsTree($nodes, $selectedCategories): array
    {
        $categoryArray = array();
        $traverse = function ($categories, $prefix = '-') use (&$traverse, &$categoryArray, $selectedCategories) {
            foreach ($categories as $category) {
                $selected = false;
                if (!is_null($selectedCategories)) {
                    $selected = $selectedCategories->contains('category_id', $category->id) ? true : false;
                }

                $categoryArray[] = ['id' => $category->id, 'text' => $category->category_name, 'parent' => $category->parent_id ?? '#', 'state' => ['opened' => false, 'selected' => $selected]];
                $traverse($category->children, $prefix . '-');
            }
        };
        $traverse($nodes);
        return $nodes;
    }

Works fine when I do not have a full database, when I have all 167,000 records, it displays an error: [2020-10-28 16:30:27] local.ERROR: Allowed memory size of 268435456 bytes exhausted (tried to allocate 76546048 bytes ) {"userId": 1, "exception": "[object] (Symfony \ Component \ ErrorHandler \ Error \ FatalError (code: 0): Allowed memory size of 268435456 bytes exhausted (tried to allocate 76546048 bytes) at /var/www/project/www/vendor/laravel/framework/src/Illuminate/Cache/FileStore.php:74)

My migration and model:

class Category extends Model
{
    use ScopeActiveTrait,
        NodeTrait,
        HasSlug,
        SoftDeletes;

    protected $guarded = ['id'];

    protected $fillable = [
        'category_name',
        'description',
        'keywords',
        'content',
        'enable',
        'photo',
        'order',
        'slug',
        '_lft',
        '_rgt',
        'parent_id'
    ];

    public $timestamps = false;

    protected $dates = [
        'deleted_at'
    ];

    protected $casts = [
        'order' => 'integer',
        'enable'=>'boolean'
    ];

    /**
     * Get the options for generating the slug.
     */
    public function getSlugOptions() : SlugOptions
    {
        return SlugOptions::create()
            ->generateSlugsFrom('category_name')
            ->slugsShouldBeNoLongerThan(160)
            ->saveSlugsTo('slug');
    }

}


Schema::create('categories', function (Blueprint $table) {
            $table->id();
            $table->string('category_name', 155);
            $table->string('description', 155)->nullable();
            $table->string('keywords', 155)->nullable();
            $table->longText('content')->nullable();
            $table->boolean('enable')->default(false);
            $table->string('photo', 155)->nullable();
            $table->bigInteger('order')->default(0);
            $table->string('slug', 160)->nullable();
            $table->softDeletes();
            NestedSet::columns($table);
            $table->engine = "InnoDB";
            $table->charset = 'utf8mb4';
            $table->collation = 'utf8mb4_unicode_ci';
        });

How can I repair it? Please help me.

Activity icon

Replied to Dynamically Added Elements To The Page Do Not Work On The Page

Thanks for your help, it works great :) Is it possible to add something like this: let autoStart = 1; // if 1 -> auto start watch, 0 = stopped? When a new stopwatch is created and its status is 1 - then the countdown would be automatically activated

Activity icon

Replied to Dynamically Added Elements To The Page Do Not Work On The Page

Thank you for your's answer :) Almost perfect :) https://ibb.co/n7K6Ckr - the stopwatch was created correctly, but it shows 0. When I start it, it actually counts down from 145 seconds. How can I fix it?

Activity icon

Started a new Conversation Dynamically Added Elements To The Page Do Not Work On The Page

Hi, I am beginner webdeveloper. I make on my website stopwatch. My actual page: http://upload.newapp.ovh/jquery.html (working code). I make my project in jQuery.

I am having trouble creating these stopwatches dynamically.

When I uncomment:

    $('#watchgroup').empty();
    $('#watchgroup').append('<span class="basic stopwatch">Case ID: ' + caseId +'</span>');

Then a new stopwatch will be added, but it won't have start buttons etc (adds html - not an interactive stopwatch).

In the startWorkedTimeSeconds variable I have the number of seconds from which the new stopwatch should start. How can I fix my problem?

Please help.

Oct
27
1 month ago
Activity icon

Started a new Conversation Searching For A Laravel Equivalent

Hi, I am beginner webdeveloper. I have small problem my model.

I have this migration and model:


    Schema::create('stopwatches', function (Blueprint $table) {
                $table->increments('id');
                $table->integer('case_id')->unsigned();
                $table->foreign('case_id')->references('id')->on('case_instances')->onDelete('cascade');
                $table->integer('user_id')->unsigned();
                $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
                $table->timestamps();
            });
    
    Schema::create('timecycles', function (Blueprint $table) {
                $table->increments('id');
                $table->integer('timecycleable_id');
                $table->string('timecycleable_type');
                $table->integer('case_id')->unsigned();
                $table->foreign('case_id')->references('id')->on('case_instances')->onDelete('cascade');
                $table->boolean('status')->default(0);
                $table->integer('worked_time')->default(0);
                $table->timestamps();
            });
    
    
    class Stopwatch extends Model
    {
    
        protected $fillable = [
            'case_id',
            'user_id'
        ];
    
        protected $casts = [
            'id' => 'int',
            'case_id' => 'int',
            'user_id' => 'int',
        ];
    
        protected $dates = [
            'created_at',
            'updated_at'
        ];
    
        public function timeCycle()
        {
            return $this->morphMany(Timecycle::class, 'timecycleable');
        }
    
        public function caseInstance()
        {
            return $this->belongsTo(CaseInstance::class, 'case_id');
        }
    
    
    
    
    class Timecycle extends Model
    {
    
        protected $fillable = [
            'case_id',
            'timecycleable_id',
            'timecycleable_type',
            'status',
            'worked_time'
        ];
    
        protected $casts = [
            'id' => 'int',
            'case_id' => 'int',
        ];
    
        protected $dates = [
            'created_at',
            'updated_at'
        ];
    
        public function stopwatch()
        {
            return $this->morphTo();
        }
    
    }

In timecycles I have 2 record with status = 0 and status = 1: https://ibb.co/5vyh316

I need my stopwatches with only one timecycles with status = 1.

I make this code:

    return $this->stopwatch::with(['timeCycle', 'caseInstance'])
                ->where('user_id', Auth()->user()->id)
                ->where('updated_at', '<=', \Carbon\Carbon::now()->subSeconds(30)->toDateTimeString())
                ->whereHas('timeCycle', function ($q) {
                    $q->where('status', 1);
                })
                ->get();

In result I have booth items: https://ibb.co/WnJ58Kc

What's wrong in my code?

How can I repair it?

Please help me.

Activity icon

Started a new Conversation The Number Of Records In The Relation In Laravel

Hi, I am beginner php developer. I have project in Laravel 5.6.

I have 2 migrations:

    class CreateStopwatches extends Migration
    {
        /**
         * Run the migrations.
         *
         * @return void
         */
        public function up()
        {
            Schema::create('stopwatches', function (Blueprint $table) {
                $table->increments('id');
                $table->integer('case_id')->unsigned();
                $table->foreign('case_id')->references('id')->on('case_instances')->onDelete('cascade');
                $table->timestamps();
            });
        }
    
        /**
         * Reverse the migrations.
         *
         * @return void
         */
        public function down()
        {
            Schema::dropIfExists('stopwatches');
        }
    }
    
    
    
    class CreateStopwatchTimeCycles extends Migration
    {
        /**
         * Run the migrations.
         *
         * @return void
         */
        public function up()
        {
            Schema::create('stopwatch_time_cycles', function (Blueprint $table) {
                $table->increments('id');
                $table->morphs('timecycle');
                $table->boolean('status')->default(0);
                $table->integer('worked_time')->default(0);
                $table->timestamps();
            });
        }
    
        /**
         * Reverse the migrations.
         *
         * @return void
         */
        public function down()
        {
            Schema::dropIfExists('stopwatch_time_cycles');
        }
    }

And models:

    class Stopwatch extends Model
    {
    
        protected $fillable = [
            'case_id'
        ];
    
        protected $casts = [
            'id' => 'int',
            'case_id' => 'int',
        ];
    
        protected $dates = [
            'created_at',
            'updated_at'
        ];
    
        public function timeCycle()
        {
            return $this->morphMany(StopWatchTimeCycle::class, 'timecycle');
        }
    
    }
    
    class StopwatchTimeCycle extends Model
    {
    
        protected $fillable = [
            'case_id'
        ];
    
        protected $casts = [
            'id' => 'int',
            'case_id' => 'int',
        ];
    
        protected $dates = [
            'created_at',
            'updated_at'
        ];
    
        public function stopwatch()
        {
            return $this->morphTo();
        }
    
    }

In my controller I need return 1 - when stopwatches has stopwatches_time_cycles. I make this controller:

    public function checkActivity(int $caseId)
        {   
            if (Stopwatch::with(['timeCycle'])->where('case_id', $caseId)->withCount('timeCycle')->first() === 0) {
                return 0;
            } else {
                return 1;
            }
        }

but it's not working correctly. It's always return 1 (I have empty table stopwatch_time_cycles).

How can I repair it?

Please help me

Oct
22
1 month ago
Activity icon

Replied to Displaying Data Retrieved From Json In Laravel

Yes, I have this result in this place:

{
    "data": [
        [
            {
                "id": 1,
                "value": "99.00",
                "settlement_date": "October 2020",
                "loaded_from": "Stan pobrany z systemu BAŁTYKGAZ",
                "img": "img/icons/crm.svg",
                "created_at": "2020-10-21T15:09:22.000000Z"
            },
            {
                "id": 2,
                "value": "109.00",
                "settlement_date": "October 2020",
                "loaded_from": "Zgłoszone przez aplikację",
                "img": "img/icons/cms.svg",
                "created_at": "2020-10-21T17:02:18.000000Z"
            }
        ]
    ]
}
Activity icon

Replied to Displaying Data Retrieved From Json In Laravel

I have this code:

class ArchiveListItemResource extends JsonResource
{

    public function toArray($request)
    {
        $results = [];
        foreach ($this->gasmeterStates as $state) {
            if(isset($state->loaded_from_crm_at)){
                $loadedFrom = 'Stan pobrany z systemu BAŁTYKGAZ';
                $img =  'crm.svg';
            } else {
                $loadedFrom = 'Zgłoszone przez aplikację';
                $img =  'cms.svg';
            }
            $date = DateTime::createFromFormat('Y-m-d', $state->settlement_date->toDateString());

            $results[] = [
                'id' => $state->id,
                'value' => $state->value,
                'settlement_date' => $date->format('F').' '.$date->format('Y'),
                'loaded_from' => $loadedFrom,
                'img' => 'img/icons/'.$img,
                'created_at' => $state->created_at->toDateString()
            ];
        }

        return $results;
    }

}

and controller:

public function list(Request $request)
    {
        $gasmeters = $this->clientRepository->getById(4, ['gasmeters', 'gasmeters.gasmeterStates']);
        return ArchiveListItemResource::collection($gasmeters->gasmeters);
    }
Activity icon

Replied to Displaying Data Retrieved From Json In Laravel

I generated this array by this code:

public function toArray($request)
    {
        $results = [];
        foreach ($this->gasmeterStates as $state) {
            if(isset($state->loaded_from_crm_at)){
                $loadedFrom = 'Stan pobrany z systemu BAŁTYKGAZ';
                $img =  'crm.svg';
            } else {
                $loadedFrom = 'Zgłoszone przez aplikację';
                $img =  'cms.svg';
            }
            $date = DateTime::createFromFormat('Y-m-d', $state->settlement_date->toDateString());

            $results[] = [
                'id' => $state->id,
                'value' => $state->value,
                'settlement_date' => $date->format('F').' '.$date->format('Y'),
                'loaded_from' => $loadedFrom,
                'img' => 'img/icons/'.$img,
                'created_at' => $state->created_at
            ];
        }

        return $results;
    }

maybe here is problem?

This return:

{
    "data": [
        [
            {
                "id": 1,
                "value": "99.00",
                "settlement_date": "October 2020",
                "loaded_from": "Stan pobrany z systemu BAŁTYKGAZ",
                "img": "img/icons/crm.svg",
                "created_at": "2020-10-21T15:09:22.000000Z"
            },
            {
                "id": 2,
                "value": "109.00",
                "settlement_date": "October 2020",
                "loaded_from": "Zgłoszone przez aplikację",
                "img": "img/icons/cms.svg",
                "created_at": "2020-10-21T17:02:18.000000Z"
            }
        ]
    ]
}
Activity icon

Started a new Conversation Displaying Data Retrieved From Json In Laravel

Hi, I am beginner webdeveloper. I use in my project Laravel 8 and Vue.

I have this code:

<template>
    <div class="sm:bg-transparent pt-6 md:mt-16 w-full px-4 md:px-0">
        <h1 class="text-dark text-4xl sm:text-3xl font-medium sm:text-center mb-6">{{ __('Archiwum') }}</h1>


        <preloader
            v-if="isLoadingInProgress"
            class="py-8"
            :class="preloaderClass"
        />

        <div class="text-center" v-if="gasmeters.length == 0 && !isLoadingInProgress">
            {{ __('Nie posiadasz jeszcze żadnych odczytów') }}
        </div>

        <div v-if="gasmeters.length">
            <div class="bg-white rounded border border-stroke flex items-start p-6"
                 v-for="(gasmeter, index) in gasmeters"
                 v-bind:key="`gasmeter-${index}`">
                <div class="mr-6">
                    <img class="mb-2" :src="gasmeters.img"/> {{ gasmeters }}
                </div>
                <div class="w-1/5">
                    <span class="font-bold text-xl text-grey">Lipiec 2020 (#123)</span>
                </div>
                <div class="w-1/5">
                    <span class="font-bold text-xl text-grey">Stan:</span> <span>2120</span>
                </div>
                <div class="w-1/5">
                    <span class="font-bold text-xl text-grey">Data:</span> <span>2020.01.12</span>
                </div>
                <div class="w-1/5">
                    <span class="text-xl">Zgłoszone przez aplikację</span>
                </div>
            </div>
        </div>


    </div>
</template>
<script>
import axios from "axios";
import Preloader from "@/common/components/Preloader";

export default {
    components: {
        Preloader
    },
    mounted() {
        this.loadGasmeters();
    },
    data() {
        return {
            gasmeters: [],
            isLoadingInProgress: false,
        }
    },
    computed: {
        preloaderClass() {
            return this.gasmeters.length > 0
                ? ""
                : "loading--transparent loading--block";
        }
    },
    methods: {
        loadGasmeters() {
            this.isLoadingInProgress = true;

            axios
                .get(route('api.archive.list'))
                .then(response => {
                    this.gasmeters = _.get(response, "data.data", []);
                    console.log(this.gasmeters);
                })
                .catch(error => {
                    console.log(error);
                })
                .then(() => {
                    this.isLoadingInProgress = false;
                });
        },

    }
}
</script>

My php return me:

{
    "data": [
        [
            {
                "id": 1,
                "value": "99.00",
                "settlement_date": "2020-10-20T22:00:00.000000Z",
                "loaded_from": "Stan pobrany z systemu BAŁTYKGAZ",
                "img": "img/icons/crm.svg",
                "created_at": "2020-10-21T15:09:22.000000Z"
            },
            {
                "id": 2,
                "value": "109.00",
                "settlement_date": "2020-10-20T22:00:00.000000Z",
                "loaded_from": "Zgłoszone przez aplikację",
                "img": "img/icons/cms.svg",
                "created_at": "2020-10-21T17:02:18.000000Z"
            }
        ]
    ]
}

I have problem with my part this code:

<div v-if="gasmeters.length">
            <div class="bg-white rounded border border-stroke flex items-start p-6"
                 v-for="(gasmeter, index) in gasmeters"
                 v-bind:key="`gasmeter-${index}`">
                <div class="mr-6">
                    <img class="mb-2" :src="gasmeters.img"/> {{ gasmeters }}
                </div>
                <div class="w-1/5">
                    <span class="font-bold text-xl text-grey">Lipiec 2020 (#123)</span>
                </div>
                <div class="w-1/5">
                    <span class="font-bold text-xl text-grey">Stan:</span> <span>2120</span>
                </div>
                <div class="w-1/5">
                    <span class="font-bold text-xl text-grey">Data:</span> <span>2020.01.12</span>
                </div>
                <div class="w-1/5">
                    <span class="text-xl">Zgłoszone przez aplikację</span>
                </div>
            </div>
        </div>

I want replace my img by img from json, "Lipiec 2020 (#123)" => gasmeters.settlement_date (# gasmeters.id), "Stan: " 2120 => Stan: gasmeters.value

How can I make it?

This: {{ gasmeters }} return me:

[ [ { "id": 1, "value": "99.00", "settlement_date": "2020-10-20T22:00:00.000000Z", "loaded_from": "Stan pobrany z systemu BAŁTYKGAZ", "img": "img/icons/crm.svg", "created_at": "2020-10-21T15:09:22.000000Z" }, { "id": 2, "value": "109.00", "settlement_date": "2020-10-20T22:00:00.000000Z", "loaded_from": "Zgłoszone przez aplikację", "img": "img/icons/cms.svg", "created_at": "2020-10-21T17:02:18.000000Z" } ] ]

Please help me

Oct
21
1 month ago
Activity icon

Replied to Find All Client Values In Laravel Equivalent

Method Illuminate\Database\Eloquent\Collection::gasmeterStates does not exist.

Activity icon

Replied to Find All Client Values In Laravel Equivalent

In gasmeter i have relations:

public function gasmeterStates(){
        return $this->hasMany(GasmeterState::class);
    }
Activity icon

Replied to Find All Client Values In Laravel Equivalent

I have error: Property [gasmeterStates] does not exist on this collection instance.

Activity icon

Replied to Find All Client Values In Laravel Equivalent

I make this:

public function gasmeters()
    {
        return $this->hasManyThrough('App\Models\Gasmeter', 'App\Models\Location');
    }

this. work fine. In result I have all user gasmeter. Is posible in this place get GasmeterState?

Activity icon

Replied to Find All Client Values In Laravel Equivalent

Thank you very much. Better for me is collection in result. I want try use hasManyThrough I make this:

public function gasmetersStates()
    {
        return $this->hasManyThrough(
            'App\Models\GasmeterState',
            'App\Models\Gasmeter',
            'location_id', 
            'gasmeter_id', 
            'id', 
            'id' 
        );
    }

but. I haven's any result :( Why?

Activity icon

Replied to Find All Client Values In Laravel Equivalent

This is my controller:

public function list(int $clientId)
    {
        dd($this->gasmeterStateRepository->gasmeter) ;
    }
Activity icon

Replied to Find All Client Values In Laravel Equivalent

I paste my code. I have relation: 0. Clients

  1. Location: $table->foreignId('client_id')->constrained('clients')->onDelete('cascade'); (Client <->Location)
  2. Gasmeter: $table->foreignId('location_id')->constrained('locations')->onDelete('cascade'); (Location <->Gasmeter)
  3. Gasmeter States: $table->foreignId('gasmeter_id')->constrained('gasmeters')->onDelete('cascade'); (Gasmeter <-> Gasmeter States.

I need all record gasmeter_states for selected client

Activity icon

Started a new Conversation Find All Client Values In Laravel Equivalent

Hi, I am beginner Laravel developer. I have:

  • Clients (my users)
  • Client has many locations
  • Location has many gasmeters
  • gasmeter has many values in databases (reader values).

I have this models:

class Client extends Authenticatable implements Presentable
{
    ...

    protected $fillable = [
        'email',
        'crm_number',
        'email_verified_at',
        'password_assigned_at',
        'verify_token',
        'password',
        'type'
    ];

    protected $hidden = [
        'password',
        'verify_token',
        'remember_token',
    ];

    protected $dates = [
        'password_assigned_at',
        'email_verified_at',
        'created_at',
        'updated_at',
        'deactivated_at',
        'deleted_at',
    ];
...
    
}




class Gasmeter extends Model implements Presentable
{
    use SoftDeletes;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name',
        'location_id',
    ];

    protected $dates = [
        'created_at',
        'updated_at',
        'deleted_at'
    ];

    protected $casts = [
        'location_id' => 'integer'
    ];
....
}



class Location extends Model implements Presentable
{
    use SoftDeletes;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name',
        'client_id',
    ];

    protected $dates = [
        'created_at',
        'updated_at',
        'deleted_at'
    ];

    protected $casts = [
        'client_id' => 'integer'
    ];
....
}



class GasmeterState extends Model implements Presentable
{
    use SoftDeletes;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'gasmeter_id',
        'value',
        'settlement_date',
        'loaded_from_crm_at'
    ];

    protected $dates = [
        'settlement_date',
        'created_at',
        'updated_at',
        'deleted_at'
    ];

    protected $casts = [
        'gasmeter_id' => 'integer',
        'created_at' => 'datetime:Y-m-d H:i ',
        'settlement_date' => 'datetime:Y-m-d ',
    ];
...

}

Migrations:

Schema::create('clients', function (Blueprint $table) {
            $table->id();
            $table->string('email');
            $table->integer('type')->comment('1 - klient indywidualny, 2 - firma');
            $table->string('crm_number')->unique();
            $table->string('password');
            $table->string('verify_token');
            $table->rememberToken();
            $table->timestamp('password_assigned_at')->nullable();
            $table->timestamp('email_verified_at')->nullable();
            $table->timestamps();
            $table->deactivation();
            $table->softDeletes();

            $table->unique(['email', 'deleted_at']);
        });


Schema::create('locations', function (Blueprint $table) {
            $table->id();
            $table->foreignId('client_id')->constrained('clients')->onDelete('cascade');
            $table->string('name');
            $table->timestamps();
            $table->softDeletes();
        });


Schema::create('gasmeters', function (Blueprint $table) {
            $table->id();
            $table->foreignId('location_id')->constrained('locations')->onDelete('cascade');
            $table->string('name');
            $table->timestamps();
            $table->softDeletes();
        });


Schema::create('gasmeter_states', function (Blueprint $table) {
            $table->id();
            $table->foreignId('gasmeter_id')->constrained('gasmeters')->onDelete('cascade');
            $table->decimal('value');
            $table->date('settlement_date');
            $table->timestamp('loaded_from_crm_at')->nullable();
            $table->timestamps();
            $table->softDeletes();
        });

Now I must show all my Client gasmeter_states.

I haven't user_id in table gasmeter_states :(

How can I make it?

Activity icon

Started a new Conversation Create New Main Git Branch In PHP Storm

Hi, I am beginner webdeveloper. I make my project with friends. We use GIT and make commit to separated branch in Develop:

  • develop/add-login
  • develop/add-login-history

etc. I use PHP Storm.

In GitHub i have main branch: develop. Now I need create second main branch: pre-develop and copy files from develop to pre-develop.

How can I make it?

Oct
20
1 month ago
Activity icon

Started a new Conversation Filtering The Product List In Laravel And Vue

Hi, I am beginner webdeveloper. I Make my project in Laravel 8 and Vue. I have product list and filters:

    <template>
        <div>
            <form id="fillter-form" class="mt-3.5">
                <div class="grid grid-cols-3 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-4 xl:grid-cols-4">
                    <div class="multiselect border border-white border-opacity-20">
                        <div class="selectBox w-100 h-22" @click="toggleCategoriesSelect">
                            <span
                                class="inline float-left red pl-1.5 hidden multiselect-desc-categories absolute">Typ</span>
                            <div class=" bg-black placeholder-white text-2xl select-type-categories block p-6">
                                Typ
                            </div>
                            <span class="carrot inline float-right pt-10 pr-2"><img src="img/carrot.png"></span>
                        </div>
                        <div v-if="showMultiSelectCategories" class="multiselect-list-categories border-opacity-20 p-1.5">
                            <div class="checkboxes" v-for="(category, index) in categories"
                                 v-bind:key="`categories-${index}`">
                                <label class="text-2xl inline-block" :class="{ 'mt-1.5': index === 0 }">
                                    <input type="checkbox" name="categories[]"
                                           class="mr-1.5 multiselect-categories-checkbox"
                                           v-model="selectedCategories"
                                           :value="category.id"
                                           @click="loadProducts"
                                    />
                                    <span class="multiselect-icon"></span>
                                </label>
                                <div class="inline-block text-3xl ml-1.5">{{ category.name }}</div>
                            </div>
                        </div>
                    </div>
    
                    <input type="text" placeholder="Artysta" name="artist"
                           class="outline-none h-24 w-100 text-white text-2xl p-1.5 bg-black placeholder-white  border border-white border-opacity-20"/>
    
                    <input type="text" placeholder="Wytwórnia" name="company"
                           class="outline-none h-24 w-100 text-white text-2xl p-1.5 bg-black placeholder-white  border border-white border-opacity-20"/>
    
                    <div class="multiselect border border-white border-opacity-20">
                        <div class="selectBox w-100 h-22" @click="toggleGenresSelect">
                            <span
                                class="inline float-left red pl-1.5 hidden multiselect-desc-genres absolute">Gatunek</span>
                            <div class=" bg-black placeholder-white text-2xl select-type-genres block p-6">
                                Gatunek
                            </div>
                            <span class="carrot inline float-right pt-10 pr-2"><img src="img/carrot.png"></span>
                        </div>
                        <div v-if="showMultiSelectGenres" class="multiselect-list-genres border-opacity-20 p-1.5">
                            <div class="checkboxes" v-for="(genre, index) in genres" v-bind:key="`genre-${index}`">
                                <label class="text-2xl inline-block" :class="{ 'mt-1.5': index === 0 }">
                                    <input type="checkbox" name="genres[]" class="mr-1.5 multiselect-genres-checkbox"
                                           :value="genre.id"
                                           v-model="selectedGenres"
                                           @click="loadProducts"
                                    />
                                    <span class="multiselect-icon"></span>
                                </label>
                                <div class="inline-block text-3xl ml-1.5">{{ genre.custom_value }}</div>
                            </div>
                        </div>
                    </div>
    
                </div>
            </form>
    
            <div class="relative mt-12">
                <preloader
                    v-if="isLoadingInProgress"
                    class="py-8"
                    :class="preloaderClass"
                />
    
                <div class="text-center" v-if="products.length == 0 && !isLoadingInProgress">
                    {{ __('Żaden produkt nie jest aktualnie dostępny') }}
                </div>
    
                <div class="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-5 gap-8" v-if="products.length">
                    <div class="products-list text-center" v-for="(product, index) in products"
                         v-bind:key="`products-${index}`">
                        <a :href="product.url">
                            <img class="m-auto space-x-1" :src="product.img">
                            <div class="light-grey text-base">{{ product.artist }}</div>
                            <div class="text-white text-2xl">{{ product.name }}</div>
                            <div class="text-sm" v-if="product.promo_price == 0">{{ product.price }} /
                                {{ product.category_name }}
                            </div>
                            <div class="text-sm" v-else>
                                <div class="text-sm line-through">{{ product.price }} / {{ product.category_name }}</div>
                                <div class="text-sm red">{{ product.promo_price }} / {{ product.category_name }}</div>
                            </div>
                        </a>
                    </div>
                </div>
            </div>
        </div>
    </template>
    
    <script>
    import axios from "axios";
    import Preloader from "@/common/components/Preloader";
    
    export default {
        components: {
            Preloader
        },
        props: {
            categories: {
                type: Array,
                required: true,
                default: () => []
            },
            genres: {
                type: Array,
                required: true,
                default: () => []
            }
        },
        mounted() {
            this.loadProducts();
        },
        data() {
            return {
                showMultiSelectCategories: false,
                showMultiSelectGenres: false,
                isLoadingInProgress: false,
                artist: null,
                company: null,
                products: [],
                selectedCategories: [],
                selectedGenres: []
            }
        },
        computed: {
            preloaderClass() {
                return this.products.length > 0
                    ? ""
                    : "loading--transparent loading--block";
            }
        },
        methods: {
            toggleCategoriesSelect() {
                this.showMultiSelectCategories = !this.showMultiSelectCategories
            },
            toggleGenresSelect() {
                this.showMultiSelectGenres = !this.showMultiSelectGenres
            },
            loadProducts() {
                this.isLoadingInProgress = true;
    
                axios
                    .post(route('json.products'),
                        {
                            genres: this.selectedGenres,
                            categories: this.selectedCategories,
                            artist: this.artist,
                            company: this.company
                        })
                    .then(response => {
                        this.products = _.get(response, "data.data", []);
                    })
                    .catch(error => {
                        console.log(error);
                    })
                    .then(() => {
                        this.isLoadingInProgress = false;
                    });
            },
    
        }
    }
    </script>

It's work fine - I have product list. Now I need send to my php strings from my input and selected checkbox.

How can I make it? Please help me. I haven't problem with Laravel. My problem is with send selected checkbox and values with inputs to my php

Activity icon

Started a new Conversation Laravel If Statement In Query

Hi, I am beginner php developer.

I have this code:

    Model::selectRaw('clients.*, if((client_company_infos.name != "" , client_company_infos.type == 1),  client_company_infos.name, concat(client_infos.first_name, " ", client_infos.last_name)) as name')
                ->leftJoin('client_company_infos', 'client_company_infos.client_id', '=', 'clients.id')
                ->leftJoin('client_infos', 'client_infos.client_id', '=', 'clients.id')
                ->get();

I have error:

    "message": "SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '== 1),  client_company_infos.name, concat(client_infos.first_name, \" \", client_i' at line 1 (SQL: select clients.*, if((client_company_infos.name != \"\" , client_company_infos.type == 1),  client_company_infos.name, concat(client_infos.first_name, \" \", client_infos.last_name)) as name from `clients` left join `client_company_infos` on `client_company_infos`.`client_id` = `clients`.`id` left join `client_infos` on `client_infos`.`client_id` = `clients`.`id` where `clients`.`deleted_at` is null)",

When I make:

    Model::selectRaw('clients.*, if(client_company_infos.name != "",  client_company_infos.name, concat(client_infos.first_name, " ", client_infos.last_name)) as name')
                ->leftJoin('client_company_infos', 'client_company_infos.client_id', '=', 'clients.id')
                ->leftJoin('client_infos', 'client_infos.client_id', '=', 'clients.id')
                ->get();

It's work fine. Problem. I with second if. How can I. repair it?

Please help me

Oct
19
1 month ago
Activity icon

Started a new Conversation Configuration Of Routing With Guard In Laravel

Hi, I am beginner php developer. I have small problem with routing. I use this component on my website: spatie/laravel-permission

and I have this route:

    Route::group(['prefix' => '', 'middleware' => ['role:superadmin, admin, seller, telemarketer']], function () {
        Route::get('/', '[email protected]')->name('cms.home');
    
        Route::resource('pages', 'PageController')->only(['index', 'create', 'store', 'edit', 'update', 'destroy']);
        Route::get('/pages/dataTable', '[email protected]')->name('pages.dataTable');
    });

I have problem with middleware. When I have this: ['role:superadmin, admin, seller, telemarketer']] I have error: InvalidArgumentException Auth guard [ admin] is not defined.

My user has 'superadmin' role.

When I make this code: ['role:superadmin']] - it's work fine.

How can I repair it to other my role??

Please help me

Activity icon

Started a new Conversation Laravel 8 Error Pages 403, 404, 500, 503

Hi, I have many routs in my project. Other for frontend and others for backend. I need add error pages 403, 404, 500, 503 for my admin.

My routs structure:

  1. Routers:
  • admin -- auth -- client -- user
  • common
  • front -- auth -- home

How can I add error pages only for my admins?

Oct
14
1 month ago
Activity icon

Started a new Conversation Problem With Search In Laravel 8 In Left Join

Hi, I am beginner webdeveloper. I have this migration:

    Schema::create('clients', function (Blueprint $table) {
                $table->id();
                $table->string('email');
                $table->integer('type')->comment('1 - klient indywidualny, 2 - firma');
                $table->string('crm_number')->unique();
                $table->string('password');
                $table->string('verify_token');
                $table->rememberToken();
                $table->timestamp('password_assigned_at')->nullable();
                $table->timestamp('email_verified_at')->nullable();
                $table->timestamps();
                $table->deactivation();
                $table->softDeletes();
    
                $table->unique(['email', 'deleted_at']);
            });
    
    Schema::create('client_infos', function (Blueprint $table) {
                $table->id();
                $table->foreignId('client_id')->constrained('clients')->onDelete('cascade');
                $table->string('first_name');
                $table->string('last_name');
                $table->string('phone_nr')->nullable();
                $table->timestamps();
            });
    
    Schema::create('client_company_infos', function (Blueprint $table) {
                $table->id();
                $table->foreignId('client_id')->constrained('clients')->onDelete('cascade');
                $table->string('name');
                $table->string('nip')->nullable();
                $table->string('phone_nr')->nullable();
                $table->string('contact_email')->nullable();
                $table->string('invoice_email')->nullable();
                $table->timestamps();
            });
    
    Schema::create('locations', function (Blueprint $table) {
                $table->id();
                $table->foreignId('client_id')->constrained('clients')->onDelete('cascade');
                $table->string('name');
                $table->timestamps();
                $table->deactivation();
                $table->softDeletes();
            });
    
    Schema::create('gasmeters', function (Blueprint $table) {
                $table->id();
                $table->foreignId('location_id')->constrained('locations')->onDelete('cascade');
                $table->string('name');
                $table->timestamps();
                $table->deactivation();
                $table->softDeletes();
            });
    
    Schema::create('gasmeter_states', function (Blueprint $table) {
                $table->id();
                $table->foreignId('gasmeter_id')->constrained('gasmeters')->onDelete('cascade');
                $table->decimal('value');
                $table->date('settlement_date');
                $table->timestamp('loaded_from_crm_at')->nullable();
                $table->timestamps();
                $table->softDeletes();
            });

When I run my controller:

    GasmeterStates::
                selectRaw('client_company_infos.name, client_infos.last_name, client_infos.first_name, locations.name as location_name, gasmeters.name, gasmeters.location_id, gasmeter_states.gasmeter_id, gasmeter_states.value, gasmeter_states.settlement_date, gasmeter_states.loaded_from_crm_at, gasmeter_states.created_at, if(client_company_infos.name != "",  client_company_infos.name, concat(client_infos.first_name, " ", client_infos.last_name)) as client_name ')
                ->leftJoin('gasmeters', 'gasmeter_states.gasmeter_id', '=', 'gasmeters.id')
                ->leftJoin('locations', 'locations.id', '=', 'gasmeters.location_id')
                ->leftJoin('clients', 'clients.id', '=', 'locations.client_id')
                ->leftJoin('client_company_infos', 'client_company_infos.client_id', '=', 'clients.id')
                ->leftJoin('client_infos', 'client_infos.client_id', '=', 'clients.id');
            if (!is_null($filter['gasmeter'])) {
                $query->where('gasmeter_id', '=', $filter['gasmeter']);
            }
            $query->get();

This code work fine. Problem is when I try search. When i try search I have error:

    Column not found: 1054 Unknown column 'gasmeter_states.client_name' in 'where clause' (SQL: select count(*) as aggregate from (select '1' as `row_count` from `gasmeter_states` left join `gasmeters` on `gasmeter_states`.`gasmeter_id` = `gasmeters`.`id` left join `locations` on `locations`.`id` = `gasmeters`.`location_id` left join `clients` on `clients`.`id` = `locations`.`client_id` left join `client_company_infos` on `client_company_infos`.`client_id` = `clients`.`id` left join `client_infos` on `client_infos`.`client_id` = `clients`.`id` where (LOWER(`gasmeter_states`.`value`) LIKE %d% or LOWER(`gasmeter_states`.`settlement_date`) LIKE %d% or LOWER(`gasmeter_states`.`created_at`) LIKE %d% or LOWER(`gasmeter_states`.`client_name`) LIKE %d% or LOWER(`gasmeter_states`.`location_name`) LIKE %d% or LOWER(`gasmeter_states`.`loaded_from_crm_at`) LIKE %d%) and `gasmeter_states`.`deleted_at` is null) count_row_table)

How can I repair it?

Please help me.

Oct
12
1 month ago
Activity icon

Replied to Laravel Equivalent If Statement

Thank you, I know this solution. However, I need to do it in joiny or selectRaw :(

I try something like this:

Clients::when(request('clients.type', 1), function ($q, $role) {
                return $q->leftJoin('client_infos', 'client_infos.client_id', '=', 'clients.id')->select('clients.*', 'client_infos.first_name as name');
            })
            ->when(request('clients.type', 2), function ($q, $role) {
                return $q->leftJoin('client_company_infos', 'client_company_infos.client_id', '=', 'clients.id')->select('clients.*', 'client_company_infos.name as name');
            })

but it'asnot working :(

Activity icon

Replied to Laravel Equivalent If Statement

This is not exactly a solution. I need to have "name" written depending on whether the user is a company: client_company_infos.name oub if it is individual: name = client_infos.last_name + last_name

Activity icon

Replied to Laravel Equivalent If Statement

can you show me how to use this with if?

Activity icon

Started a new Conversation Laravel Equivalent If Statement

Hi, I am beginner php developer. I make my project in Laravel 8.

I have this migrations:

    Schema::create('clients', function (Blueprint $table) {
                $table->id();
                $table->string('email');
                $table->integer('type')->comment('1 - Client individual , 2 - Client Company');
                $table->string('crm_number')->unique();
                $table->string('password');
                $table->string('verify_token');
                $table->rememberToken();
                $table->timestamp('password_assigned_at')->nullable();
                $table->timestamp('email_verified_at')->nullable();
                $table->timestamps();
                $table->deactivation();
                $table->softDeletes();
    
                $table->unique(['email', 'deleted_at']);
            });
    
    Schema::create('client_infos', function (Blueprint $table) {
                $table->id();
                $table->foreignId('client_id')->constrained('clients')->onDelete('cascade');
                $table->string('first_name');
                $table->string('last_name');
                $table->string('phone_nr')->nullable();
                $table->timestamps();
            });
    
    Schema::create('client_company_infos', function (Blueprint $table) {
                $table->id();
                $table->foreignId('client_id')->constrained('clients')->onDelete('cascade');
                $table->string('name');
                $table->string('nip')->nullable();
                $table->string('phone_nr')->nullable();
                $table->string('contact_email')->nullable();
                $table->string('invoice_email')->nullable();
                $table->timestamps();
            });

If client.type = 1 - Client individual , 2 - Client Company

I have this code:

    Client:: leftJoin('client_company_infos', 'client_company_infos.client_id', '=', 'clients.id')
                ->leftJoin('client_infos', 'client_infos.client_id', '=', 'clients.id')
                ->select('clients.*',
                    'client_company_infos.name as name',
                    'client_infos.first_name as first_name',
                    'client_infos.last_name as last_name',
                );

In my situation I have name - for company name, first_name for first name and last_name as last_name.

I need always one value "name":

  1. company = name
  2. individual user = name as 'first name + last name'

How can I make it?

Please help me

Activity icon

Started a new Conversation Get Name With Two Columns Tables In Laravel

Hi, I am beginner laravel - developer.

I have this migrations:

    Schema::create('clients', function (Blueprint $table) {
                $table->id();
                $table->string('email');
                $table->integer('type')->comment('1 - klient indywidualny, 2 - firma');
                $table->string('crm_number')->unique();
                $table->string('password');
                $table->string('verify_token');
                $table->rememberToken();
                $table->timestamp('password_assigned_at')->nullable();
                $table->timestamp('email_verified_at')->nullable();
                $table->timestamps();
                $table->deactivation();
                $table->softDeletes();
    
                $table->unique(['email', 'deleted_at']);
            });
    
    Schema::create('client_infos', function (Blueprint $table) {
                $table->id();
                $table->foreignId('client_id')->constrained('clients')->onDelete('cascade');
                $table->string('first_name');
                $table->string('last_name');
                $table->string('phone_nr')->nullable();
                $table->timestamps();
            });
    Schema::create('client_company_infos', function (Blueprint $table) {
                $table->id();
                $table->foreignId('client_id')->constrained('clients')->onDelete('cascade');
                $table->string('name');
                $table->string('nip')->nullable();
                $table->string('phone_nr')->nullable();
                $table->string('contact_email')->nullable();
                $table->string('invoice_email')->nullable();
                $table->timestamps();
            });

and models:

class Client extends Authenticatable implements Presentable
{
    use Deactivation,
        Notifiable,
        SoftDeletes;

    const INDIVIDUAL = 1;
    const COMPANY = 2;


    protected $fillable = [
        'email',
        'crm_number',
        'email_verified_at',
        'password_assigned_at',
        'verify_token',
        'password',
        'type'
    ];

    protected $hidden = [
        'password',
        'verify_token',
        'remember_token',
    ];

    protected $dates = [
        'password_assigned_at',
        'email_verified_at',
        'created_at',
        'updated_at',
        'deactivated_at',
        'deleted_at',
    ];


    public function getAdminUrlAttribute(): AbstractAdminUrlPresenter
    {
        return new ClientUrlPresenter($this);
    }

    public function info()
    {
        return $this->hasOne(ClientInfo::class);
    }

    public function companyInfo()
    {
        return $this->hasOne(ClientCompanyInfo::class);
    }

    public function contractInfo()
    {
        return $this->hasOne(ClientContractInfo::class);
    }

    public function getHasAssignedPasswordAttribute(): bool
    {
        return !is_null($this->password_assigned_at);
    }

    public function getNameAttribute(): string
    {
        return $this->isCompany()
            ? data_get($this, 'companyInfo.name', "")
            : data_get($this, 'info.full_name', "");
    }

    public function isIndividualClient()
    {
        return $this->type == self::INDIVIDUAL;
    }

    public function isCompany()
    {
        return $this->type == self::COMPANY;
    }
}

Now I need select all record with client name:

  1. if company -> them client_company_infos.name
  2. if individual -> them client_infos.first_name and client_infos.last_name

I need use join or selectRaw.

How can I make it?

Please help me

Oct
06
1 month ago
Activity icon

Replied to Laravel Equivalent Result Without Duplicates

Yes. This is pivot table for my Products:

<?php

namespace App\Models\Catalog;

use App\Interfaces\Presentable;
use App\Models\{
    Image,
    ProductCategory,
    VatType
};
use App\Presenters\{
    AbstractAdminUrlPresenter,
    Admin\ProductUrlPresenter
};
use App\Traits\{
    Deactivation,
    Imageable,
    Seoable,
    Taggable,
    Translatable
};
use Illuminate\Database\Eloquent\{
    Model,
    Relations\BelongsTo,
    SoftDeletes
};
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Support\Str;

class Product extends Model implements Presentable
{
    use SoftDeletes,
        Deactivation,
        Seoable,
        Taggable,
        Translatable,
        Imageable;

    protected $appends = ['artist'];

    protected $fillable = [
        'name',
        'slug',
        'lead',
        'description',
        'price',
        'promo_price',
        'product_category_id',
        'image_id',
        'vat_type_id'
    ];

    protected $dates = [
        'deactivated_at',
        'created_at',
        'updated_at',
        'deleted_at'
    ];

    protected $casts = [
        'image_id' => 'integer',
        'product_category_id' => 'integer',
        'vat_type_id' => 'integer',
        'min_student_level' => 'integer',
        'price' => 'decimal:2'
    ];

    protected $hidden = [
        'product_category_id',
        'image_id',
        'vat_type_id',
        'deactivated_at',
        'created_at',
        'updated_at',
        'deleted_at'
    ];

    public function image(): BelongsTo
    {
        return $this->belongsTo(Image::class);
    }

    public function productCategory(): BelongsTo
    {
        return $this->belongsTo(ProductCategory::class);
    }

    public function vatType(): BelongsTo
    {
        return $this->belongsTo(VatType::class);
    }

    public function features(): BelongsToMany
    {
        return $this->belongsToMany(Feature::class)->withPivot('feature_value_id', 'custom_value');
    }

    public function getAdminUrlAttribute(): AbstractAdminUrlPresenter
    {
        return new ProductUrlPresenter($this);
    }

    public function getPriceFormattedAttribute(): string
    {
        return Str::price($this->price);
    }

    public function getPriceNettoAttribute(): string
    {
        $priceNetto = (1 - $this->vatType->value / 100) * $this->price;
        return Str::price(max(0, $priceNetto));
    }

    public function getArtistAttribute()
    {
        $features = $this->features()->get();
        if (count($features) > 0 ) {
            foreach ($features as $feature) {
                if (isset($feature->pivot) && $feature->name == "Artysta") {
                    return $feature->pivot->custom_value;
                }
            }
        }
    }
}