trifek

trifek

Member Since 1 Year Ago

Experience Points
3,220
Total
Experience

1,780 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.

Level 1
3,220 XP
Sep
12
1 week ago
Activity icon

Started a new Conversation Search Img In String And Add Class

Hi, I am beginner in Laravel and php. I have function to show text in text page.

Sample code:

public function index(String $slug, Request $request)
    {
        $page = $this->pageRepository->getTextPageFromSlug($slug);
        return view('front.textpage', [
            'metaDescription' => $page->title,
            'metaKeywords' => $page->title,
            'page' => $page,
        ]);
    }

In result I have something like this: http://serwer1356363.home.pl/_nauka/

I need add to my all images new class (without remove old class if exist): picla and data-label-class="label-class".

In result I need:

<img src="1.jpg" class="img-responsive picla" data-label-class="label-class" alt="Description" />

In $page ihave my html.

How can I make it?

Sep
09
2 weeks ago
Activity icon

Started a new Conversation Order Result By Related Table In Laravel

Hi, I am beginner webdeveloper.

I have this code Controller:

        public function getPlates(string $query, int $type, int $productId)
        {
            return $this->model->with(['plate'])
                ->where('product_id', $productId)
                ->whereHas('plate', function ($q) use ($query, $type) {
                    if ($query != "") {
                        $q->where('name', 'LIKE', '%' . $query . '%');
                        $q->orWhere('description', 'LIKE', '%' . $query . '%');
                    }
                    $q->where('price', '<>', '0.00');
                })
                ->whereHas('plate', function ($q) use ($query, $type) {
                    $q->where('plates.type', $type);
                    $q->orWhere('plates.type', 3);
                    $q->orderBy('name', 'asc');
                })->paginate(40);
        }
    
    ```
And migrations / model:
    ```
    Schema::create('plates', function (Blueprint $table) {
                $table->id();
                $table->string('name', 200);
                $table->string('description', 155)->nullable();
                $table->boolean('enable')->default(false);
                $table->decimal('price', 9, 2)->default(0);
                $table->smallInteger('vat_id')->unsigned()->default(1);
                $table->foreign('vat_id')->references('id')->on('vat_types');
                $table->char('type', 1)->default(0);
                $table->char('colors_type', 1)->default(0);
                $table->timestamps();
                $table->engine = "InnoDB";
                $table->charset = 'utf8mb4';
                $table->collation = 'utf8mb4_unicode_ci';
            });
    
    
    
    Schema::create('selected_plates', function (Blueprint $table) {
                $table->id();
                $table->bigInteger('plate_id')->unsigned();
                $table->foreign('plate_id')->references('id')->on('plates')->onDelete('cascade');
                $table->bigInteger('product_id')->unsigned();
                $table->foreign('product_id')->references('id')->on('products')->onDelete('cascade');
                $table->char('status', 1)->default(0);
                $table->decimal('maxvalue', 9, 2)->default(0);
                $table->decimal('minvalue', 9, 2)->default(0);
                $table->timestamps();
            });
    
    
    
    Schema::create('products', function (Blueprint $table) {
                $table->id();
                $table->string('name', 155);
                $table->string('title', 155);
                $table->string('description', 155)->nullable();
                $table->string('keywords', 155)->nullable();
                $table->longText('content')->nullable();
                $table->string('delivery_time', 155)->nullable();
                $table->string('small_description', 155)->nullable();
                $table->smallInteger('vat_id')->unsigned()->default(1);
                $table->foreign('vat_id')->references('id')->on('vat_types');
                $table->bigInteger('main_category_id')->unsigned()->default(0);
                //$table->foreign('category_id')->references('id')->on('categories');
                $table->boolean('enable')->default(false);
                $table->boolean('mark_new')->default(false);
                $table->boolean('mark_popular')->default(false);
                $table->boolean('product_type')->default(false);
                $table->string('promo_desc', 3)->nullable();
                $table->bigInteger('order')->default(0);
                $table->string('slug', 160)->nullable();
                $table->timestamps();
                $table->engine = "InnoDB";
                $table->charset = 'utf8mb4';
                $table->collation = 'utf8mb4_unicode_ci';
            });
    
    
    class Plate extends Model
    {
        use ScopeActiveTrait;
    
        protected $fillable = ['name', 'enable', 'price', 'vat_id', 'type', 'description'];
        protected $guarded = ['id'];
    
        public function frontImage()
        {
            return $this->hasMany('App\Models\UploadImage', 'file_id', 'id')->orderBy('order', 'ASC')->where('file_type', 'plates');
        }
    
        public function vat()
        {
            return $this->belongsTo('App\Models\VatTypes', 'vat_id');
        }
    
    
    }
    
    class SelectedPlates extends Model
    {
        use ScopeActiveTrait;
    
        protected $guarded = ['id'];
        protected $fillable = ['plate_id', 'status', 'maxvalue', 'minvalue', 'product_id'];
    
        public function plate()
        {
            return $this->hasMany('App\Models\Plate', 'id', 'plate_id');
        }
    }
    
    class Product extends Model
    {
        use ScopeActiveTrait;
        use Slugable;
    
        public function setNameAttribute($value)
        {
            $this->attributes['name'] = $value;
            $this->attributes['slug'] = $this->makeSlug($value);
        }
    
        protected $fillable = ['mark_popular', 'mark_new', 'delivery_time', 'product_type', 'name', 'title', 'description', 'keywords', 'content', 'vat_id', 'main_category_id', 'enable', 'slug', 'small_description', 'promo_desc', 'order'];
        protected $guarded = ['id'];
    
        public function vat()
        {
            return $this->hasOne('App\Models\VatTypes', 'id', 'vat_id');
        }
    
        public function category()
        {
            return $this->belongsTo('App\Models\Category', 'main_category_id');
        }
    
        public function selectedCategory()
        {
            return $this->hasMany('App\Models\SelectedProductCategory', 'product_id', 'id');
        }
    
    
        public function related()
        {
            return $this->hasMany('App\Models\RelatedProduct', 'product_id', 'id');
        }
    
        public function features()
        {
            return $this->hasMany('App\Models\SelectedProductFeature');
        }
    
    
        public function frontImage()
        {
            return $this->hasMany('App\Models\UploadImage', 'file_id', 'id')->orderBy('order', 'ASC')->where('file_type', 'products');
        }
    
        public function selectedPlates()
        {
            return $this->hasMany('App\Models\SelectedPlates', 'product_id', 'id');
        }
    
    }

in function getPlates I need sort result by plate.name.

my code works fine, but without order.

How can I repair it?

Please helo me

Sep
08
2 weeks ago
Activity icon

Started a new Conversation Search In Related Table

Hi, I have this controller:

public function getSelectedPlatesForProductByType(int $productId, int $type, int $selectedPlate)
    {
        if ($selectedPlate == 0) {
            return $this->model->with(["plate" => function ($q) use ($type) {
                $q->orWhere('colors_type', $type);
                $q->orWhere('colors_type', 3);
            }])
                ->where('product_id', $productId)
                ->limit(1)
                ->get();
        } else {
            echo 'here is problem!!' ;
            return $this->model->with(["plate" => function ($q) use ($type, $selectedPlate) {
                $q->orWhere('colors_type', $type);
                $q->orWhere('colors_type', 3);
                $q->where('id', $selectedPlate);
            }])
                ->where('product_id', $productId)
                ->limit(1)
                ->get();
        }
    }

And my schema migrations:

Schema::create('plates', function (Blueprint $table) {
            $table->id();
            $table->string('name', 200);
            $table->string('description', 155)->nullable();
            $table->boolean('enable')->default(false);
            $table->decimal('price', 9, 2)->default(0);
            $table->smallInteger('vat_id')->unsigned()->default(1);
            $table->foreign('vat_id')->references('id')->on('vat_types');
            $table->char('type', 1)->default(0);
            $table->char('colors_type', 1)->default(0);
            $table->timestamps();
            $table->engine = "InnoDB";
            $table->charset = 'utf8mb4';
            $table->collation = 'utf8mb4_unicode_ci';
        });


Schema::create('selected_plates', function (Blueprint $table) {
            $table->id();
            $table->bigInteger('plate_id')->unsigned();
            $table->foreign('plate_id')->references('id')->on('plates')->onDelete('cascade');
            $table->bigInteger('product_id')->unsigned();
            $table->foreign('product_id')->references('id')->on('products')->onDelete('cascade');
            $table->char('status', 1)->default(0);
            $table->decimal('maxvalue', 9, 2)->default(0);
            $table->decimal('minvalue', 9, 2)->default(0);
            $table->timestamps();
        })

My code not return result when I have: $q->where('id', $selectedPlate);

For exapple in plates.id = 2 - I have record.

What's is wrong?

How can I repair it?

Sep
03
3 weeks ago
Activity icon

Replied to Function To Check User Birth Date Is 18 Years Or Upper Not Always Work Correctly

It's not help. When I have 2045-12-12 - yours function not working :(

Activity icon

Started a new Conversation Function To Check User Birth Date Is 18 Years Or Upper Not Always Work Correctly

Hi I am beginner webdeveloper. I use in my project Laravel 5.8. I have this this code:

if ($this->calcutateAge($request->input('date')) < 18) {
            return Redirect::back()->withErrors(['You are a minor. Registration is allowed for adult users']);
        }

function calcutateAge($dob)
    {

        $dob = date("Y-m-d", strtotime($dob));

        $dobObject = new DateTime($dob);
        $nowObject = new DateTime();

        $diff = $dobObject->diff($nowObject);

        return $diff->y;

    }

It's work fine. But I have problem with date ex 2045-12-12. This function is not working. With year: 2015-12-12 - it's okey.

How can I repair it?

Sep
01
3 weeks ago
Activity icon

Started a new Conversation Displaying Categories Using The Cache In Laravel - Optimization

Hi. I am beginner php developer. I have problem with categories tree. I have website with https://www.jstree.com and Laravel 7 + https://packagist.org/packages/kalnoy/nestedset

I have a category table (164,574 records) - which is around 22.3MB (after phpmyadmin dump). The categories are practically unchanged.

My model and migration looks like this:

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

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

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

}

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

Assumption:

  1. display the category tree
  2. mark the selected categories on the tree I have to save selected categories:
Schema::create('selected_product_categories', function (Blueprint $table) {
            $table->id();
            $table->bigInteger('product_id')->unsigned()->default(0);
            $table->foreign('product_id')->references('id')->on('products')->onDelete('cascade');
            $table->bigInteger('category_id')->unsigned()->default(0);
            $table->foreign('category_id')->references('id')->on('categories')->onDelete('cascade');
            $table->timestamps();
        });

class SelectedProductCategory extends Model
{
    protected $fillable = ['product_id', 'category_id'];
    protected $guarded = ['id'];
}

My display code looks like this:

<div id="ajax" class="ajax"></div>
<script>
        $(function () {
            $('#ajax').jstree({
                "checkbox": {
                    "keep_selected_style": false
                },
                "plugins": [
                    "checkbox",
                ],
                'core': {
                    'data': {
                        "url": "domain.com/products/categoryTree",
                        "dataType": "json"
                    }
                }
            }).on('changed.jstree', function (e, data) {
                var checked_ids = [];
                var selectedNodes = $('#ajax').jstree("get_selected", true);
                $.each(selectedNodes, function () {
                    checked_ids.push(this.id);
                });
                $('.categoryTree').val(checked_ids);
            });
        });

    </script>



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 $categoryArray;
    }

The script generates a cache file (~ 250MB) on the server for me, but the tree is showing very slowly (after 3-5 minutes).

When I paste the html link into my browser: domain.com/products/categoryTree, it takes a few minutes to generate the data.

What could be causing such long loading times? What can be better optimized? Please help :)

I use php 7.4 and testing on localhost (I7, 32GB Ram, SSD), VPS and hosting

Aug
28
4 weeks ago
Activity icon

Replied to Validate Date In Laravel

you think about something like this:

$request->validate([
            'mydate' => 'date',
            'mydate' => 'date_format:y-m-d|before:today'
        ]);

??

Activity icon

Replied to Validate Date In Laravel

I have format YYYY-MM-DD

Activity icon

Started a new Conversation Validate Date In Laravel

Hi, I am beginner in Laravel. I make my project in Laravel 6.

I have this code:

public function validation(Request $request)
    {
        if ($this->endDate < now()->toDateString() or $this->summaryPeopleLimit <= $this->peopleLimit + 1) {
            return json_encode(['status' => 'error', 'message' => 'Rejestracja na to wydarzenie została zakończona!']);
        }


        if ($this->calcutateAge($request->input('date')) <= 18) {
            return json_encode(['status' => 'error', 'message' => 'Jesteś osobą niepełnoletnią. Rejestracja dozwolona jest dla użytkowników pełnoletnich!']);
        }

        if ($this->reservationRepository->isFreeReservationForEmail( $request->input('email'),$request->input('date') )) {
            return json_encode(['status' => 'error', 'message' => 'Posiadasz już rezerwację na to wydarzenie!']);
        }

        return json_encode(['status' => 'ok']);
    }

I need add this function: 1.Check if the date format: $ request-> input ('date') is correct (is it not, for example: 9999-99-99), 2. Check that the date in $ request-> input ('date') is not in the future

How can I make it?

Aug
27
4 weeks ago
Activity icon

Started a new Conversation User Age Verification

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

I would like to check if the user is 18 years old (taking into account his day and month of birth)

I make this function:

function calcutateAge($dob){

        $dob = date("Y-m-d",strtotime($dob));

        $dobObject = new DateTime($dob);
        $nowObject = new DateTime();

        $diff = $dobObject->diff($nowObject);

        return $diff->y;

    }

But it's not work correctly. When I check date: 2002-01-01 - I have result: the user is of legal age.

How can I repair it?

Aug
26
4 weeks ago
Activity icon

Replied to Addition Of An Ordinal Number In The Laravel Model

I't better :)

Now I have result:

"number" => 1
        "id" => 1933
        "email" => "[email protected]"
        "token" => "908970223"
        "date" => "2020-08-27"
        "hour" => "11:15"
        "track" => 1
        "sex" => "kobieta"

number is always == 1

Activity icon

Replied to Addition Of An Ordinal Number In The Laravel Model

Reservation::select(DB::raw('1 as index'), 'id', 'email', 'token', 'date', 'hour', 'track', 'sex') return me:

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 'index, id, email, token, date, hour, track, sex from reservations' at line 1 (SQL: select 1 as index, id, email, token, date, hour, track, sexfromreservationswheredate= 2020-08-27 order bytimeasc,track` asc)

Reservation::select('1 as index', 'id', 'email', 'token', 'date', 'hour', 'track', 'sex') return me:

SQLSTATE[42S22]: Column not found: 1054 Unknown column '1' in 'field list' (SQL: select 1 as index, id, email, token, date, hour, track, sex from reservations where date = 2020-08-27 order by time asc, track asc)

Activity icon

Replied to Addition Of An Ordinal Number In The Laravel Model

SQLSTATE[42S22]: Column not found: 1054 Unknown column '1' in 'field list' (SQL: select 1 as index, id, email, token, date, hour, track, sex from reservations where date = 2020-08-27 order by time asc, track asc)

Activity icon

Replied to Addition Of An Ordinal Number In The Laravel Model

It's work. Thank you. I have this result:

    "id" => 1834
        "email" => "[email protected]"
        "token" => "678168913"
        "date" => "2020-08-27"
        "hour" => "8:15"
        "track" => 6
        "sex" => "kobieta"
        "index" => 1

Is posible set index to first element?

Activity icon

Started a new Conversation Addition Of An Ordinal Number In The Laravel Model

Hi, I am beginner webdeveloper, I use in my project Laravel 7 and maatwebsite/excel

I have this code:

    namespace App\Models;
    
    use App\Models\Reservation;
    use Maatwebsite\Excel\Excel;
    use Maatwebsite\Excel\Concerns\FromCollection;
    use Maatwebsite\Excel\Concerns\FromQuery;
    use Maatwebsite\Excel\Concerns\WithHeadings;
    use Maatwebsite\Excel\Concerns\Exportable;
    
    
    class ReservationExport implements FromCollection, WithHeadings
    {
        use Exportable;
    
        protected $date;
    
        public function __construct(string $date)
        {
            $this->date = $date;
        }
    
        public function headings(): array
        {
            return [
                'LP',
                'ID Rezerwacji',
                'Adres email',
                'Token',
                'Data',
                'Godzina',
                'Tor',
                'Płeć',
            ];
        }
    
        public function collection()
        {
            $res = Reservation::select('id', 'id', 'email', 'token', 'date', 'hour', 'track', 'sex')->where('date', $this->date)->orderBy('time', 'ASC')->orderBy('track', 'ASC')->get();
            foreach ($res as $val) {
                $val->sex = ($val->sex == 1) ? 'kobieta' : 'mężczyzna';
            }
            return $res;
        }
    }
    
    public function export(Request $request)
        {
            return Excel::download(new ReservationExport($request->input('query')), 'reservation-'.$request->input('query').'.xlsx');
        }

This code generates an Excel document. It works fine. I would like to add a sequence number in 1 column (1,2,3 etc).

How can I do this?

My model:

    class Reservation extends Model
    {
        protected $quarded = ['id'];
        protected $fillable = ['email', 'token', 'date', 'hour', 'track', 'sex', 'time', 'people'];
        public $timestamps = true;
        protected $table = 'reservations';
    }

Please help

Aug
22
1 month ago
Activity icon

Started a new Conversation Checking If The Blade View File Exists

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

public function realization(string $slug)
    {
        $previous = $this->prev_elm($this->realizations, $slug);
        $next = $this->next_elm($this->realizations, $slug);

        $realization = null;
        foreach ($this->realizations as $value) {
            if ($value['url'] == $slug) {
                $realization = $value['name'];
            }
        }
        if ($realization == null) return redirect('home');
        return view('frontend.pl.projects.' . $slug, ['hideContact' => false, 'previous' => $previous, 'next' => $next, 'active' => 4, 'name' => $realization]);
    }

I would like to protect 'frontend.pl.projects.' . $ slug - if the appropriate blade view does not exist then I would like to redirect: return redirect ('home');

How can I do this?

Aug
20
1 month ago
Activity icon

Started a new Conversation Read Cookies In Laravel Blade Created In JS

I am beginner webdeveloper. I make my project in Laravel 7 and jQuery.

I create cookies in JavaScript (jQuery) and I need read it in Laravel Blade.

I have this code:

!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e=e||self,function(){var r=e.Cookies,n=e.Cookies=t();n.noConflict=function(){return e.Cookies=r,n}}())}(this,function(){"use strict";function e(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)e[n]=r[n]}return e}var t={read:function(e){return e.replace(/%3B/g,";")},write:function(e){return e.replace(/;/g,"%3B")}};return function r(n,i){function o(r,o,u){if("undefined"!=typeof document){"number"==typeof(u=e({},i,u)).expires&&(u.expires=new Date(Date.now()+864e5*u.expires)),u.expires&&(u.expires=u.expires.toUTCString()),r=t.write(r).replace(/=/g,"%3D"),o=n.write(String(o),r);var c="";for(var f in u)u[f]&&(c+="; "+f,!0!==u[f]&&(c+="="+u[f].split(";")[0]));return document.cookie=r+"="+o+c}}return Object.create({set:o,get:function(e){if("undefined"!=typeof document&&(!arguments.length||e)){for(var r=document.cookie?document.cookie.split("; "):[],i={},o=0;o<r.length;o++){var u=r[o].split("="),c=u.slice(1).join("="),f=t.read(u[0]).replace(/%3D/g,"=");if(i[f]=n.read(c,f),e===f)break}return e?i[e]:i}},remove:function(t,r){o(t,"",e({},r,{expires:-1}))},withAttributes:function(t){return r(this.converter,e({},this.attributes,t))},withConverter:function(t){return r(e({},this.converter,t),this.attributes)}},{attributes:{value:Object.freeze(i)},converter:{value:Object.freeze(n)}})}(t,{path:"/"})});

$(document).ready(function () {
    $('.cookies-box-close').click(function (e) {
        $('.cookies-box').removeClass('d-flex');
        $('.cookies-box').addClass('d-none');
        Cookies.set('hiddenCookiesSplash', '1', { expires: 30 })
    });

});

This code create cookies correctly.

Now I try check value in Laravel Blade:

@if (Cookie::get('hiddenCookiesSplash') != '1')
Is okey
@endif
But it's not working - laravel can't read vale from cookie :(

How can I repair it?

Aug
18
1 month ago
Activity icon

Started a new Conversation Website Translation

Hi, I am beginner in Laravel. I make my project in Laravel 7.

I have this code:

router.php

$locale = App::getLocale();

if (App::isLocale('pl')) {
    Route::get('/', '[email protected]')->name('home');
    Route::get('/o-nas', '[email protected]')->name('about');
    Route::get('/oferta', '[email protected]')->name('offer');
    Route::get('/realizacje', '[email protected]')->name('realizations');
    Route::get('/kontakt', '[email protected]')->name('contact');
    Route::get('/polityka-prywatnosci', '[email protected]')->name('privacy-policy');
}

Route::get('/en', '[email protected]')->name('home2');

if (App::isLocale('en')) {
    Route::get('/en/about-us', '[email protected]')->name('about');
    Route::get('/en/offer', '[email protected]')->name('offer');
    Route::get('/en/realizations', '[email protected]')->name('realizations');
    Route::get('/en/contact', '[email protected]')->name('contact');
    Route::get('/en/privacy-policy', '[email protected]')->name('privacy-policy');
}

Route::any('{query}',
    function() { return redirect('/'); })
    ->where('query', '.*');

in resources/lang I make 2 directory: pl and en and put router.php:

return array(
    'start' => 'start',
    'about'   => 'about us',
    'offer'   => 'offer',
    'realizations'   => 'realizations',
    'contact'   => 'contact'
)

In blade I make this url:


<ul class="navbar-nav">
                        <li class="nav-item d-block d-lg-none  d-xl-block text-center">
                            <a class="nav-link active" href="{{ route('home') }}">Start</a>
                        </li>
                        <li class="nav-item text-center">
                            <a class="nav-link" href="{{ route('about') }}">O nas</a>
                        </li>
                        <li class="nav-item text-center">
                            <a class="nav-link" href="{{ route('offer') }}">Oferta</a>
                        </li>
                        <li class="nav-item text-center">
                            <a class="nav-link" href="{{ route('realizations') }}">Realizacje </a>
                        </li>
                        <li class="nav-item text-center">
                            <a class="nav-link" href="{{ route('contact') }}">Kontakt</a>
                        </li>
                        <li class="nav-item mx-xl-4 mb-2 mb-md-0 text-center">
                            <a class="nav-link order-visit" href="{{ route('contact') }}">Zamów wizytę</a>
                        </li>
                        <li class="nav-item text-center d-inline-block d-lg-none language-box2">
                            <a href="{{ route('home') }}">PL</a> | <a href="{{ route('home2') }}">EN</a>
                        </li>
                    </ul>

Is this code correct for translations?

I have a problem, without changing the language I cannot go to e.g. domain.com/en/contact, domain.com/en/about-us etc

How can I repair this problem?

Aug
09
1 month ago
Activity icon

Replied to How To Optimize The Display Of Categories In Laravel 7?

I have about 170,000 records

Aug
08
1 month ago
Activity icon

Started a new Conversation How To Optimize The Display Of Categories In Laravel 7?

Hello, I am beginner php developer. I'm doing a project in Laravel 7 and using: https://packagist.org/packages/kalnoy/nestedset. I have a script that displays data to me for jstree https://www.jstree.com

I have the following category code:

    Schema::create('categories', function (Blueprint $table) {
                $table->bigIncrements('id');
                $table->string('category_name', 155);
                $table->string('description', 155)->nullable();
                $table->string('keywords', 155)->nullable();
                $table->longText('content')->nullable();
                $table->char('enable', 1)->default(0);
                $table->string('photo', 155)->nullable();
                $table->bigInteger('order')->default(0);
                $table->string('slug', 160)->nullable();
                NestedSet::columns($table);
                $table->engine = "InnoDB";
                $table->charset = 'utf8mb4';
                $table->collation = 'utf8mb4_unicode_ci';
            });
    
    
    
    use App\Traits\ScopeActiveTrait;
    use Illuminate\Database\Eloquent\Model;
    use Kalnoy\Nestedset\NodeTrait;
    use Spatie\Sluggable\HasSlug;
    use Spatie\Sluggable\SlugOptions;
    
    class Category extends Model
    {
        use ScopeActiveTrait;
        use NodeTrait;
        use HasSlug;
    
        /**
         * Get the options for generating the slug.
         */
        public function getSlugOptions() : SlugOptions
        {
            return SlugOptions::create()
                ->generateSlugsFrom('category_name')
                ->slugsShouldBeNoLongerThan(160)
                ->saveSlugsTo('slug');
        }
    
        protected $guarded = ['id'];
        protected $fillable = ['category_name', 'description', 'keywords', 'content', 'enable', 'photo', 'order', 'slug', '_lft', '_rgt', 'parent_id'];
        public $timestamps = false;
    
    } 

I have about 170,000 records in the category.

Generate code for my jstree with:

    public function categoryTree(Category $category, SelectedProductCategory $selectedProductCategory, Request $request)
    {
        $tree = Cache::remember('categories', 31536000, function () use ($category) {
            return $category->active()->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 $categoryArray;
    }

(I assume a cache update once a year)

SelectedProductCategory = selected categories

    class SelectedProductCategory extends Model
    {
        protected $fillable = ['product_id', 'category_id'];
        protected $guarded = ['id'];
    }
    
    Schema::create('selected_product_categories', function (Blueprint $table) {
                $table->id();
                $table->bigInteger('product_id')->unsigned()->default(0);
                $table->foreign('product_id')->references('id')->on('products')->onDelete('cascade');
                $table->bigInteger('category_id')->unsigned()->default(0);
                $table->foreign('category_id')->references('id')->on('categories')->onDelete('cascade');
                $table->timestamps();
    });

The problem is that the script is generated 4 minutes, both on the server and on the local computer :( The cache file takes about 300MB. Strangely, both I have a cache file and without it - the script always takes a long time to generate.

How can this be optimized?

Please help

Aug
03
1 month ago
Activity icon

Started a new Conversation Laravel Cannot See The Cookie Created In JS

Hi, I am beginner webdeveloper.

I have this JS:

function createCookie(name, value, days) {
    var expires;

    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        expires = "; expires=" + date.toGMTString();
    } else {
        expires = "";
    }
    document.cookie = encodeURIComponent(name) + "=" + encodeURIComponent(value) + expires + "; path=/";
}

function readCookie(name) {
    var nameEQ = encodeURIComponent(name) + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) === ' ')
            c = c.substring(1, c.length);
        if (c.indexOf(nameEQ) === 0)
            return decodeURIComponent(c.substring(nameEQ.length, c.length));
    }
    return null;
}
createCookie('selected-material-body', $(this).attr('id'), 14);

When I try this cookie in my blade:

{{ Cookie::get('selected-material-body') }}

I not visible result from JS :(

How can I repair this problem?

Jul
24
2 months ago
Activity icon

Replied to Disable Required CSRF In POST Method In Selected Route

Complete addresses including domain required here?

Can I do, for example, from the domain name.pl

protected $ except = [
         'PaymentStatus'
         'PaymentConfirmation'
         'PaymentConfirmationSplash'
         'CreatePayment'
     ];

will this be correct for my routs?

Activity icon

Started a new Conversation Disable Required CSRF In POST Method In Selected Route

Hi, I have 4 router, where I need disable required CSRF in post (payments).

Route::post('createPayment', '[email protected]')->name('frontend.dotpay.createPayment');
Route::post('paymentConfirmation', '[email protected]')->name('frontend.paymentConfirmation');
Route::match(['POST', 'GET'], 'paymentConfirmationSplash', '[email protected]')->name('frontend.paymentConfirmationSplash');
Route::get('/paymentStatus', '[email protected]')->name('frontend.paymentStatus')


How can I make it?

Activity icon

Started a new Conversation Migration Not Working With Cascade Delete

Hi,

I have 2 schema:

Schema::create('ordered_products', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->bigInteger('order_id')->default(0);
            $table->foreign('order_id')->references('order_number')->on('orders')->onDelete('cascade');
            $table->text('product')->nullable();
            $table->unsignedInteger('quantity')->default(0);
            $table->decimal('product_price', 9, 2)->default(0);
            $table->smallInteger('vat_id')->default(0);
            $table->engine = "InnoDB";
            $table->charset = 'utf8mb4';
            $table->collation = 'utf8mb4_unicode_ci';
        });


Schema::create('orders', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('email', 100)->nullable();
            $table->string('phone', 35)->nullable();
            $table->string('street', 250)->nullable();
            $table->string('city', 100)->nullable();
            $table->string('post_code', 15)->nullable();
            $table->string('company_name', 250)->nullable();
            $table->string('nip', 30)->nullable();
            $table->longText('comment')->nullable();
            $table->char('invoice', 1)->default(0);
            $table->ipAddress('ip')->nullable();
            $table->smallInteger('status')->default(0);
            $table->bigInteger('order_number')->default(0);
            $table->timestamps();
            $table->engine = "InnoDB";
            $table->charset = 'utf8mb4';
            $table->collation = 'utf8mb4_unicode_ci';
        });

When I run migration I have error:

SQLSTATE[HY000]: General error: 1005 Can't create table project1.ordered_products (errno: 150 "Foreign key constraint is incorrectly formed") (SQL: alter table ordered_products add constraint ordered_products_order_id_foreign foreign key (order_id) references orders (order_number) on delete cascade)

How can I repair this problem?

Jul
22
2 months ago
Activity icon

Replied to How Access From Blade File To Function From Repository?

I have list in Blade file:

@foreach($card as $item)
@php $plate = \App\Repositories\PlateRepository::plate($item->id); @endphp
                                    
@endforeach

and I can't use this in controller

Activity icon

Replied to How Access From Blade File To Function From Repository?

This code return: Call to undefined method App\Repositories\PlateRepository::plate() (View: /Applications/XAMPP/xamppfiles/htdocs/roelle/resources/views/front/basket.blade.php) http://roelle.test/koszyk

Activity icon

Started a new Conversation How Access From Blade File To Function From Repository?

Hi, I have function:

public function getPlateFromId(int $productId)
    {
        return $this->model->active()->with(['vat', 'frontImage'])->where('id', $productId)->first();
    }

in my PlateRepository.php

I need access to this function from Blade.

I try this code in blade file:

$plate = \App\Repositories\PlateRepository::getPlateFromId($item->quantity);

butt it's not working. I have error: Non-static method App\Repositories\PlateRepository::getPlateFromId() should not be called statically (View: /Applications/XAMPP/xamppfiles/htdocs/roelle/resources/views/front/basket.blade.php)

How can I repair it?

Jul
21
2 months ago
Activity icon

Replied to Displaying Records From The Database Based On Selected Values

I try this:

$this->model->active()->with(['vat', 'frontImage', 'selectedPlates'])->whereHas('selectedPlates', function($q) use ($query, $type){
            if ($query != "") {
                $q->where('name', 'LIKE', '%' . $query . '%');
                $q->orWhere('description', 'LIKE', '%' . $query . '%');
            }
        })->orderBy('name', 'asc')->get()

but it's not working :(

I need search in selectedPlates -> relation plates

Activity icon

Replied to Displaying Records From The Database Based On Selected Values

The above code doesn't work. Does not search / filter.

Activity icon

Replied to Displaying Records From The Database Based On Selected Values

true, thank you :)

Ok, i change my code :)

In my system I have cabinets and boards from which it is made. I'm doing a cupboard builder. Each cabinet has specific plates assigned to it. Each cabinet may have different plates.

In this moment I have:


class Product extends Model
{
    use ScopeActiveTrait;
    use Slugable;

    public function setNameAttribute($value)
    {
        $this->attributes['name'] = $value;
        $this->attributes['slug'] = $this->makeSlug($value);
    }

    protected $fillable = ['mark_popular', 'mark_new', 'delivery_time', 'product_type', 'name', 'title', 'description', 'keywords', 'content', 'vat_id', 'main_category_id', 'enable', 'slug', 'small_description'];
    protected $guarded = ['id'];
    public $timestamps = false;

    public function vat()
    {
        return $this->belongsTo('App\Models\Vat', 'vat_id');
    }

    public function category()
    {
        return $this->belongsTo('App\Models\Category', 'main_category_id');
    }

    public function selectedCategory()
    {
        return $this->hasMany('App\Models\SelectedProductCategory', 'product_id', 'id');
    }


    public function related()
    {
        return $this->hasMany('App\Models\RelatedProduct', 'product_id', 'id');
    }

    public function features()
    {
        return $this->hasMany('App\Models\SelectedProductFeature');
    }


    public function frontImage()
    {
        return $this->hasMany('App\Models\UploadImage', 'file_id', 'id')->orderBy('order', 'ASC')->where('file_type', 'products');
    }

    public function selectedPlates()
    {
        return $this->hasMany('App\Models\SelectedPlates', 'product_id', 'id');
    }

}


class Plate extends Model
{
    use ScopeActiveTrait;

    protected $fillable = ['name', 'enable', 'price', 'vat_id', 'type', 'description'];
    protected $guarded = ['id'];
    public $timestamps = false;

    public function frontImage()
    {
        return $this->hasMany('App\Models\UploadImage', 'file_id', 'id')->orderBy('order', 'ASC')->where('file_type', 'plates');
    }

    public function vat()
    {
        return $this->belongsTo('App\Models\Vat', 'vat_id');
    }

}


class SelectedPlates extends Model
{
    use ScopeActiveTrait;

    protected $guarded = ['id'];
    protected $fillable = ['plate_id', 'status', 'maxvalue', 'minvalue', 'product_id'];

    public function plate()
    {
        return $this->belongsTo('App\Models\Plate', 'vat_id');
    }
}

SelectedPlates - assigned to a product / plate cabinet

Plate - plates

Product - cabinets

I need a searchable display of all boards assigned to a given product / cabinet

I make this function:


public function getPlates(string $query, int $type, int $productId)
{
Product::active()->with(['vat', 'frontImage', 'selectedPlates'])->where(function ($q) use ($query, $type){
            if ($query != "") {
                $q->where('name', 'LIKE', '%' . $query . '%');
                $q->orWhere('description', 'LIKE', '%' . $query . '%');
            }
        })->orderBy('name', 'asc')->get()
}

this code return me 2 plates:

Illuminate\Database\Eloquent\Collection {#1669 ▼
  #items: array:1 [▼
    0 => App\Models\Product {#1605 ▼
      #fillable: array:14 [▶]
      #guarded: array:1 [▶]
      +timestamps: false
      #connection: "mysql"
      #table: "products"
      #primaryKey: "id"
      #keyType: "int"
      +incrementing: true
      #with: []
      #withCount: []
      #perPage: 15
      +exists: true
      +wasRecentlyCreated: false
      #attributes: array:16 [▶]
      #original: array:16 [▶]
      #changes: []
      #casts: []
      #classCastCache: []
      #dates: []
      #dateFormat: null
      #appends: []
      #dispatchesEvents: []
      #observables: []
      #relations: array:3 [▼
        "vat" => App\Models\Vat {#1640 ▶}
        "frontImage" => Illuminate\Database\Eloquent\Collection {#1606 ▶}
        "selectedPlates" => Illuminate\Database\Eloquent\Collection {#1642 ▼
          #items: array:2 [▼
            0 => App\Models\SelectedPlates {#1702 ▶}
            1 => App\Models\SelectedPlates {#1703 ▶}
          ]
        }
      ]
      #touches: []
      #hidden: []
      #visible: []
    }
  ]
}

Now I need search in this plates by:

if ($query != "") {
                $q->where('plates.name', 'LIKE', '%' . $query . '%');
                $q->orWhere('plates.description', 'LIKE', '%' . $query . '%');
            }

and filter by

->where(function ($q) use ($type) {
                $q->where('plates.type', $type);
                $q->orWhere('plates.type', 3);
            })

something like this:

public function getMaterials(string $query, int $type, int $produktId)
    {
        return Product->active()->with(['vat', 'frontImage'])->where(function ($q) use ($query, $type) {
            if ($query != "") {
                $q->where('plates.name', 'LIKE', '%' . $query . '%');
                $q->orWhere('plates.description', 'LIKE', '%' . $query . '%');
            }
        })
            ->where(function ($q) use ($type) {
                $q->where('plates.type', $type);
                $q->orWhere('plates.type', 3);
            })
            ->orderBy('name', 'asc')->get();
    }

how can I make it?

Activity icon

Replied to Displaying Records From The Database Based On Selected Values

You thing about something like this:

return $this->model->active()->with(['vat', 'frontImage'])->selected_plates()->exists()->where(function ($q) use ($query, $type) {
            if ($query != "") {
                $q->where('name', 'LIKE', '%' . $query . '%');
                $q->orWhere('description', 'LIKE', '%' . $query . '%');
            }
        })
            ->where(function ($q) use ($type) {
                $q->where('type', $type);
                $q->orWhere('type', 3);
            })
            ->where('product_id', $produktId)
            ->orderBy('name', 'asc')->get();

??

Activity icon

Replied to Displaying Records From The Database Based On Selected Values

Thank you for your's answer.

What's wring with: "protected $quarded = ['id']; instead of protected $guarded = ['id']; (q => g)."?

I have products in my database with assigned countertops. My current code displays all the tops I have in the system. I would like to display only the countertops that are assigned to a product. So selected_product_features. product_id = products.id

Activity icon

Started a new Conversation Displaying Records From The Database Based On Selected Values

I am beginner in Laravel and php. I write my project in Laravel 7.

I have this code:

class Plate extends Model
{
    use ScopeActiveTrait;

    protected $fillable = ['name', 'enable', 'price', 'vat_id', 'type', 'description'];
    protected $quarded = ['id'];
    public $timestamps = false;

    public function frontImage()
    {
        return $this->hasMany('App\Models\UploadImage', 'file_id', 'id')->orderBy('order', 'ASC')->where('file_type', 'plates');
    }

    public function vat()
    {
        return $this->belongsTo('App\Models\Vat', 'vat_id');
    }
}

class SelectedPlates extends Model
{
    use ScopeActiveTrait;

    protected $quarded = ['id'];
    protected $fillable = ['plate_id', 'status', 'maxvalue', 'minvalue', 'product_id'];

}

Schema::create('selected_plates', function (Blueprint $table) {
            $table->id();
            $table->bigInteger('plate_id')->unsigned();
            $table->foreign('plate_id')->references('id')->on('plates')->onDelete('cascade');
            $table->bigInteger('product_id')->unsigned();
            $table->foreign('product_id')->references('id')->on('products')->onDelete('cascade');
            $table->char('status', 1)->default(0);
            $table->decimal('maxvalue', 9, 2)->default(0);
            $table->decimal('minvalue', 9, 2)->default(0);
            $table->timestamps();
        });

Schema::create('plates', function (Blueprint $table) {
            $table->id();
            $table->string('name', 155);
            $table->string('description', 155)->nullable();
            $table->char('enable', 1)->default(0);
            $table->decimal('price', 9, 2)->default(0);
            $table->smallInteger('vat_id')->unsigned()->default(1);
            $table->foreign('vat_id')->references('id')->on('vat');
            $table->char('type', 1)->default(0);
            $table->engine = "InnoDB";
            $table->charset = 'utf8mb4';
            $table->collation = 'utf8mb4_unicode_ci';
        });

and function to show result:

public function getMaterials(string $query, int $type, int $produktId)
    {
        return $this->model->active()->with(['vat', 'frontImage'])->where(function ($q) use ($query, $type) {
            if ($query != "") {
                $q->where('name', 'LIKE', '%' . $query . '%');
                $q->orWhere('description', 'LIKE', '%' . $query . '%');
            }
        })
            ->where(function ($q) use ($type) {
                $q->where('type', $type);
                $q->orWhere('type', 3);
            })
            ->orderBy('name', 'asc')->get();
    }
$this->model = Plate. It's work fine. Its show all my plates with parms etc.

I need to change this code so that this function returns not all plates - only the ones that were selected (selected_plates).

How can I make it?

Jul
18
2 months ago
Activity icon

Started a new Conversation Delete File After Download

Hi, I have function to save file on server and download (it's work fine):

$objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'Word2007');
        $fileNameServer = $request->user()->id.'-'.md5($request->user()->id.uniqid(). time().microtime()). '.docx';
        $fileName = 'Raport' . '-' . now()->toDateString() . '.docx';
        try {
            $objWriter->save(storage_path($fileNameServer));
        } catch (Exception $e) {
        }

        return response()->download(storage_path($fileNameServer), $fileName);

Is posible remove file after download?

Jul
14
2 months ago
Activity icon

Replied to Unknown Column In Laravel Equivalent

One product can belong to many categories, that's why I made the selected_product_categories table for this. In product I have relation:

public function selectedCategory()
{
    return $this->hasMany('App\Models\SelectedProductCategory', 'product_id', 'id');
}

it's wrong?

Activity icon

Replied to Unknown Column In Laravel Equivalent

category_id I have in selected_product_categories : - look on screen https://ibb.co/mhcBxN9 :)

Activity icon

Replied to Unknown Column In Laravel Equivalent

@michaloravec you thing about something like this:

public function getProductFromIdCategories($categories)
    {
        return $this->model->select('name', 'slug', 'products.id', 'small_description')
            ->with(['frontImage', 'selectedCategory' => function ($query) use ($categories) {
                $query->whereIn('category_id', $categories);
            }])->whereHas('selectedCategory', function ($query, $categories) {
                $query->whereIn('category_id', $categories);
            })->active()->get();
    }

?

it's return Too few arguments to function App\Repositories\ProductRepository::App\Repositories{closure}(), 1 passed in /Applications/XAMPP/xamppfiles/htdocs/roelle/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Builder.php on line 988 and exactly 2 expected in. line: }])->whereHas('selectedCategory', function ($query, $categories) {

Activity icon

Replied to Unknown Column In Laravel Equivalent

i have this code:

public function getProductFromIdCategories($categories)
    {
        return $this->model->select('name', 'slug', 'products.id', 'small_description')
            ->with(['frontImage', 'selectedCategory' => function($q) use ($categories){
                $q->whereIn('category_id', $categories);
            }])->whereIn('category_id', $categories)->active()->get();
    }

I have in selected_product_categories category_id: https://ibb.co/mhcBxN9 – operloa 4 mins ago Edit Delete and I have relation: selectedCategory in Product

Activity icon

Started a new Conversation Unknown Column In Laravel Equivalent

Hi, I am beginner in Laravel. I have problem with my mysql.

I have this code:

  1. Model:
    class Product extends Model
    {
        use ScopeActiveTrait;
        use Slugable;
    
        public function setNameAttribute($value)
        {
            $this->attributes['name'] = $value;
            $this->attributes['slug'] = $this->makeSlug($value);
        }
    
        protected $fillable = ['delivery_time', 'product_type', 'name', 'title', 'description', 'keywords', 'content', 'vat_id', 'main_category_id', 'enable', 'slug', 'small_description'];
        protected $quarded = ['id'];
        public $timestamps = false;
    
        public function vat()
        {
            return $this->belongsTo('App\Models\VAT', 'vat_id');
        }
    
        public function category()
        {
            return $this->belongsTo('App\Models\Category', 'main_category_id');
        }
    
        public function selectedCategory()
        {
            return $this->hasMany('App\Models\SelectedProductCategory', 'product_id', 'id');
        }
    
        public function related()
        {
            return $this->belongsTo('App\Models\RelatedProduct');
        }
    
        public function features()
        {
            return $this->hasMany('App\Models\SelectedProductFeature');
        }
    
    
        public function frontImage()
        {
            return $this->hasMany('App\Models\UploadImage', 'file_id', 'id')->orderBy('order', 'ASC')->where('file_type', 'products');
        }
    
    }
    
    
    
    class SelectedProductCategory extends Model
    {
        protected $fillable = ['product_id', 'category_id'];
        protected $quarded = ['id'];
    
    
    }
  1. schema:
    Schema::create('products', function (Blueprint $table) {
    $table->id();
    $table->string('name', 155);
     $table->string('title', 155);
     $table->string('description', 155)->nullable();
     $table->string('keywords', 155)->nullable();
     $table->longText('content')->nullable();
     $table->string('delivery_time', 155)->nullable();
     $table->string('small_description', 155)->nullable();
     $table->smallInteger('vat_id')->unsigned()->default(1);
     $table->foreign('vat_id')->references('id')->on('vat');
     $table->bigInteger('main_category_id')->unsigned()->default(0);
     //$table->foreign('category_id')->references('id')->on('categories');
     $table->char('enable', 1)->default(0);
     $table->char('product_type', 1)->default(0);
     $table->string('promo_desc', 3)->nullable();
     $table->string('slug', 160)->nullable();
     $table->engine = "InnoDB";
     $table->charset = 'utf8mb4';
     $table->collation = 'utf8mb4_unicode_ci';
    });

  

      
    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->char('enable', 1)->default(0);
     $table->bigInteger('order')->default(0);
     $table->string('slug', 160)->nullable();
     NestedSet::columns($table);
     $table->engine = "InnoDB";
     $table->charset = 'utf8mb4';
     $table->collation = 'utf8mb4_unicode_ci';
    });
  1. Repository:
    public function getProductFromIdCategories($categories)
        {
            return $this->model->select('name', 'slug', 'products.id', 'small_description')
                ->with(['selectedCategory', 'frontImage', 'selectedCategory' => function($q) use ($categories){
                    $q->whereIn('category_id', $categories);
                }])->whereIn('category_id', $categories)->active()->get();
        }

In $categories I have array:

    array:1 [▼
      0 => 12
    ]

My product is assigned to this category.

I have error:

    SQLSTATE[42S22]: Column not found: 1054 Unknown column 'category_id' in 'where clause' (SQL: select `name`, `slug`, `products`.`id`, `small_description` from `products` where `category_id` in (12) and `enable` = 1)

I don;'t know why. I have this column in selected_product_categories

How can I repair this problem?

Jul
13
2 months ago
Activity icon

Started a new Conversation Laravel Display Duplicates When There Is 1 Record In The Database

Hi, I am beginner in Laravel. I have small problem with Laravel.

I have this code:

    $categories = $categoryRepository->descendantsAndSelf($slug ?? null); 

this return:

    Illuminate\Support\Collection {#535 ▼
      #items: array:17 [▼
        0 => 1
        1 => 2
        2 => 3
        3 => 4
        4 => 5
        5 => 6
        6 => 7
        7 => 8
        8 => 9
        9 => 10
        10 => 11
        11 => 12
        12 => 13
        13 => 14
        14 => 15
        15 => 16
        16 => 17
      ]
    }

And my repository:

    public function getProductFromIdCategories($categories)
        {
            return $this->model->select('name', 'slug', 'products.id', 'small_description')->with(['selectedCategory', 'frontImage'])->active()->leftJoin('selected_product_categories', function ($join) {
                $join->on('products.id', 'selected_product_categories.product_id');
            })->whereIn('selected_product_categories.category_id', $categories)->get();  
        }

When I run my code:

    dd($this->model->getProductFromIdCategories($categories->toArray()));

I have result (duplicates):

    Illuminate\Database\Eloquent\Collection {#1484 ▼
      #items: array:3 [▼
        0 => App\Models\Product {#1497 ▼
          #fillable: array:12 [▶]
          #quarded: array:1 [▶]
          +timestamps: false
          #connection: "mysql"
          #table: "products"
          #primaryKey: "id"
          #keyType: "int"
          +incrementing: true
          #with: []
          #withCount: []
          #perPage: 15
          +exists: true
          +wasRecentlyCreated: false
          #attributes: array:4 [▼
            "name" => "Nazwa"
            "slug" => "nazwa"
            "id" => 1
            "small_description" => "mini opis"
          ]
          #original: array:4 [▶]
          #changes: []
          #casts: []
          #classCastCache: []
          #dates: []
          #dateFormat: null
          #appends: []
          #dispatchesEvents: []
          #observables: []
          #relations: array:2 [▶]
          #touches: []
          #hidden: []
          #visible: []
          #guarded: array:1 [▶]
        }
        1 => App\Models\Product {#1496 ▼
          #fillable: array:12 [▶]
          #quarded: array:1 [▶]
          +timestamps: false
          #connection: "mysql"
          #table: "products"
          #primaryKey: "id"
          #keyType: "int"
          +incrementing: true
          #with: []
          #withCount: []
          #perPage: 15
          +exists: true
          +wasRecentlyCreated: false
          #attributes: array:4 [▼
            "name" => "Nazwa"
            "slug" => "nazwa"
            "id" => 1
            "small_description" => "mini opis"
          ]
          #original: array:4 [▶]
          #changes: []
          #casts: []
          #classCastCache: []
          #dates: []
          #dateFormat: null
          #appends: []
          #dispatchesEvents: []
          #observables: []
          #relations: array:2 [▶]
          #touches: []
          #hidden: []
          #visible: []
          #guarded: array:1 [▶]
        }
        2 => App\Models\Product {#1493 ▼
          #fillable: array:12 [▶]
          #quarded: array:1 [▶]
          +timestamps: false
          #connection: "mysql"
          #table: "products"
          #primaryKey: "id"
          #keyType: "int"
          +incrementing: true
          #with: []
          #withCount: []
          #perPage: 15
          +exists: true
          +wasRecentlyCreated: false
          #attributes: array:4 [▼
            "name" => "Nazwa"
            "slug" => "nazwa"
            "id" => 1
            "small_description" => "mini opis"
          ]
          #original: array:4 [▶]
          #changes: []
          #casts: []
          #classCastCache: []
          #dates: []
          #dateFormat: null
          #appends: []
          #dispatchesEvents: []
          #observables: []
          #relations: array:2 [▶]
          #touches: []
          #hidden: []
          #visible: []
          #guarded: array:1 [▶]
        }
      ]
    }

My models:

    class Product extends Model
    {
        use ScopeActiveTrait;
        use Slugable;
    
        public function setNameAttribute($value)
        {
            $this->attributes['name'] = $value;
            $this->attributes['slug'] = $this->makeSlug($value);
        }
    
        protected $fillable = ['delivery_time', 'product_type', 'name', 'title', 'description', 'keywords', 'content', 'vat_id', 'category_id', 'enable', 'slug', 'small_description'];
        protected $quarded = ['id'];
        public $timestamps = false;
    
        public function vat()
        {
            return $this->belongsTo('App\Models\VAT', 'vat_id');
        }
    
        public function category()
        {
            return $this->belongsTo('App\Models\Category', 'category_id');
        }
    
        public function selectedCategory()
        {
            return $this->hasMany('App\Models\SelectedProductCategory', 'product_id', 'id');
        }
    
        public function related()
        {
            return $this->belongsTo('App\Models\RelatedProduct');
        }
    
        public function features()
        {
            return $this->hasMany('App\Models\SelectedProductFeature');
        }
    
    
        public function frontImage()
        {
            return $this->hasMany('App\Models\UploadImage', 'file_id', 'id')->orderBy('order', 'ASC')->where('file_type', 'products');
        }
    
    }
    
    
    class SelectedProductCategory extends Model
    {
        protected $fillable = ['product_id', 'category_id'];
        protected $quarded = ['id'];
    
    
    }

And schema:

    Schema::create('products', function (Blueprint $table) {
                $table->id();
                $table->string('name', 155);
                $table->string('title', 155);
                $table->string('description', 155)->nullable();
                $table->string('keywords', 155)->nullable();
                $table->longText('content')->nullable();
                $table->string('delivery_time', 155)->nullable();
                $table->string('small_description', 155)->nullable();
                $table->smallInteger('vat_id')->unsigned()->default(1);
                $table->foreign('vat_id')->references('id')->on('vat');
                $table->bigInteger('category_id')->unsigned()->default(0);
                //$table->foreign('category_id')->references('id')->on('categories');
                $table->char('enable', 1)->default(0);
                $table->char('product_type', 1)->default(0);
                $table->string('promo_desc', 3)->nullable();
                $table->string('slug', 160)->nullable();
                $table->engine = "InnoDB";
                $table->charset = 'utf8mb4';
                $table->collation = 'utf8mb4_unicode_ci';
            });
    
    
    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->char('enable', 1)->default(0);
                $table->bigInteger('order')->default(0);
                $table->string('slug', 160)->nullable();
                NestedSet::columns($table);
                $table->engine = "InnoDB";
                $table->charset = 'utf8mb4';
                $table->collation = 'utf8mb4_unicode_ci';
            });
    
    
    Schema::create('selected_product_categories', function (Blueprint $table) {
                $table->id();
                $table->bigInteger('product_id')->unsigned()->default(0);
                $table->foreign('product_id')->references('id')->on('products')->onDelete('cascade');
                $table->bigInteger('category_id')->unsigned()->default(0);
                $table->foreign('category_id')->references('id')->on('categories')->onDelete('cascade');
                $table->timestamps();
            });

In DB i have only 1 record:

https://ibb.co/dWLY9nV

Laravel return me 3 records. Why I have duplicates? How can I repair it?

Please help me.

Activity icon

Started a new Conversation Displaying A List Of Products Assigned To Many Categories

I am beginner in Laravel.

I need show all products with selected categories.

I have this code:

Schema::create('products', function (Blueprint $table) {
            $table->id();
            $table->string('name', 155);
            $table->string('title', 155);
            $table->string('description', 155)->nullable();
            $table->string('keywords', 155)->nullable();
            $table->longText('content')->nullable();
            $table->string('delivery_time', 155)->nullable();
            $table->string('small_description', 155)->nullable();
            $table->smallInteger('vat_id')->unsigned()->default(1);
            $table->foreign('vat_id')->references('id')->on('vat');
            $table->bigInteger('category_id')->unsigned()->default(0);
            //$table->foreign('category_id')->references('id')->on('categories');
            $table->char('enable', 1)->default(0);
            $table->char('product_type', 1)->default(0);
            $table->string('slug', 160)->nullable();
            $table->engine = "InnoDB";
            $table->charset = 'utf8mb4';
            $table->collation = 'utf8mb4_unicode_ci';
        });

Schema::create('selected_product_categories', function (Blueprint $table) {
            $table->id();
            $table->bigInteger('product_id')->unsigned()->default(0);
            $table->foreign('product_id')->references('id')->on('products')->onDelete('cascade');
            $table->bigInteger('category_id')->unsigned()->default(0);
            $table->foreign('category_id')->references('id')->on('categories')->onDelete('cascade');
            $table->timestamps();
        });


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->char('enable', 1)->default(0);
            $table->bigInteger('order')->default(0);
            $table->string('slug', 160)->nullable();
            NestedSet::columns($table);
            $table->engine = "InnoDB";
            $table->charset = 'utf8mb4';
            $table->collation = 'utf8mb4_unicode_ci';
        });

I have this code:

$products = $this->model->getProductFromIdCategories($categories->toArray());

I have error:

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'selected_product_categories.category_id' in 'where clause' (SQL: select * from products where selected_product_categories.category_id in (12)) In array i have this results:

$categories->toArray()



array:19 [▼
  0 => 1
  1 => 2
  2 => 3
  3 => 4
  4 => 5
  5 => 6
  6 => 7
  7 => 8
  8 => 9
  9 => 10
  10 => 11
  11 => 12
  12 => 13
  13 => 14
  14 => 15
  15 => 16
  16 => 17
  17 => 18
  18 => 19
]

My model Product:

class Product extends Model
{
    use ScopeActiveTrait;
    use Slugable;

    public function setNameAttribute($value)
    {
        $this->attributes['name'] = $value;
        $this->attributes['slug'] = $this->makeSlug($value);
    }

    protected $fillable = ['delivery_time', 'product_type', 'name', 'title', 'description', 'keywords', 'content', 'vat_id', 'category_id', 'enable', 'slug', 'small_description'];
    protected $quarded = ['id'];
    public $timestamps = false;

    public function vat()
    {
        return $this->belongsTo('App\Models\VAT', 'vat_id');
    }

    public function category()
    {
        return $this->belongsTo('App\Models\Category', 'category_id');
    }

    public function selectedCategory()
    {
        return $this->hasMany('App\Models\SelectedProductCategory', 'product_id', 'id');
    }

    public function related()
    {
        return $this->belongsTo('App\Models\RelatedProduct');
    }

    public function features()
    {
        return $this->hasMany('App\Models\SelectedProductFeature');
    }



}

How can I repair this ?

I need show all products with selected categories. One product can be assigned to many categories - that's why I use whereIn

Please help me

Activity icon

Started a new Conversation Collection Of Products With Multiple Category IDs

Hi, I am beginner in Laravel. I have this code:

public function descendantsAndSelf(string $slug = null)
    {
        if ($slug == null) {
            return $this->model->active()->get()->pluck('id');
        } else {
            $item = $this->model->where('slug', $slug)->first();
            return $this->model->active()->descendantsAndSelf($item->id ?? 0)->pluck('id');
        }
    }

this return me this:

Illuminate\Support\Collection {#535 ▼
  #items: array:19 [▼
    0 => 1
    1 => 2
    2 => 3
    3 => 4
    4 => 5
    5 => 6
    6 => 7
    7 => 8
    8 => 9
    9 => 10
    10 => 11
    11 => 12
    12 => 13
    13 => 14
    14 => 15
    15 => 16
    16 => 17
    17 => 18
    18 => 19
  ]
}

Now I need search new object

Product::where('id', ....)->get();

is it necessary to enter "where" - as many times as I have id? Is there a more optimal way?

Jul
12
2 months ago
Activity icon

Started a new Conversation Build Multiple Menu From Laravel Array Tree

Hi, I build menu in Bootstrap 4 with: https://packagist.org/packages/kalnoy/nestedset

I have this code:

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->char('enable', 1)->default(0);
            $table->bigInteger('order')->default(0);
            $table->string('slug', 160)->nullable();
            NestedSet::columns($table);
            $table->engine = "InnoDB";
            $table->charset = 'utf8mb4';
            $table->collation = 'utf8mb4_unicode_ci';
        });

I have in my controller:

        $nodes = Category::where('enable', 1)->get()->toTree()
        return view('front.product-list', ['menu'=>$nodes]);

and in view (blade):

<nav class="navbar navbar-expand-lg text-body px-md-0 pb-md-0 navbar-light w-100">
                <a class="navbar-brand" href="/"><img src="{{ asset('img/logo.jpg') }}" class="pb-2"></a>
                <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarmenu"
                        aria-controls="navbarmenu" aria-expanded="false" aria-label="Toggle navigation">
                    <span class="navbar-toggler-icon "></span>
                </button>

                <div class="collapse navbar-collapse" id="navbarmenu">
                    <ul class="navbar-nav">
                        <li class="nav-item dropdown">
                            <a class="nav-link dropdown-toggle" href="#" id="dropdown1" data-toggle="dropdown"
                               aria-haspopup="true"
                               aria-expanded="false">Kategorie <i class="fas fa-angle-down"></i></a>
                            <div class="dropdown-menu" aria-labelledby="dropdown01">
                                <a class="dropdown-item" href="#">Action</a>
                                <a class="dropdown-item" href="#">Another action</a>
                                <a class="dropdown-item" href="#">Something else here</a>
                                <div class="dropdown">
                                    <a class="dropdown-item dropdown-toggle" href="#" id="navbarDropdown" role="button"
                                       data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Dropdown1</a>
                                    <div class="dropdown-menu" aria-labelledby="navbarDropdown">
                                        <a class="dropdown-item" href="#">Action</a>
                                        <a class="dropdown-item" href="#">Another action</a>
                                        <a class="dropdown-item" href="#">Something else here</a>
                                    </div>
                                </div>
                                <a class="dropdown-item" href="#">xxxx</a>
                                <a class="dropdown-item" href="#">xxxx</a>
                                <div class="dropdown">
                                    <a class="dropdown-item dropdown-toggle" href="#" id="navbarDropdown2" role="button"
                                       data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Dropdown2</a>
                                    <div class="dropdown-menu" aria-labelledby="navbarDropdown2">
                                        <a class="dropdown-item" href="#">Action2</a>
                                        <a class="dropdown-item" href="#">Another action2</a>
                                        <div class="dropdown">
                                            <a class="dropdown-item dropdown-toggle" href="#" id="navbarDropdown3"
                                               role="button"
                                               data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Dropdown3</a>
                                            <div class="dropdown-menu" aria-labelledby="navbarDropdown3">
                                                <a class="dropdown-item" href="#">Action 3</a>
                                                <a class="dropdown-item" href="#">Another action 3</a>
                                                <a class="dropdown-item" href="#">Something else here 3</a>
                                            </div>
                                        </div>
                                        <a class="dropdown-item" href="#">Something else here2</a>
                                    </div>
                                </div>

                                @foreach($menu as $value)
                                    @if(!empty($value->children))
                                        <div class="dropdown">
                                            <a class="dropdown-item dropdown-toggle" href="#"
                                               id="navbarDropdown{{ $value->id }}" role="button"
                                               data-toggle="dropdown" aria-haspopup="true"
                                               aria-expanded="false">{{ $value->category_name }}</a>
                                            <div class="dropdown-menu" aria-labelledby="navbarDropdown{{ $value->id }}">


                                                @foreach($value->children as $value2)
                                                    @if(!empty($value2->children))
                                                        <div class="dropdown">
                                                            <a class="dropdown-item dropdown-toggle" href="#"
                                                               id="navbarDropdown{{ $value2->id }}" role="button"
                                                               data-toggle="dropdown" aria-haspopup="true"
                                                               aria-expanded="false">{{ $value2->category_name }}</a>
                                                            <div class="dropdown-menu"
                                                                 aria-labelledby="navbarDropdown{{ $value2->id }}">
                                                                .....next level ......
                                                            </div>
                                                        </div>
                                                    @else
                                                        <a class="dropdown-item"
                                                           href="#">{{ $value->category_name }} </a>
                                                    @endif
                                                @endforeach
                                            </div>
                                        </div>


                                    @else
                                        <a class="dropdown-item" href="#">{{ $value->category_name }} </a>
                                    @endif
                                @endforeach

                            </div>
                        </li>

                       
                    </ul>
                </div>
            </nav>

I have problem with this part of code:

@foreach($value->children as $value2)
                                                    @if(!empty($value2->children))
                                                        <div class="dropdown">
                                                            <a class="dropdown-item dropdown-toggle" href="#"
                                                               id="navbarDropdown{{ $value2->id }}" role="button"
                                                               data-toggle="dropdown" aria-haspopup="true"
                                                               aria-expanded="false">{{ $value2->category_name }}</a>
                                                            <div class="dropdown-menu"
                                                                 aria-labelledby="navbarDropdown{{ $value2->id }}">
                                                                .....next level ......
                                                            </div>
                                                        </div>
                                                    @else
                                                        <a class="dropdown-item"
                                                           href="#">{{ $value->category_name }} </a>
                                                    @endif
                                                @endforeach

I have 18 menu levels. Do I have to copy the above code 18 "to build this menu in" ..... next level ...... "? Is there a more universal way?

Please help me.

Activity icon

Replied to Copying Data Between Tables

Can you give me any sample?

Jul
10
2 months ago
Activity icon

Started a new Conversation Generate Multilevel Dropdown Menu Bootstrap 4 In Laravel

Hi, I am beginner web developer. I have project with Bootstrap 4 and Laravel 7.

I have this code:

    <nav class="navbar navbar-expand-lg text-body px-md-0 pb-md-0 navbar-light w-100">
                    <a class="navbar-brand" href="/"><img src="{{ asset('img/logo.jpg') }}" class="pb-2"></a>
                    <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarmenu"
                            aria-controls="navbarmenu" aria-expanded="false" aria-label="Toggle navigation">
                        <span class="navbar-toggler-icon "></span>
                    </button>
    
                    <div class="collapse navbar-collapse" id="navbarmenu">
                        <ul class="navbar-nav">
    
                            <li class="nav-item dropdown">
                                <a class="nav-link dropdown-toggle" href="#" id="dropdown1" data-toggle="dropdown"
                                   aria-haspopup="true"
                                   aria-expanded="false">Kategorie <i class="fas fa-angle-down"></i></a>
                                <div class="dropdown-menu" aria-labelledby="dropdown01">
                                    <a class="dropdown-item" href="#">Action</a>
                                    <a class="dropdown-item" href="#">Another action</a>
                                    <a class="dropdown-item" href="#">Something else here</a>
                                </div>
                            </li>
                           
                        </ul>
                    </div>
                </nav>

And my controller:

    public function index(PageRepositoryInterface $pageRepository, CategoryRepositoryInterface $categoryRepository)
        {
            $nodes = $categoryRepository->getCategoriesTreeToSelect();
    
            $traverse = function ($categories, $prefix = '-') use (&$traverse) {
                foreach ($categories as $category) {
                    echo PHP_EOL.$prefix.' '.$category->category_name;
    
                    $traverse($category->children, $prefix.'-');
                }
            };
    
            $traverse($nodes);
            
    
            return view('front.product-list', [....]);
        }

This code return:


    - Books
    -- Comic Book
    --- Marvel Comic Book
    --- DC Comic Book
    ---- Computer Science
    --- Action comics
    -- Textbooks
    --- Business
    --- Finance
    - Electronics
    -- TV
    --- LED
    --- Blu-ray
    -- Mobile
    --- Samsung
    --- iPhone
    --- Xiomi

My model:

    class Category extends Model
    {
        use ScopeActiveTrait;
        use NodeTrait;
        use Slugable;
    
        public function setCategoryNameAttribute($value)
        {
            $this->attributes['category_name'] = $value;
            $this->attributes['slug'] = $this->makeSlug($value);
        }
    
        protected $quarded = ['id'];
        protected $fillable = ['category_name', 'description', 'keywords', 'content', 'enable', 'photo', 'order', 'slug', '_lft', '_rgt', 'parent_id'];
        public $timestamps = false;
    }

I use in my model: https://packagist.org/packages/kalnoy/nestedset

How can I display the multi-level menu in Bootstrap 4 in my code?

My controller actually return my categories tree, but I don't know how show menu with multilevel

Activity icon

Started a new Conversation Copying Data Between Tables

Hi, I have this models

class DeCategories extends Model
{
    use ScopeActiveTrait;

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

    protected $table = 'cms_multikategorie22';
}



class Category extends Model
{
    use ScopeActiveTrait;
    use NodeTrait;
    use Slugable;

    public function setCategoryNameAttribute($value)
    {
        $this->attributes['category_name'] = $value;
        $this->attributes['slug'] = $this->makeSlug($value);
    }

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

}

trait Slugable
{
    protected function makeSlug($value)
    {
        $slug = str_slug($value);

        $count = static::whereRaw("slug RLIKE '^{$slug}(-[0-9]+)?$'")->count();

        return $count ? "{$slug}-{$count}" : $slug;
    }
}

trait ScopeActiveTrait
{
    public function scopeActive($query)
    {
        return $query->where('enable', 1);
    }
}

And controller:

public function index()
    {
        echo 'Importuje <br/>';
        //die();
        $level1 = DeCategories::where('title', "<>", '')->where('parent_id', 325193)->get();
        if (!$level1->isEmpty()) {
            foreach ($level1 as $key1 => $value1) {
                echo $value1->title . "<br/>";

                ////////
                $slug = str_slug($value1->title);
                $next = 1;
                while (Category::where('slug', '=', $slug)->exists()) {
                    $next++;
                    $slug = str_slug($value1->title . '-' . $next);
                }
                ////////

                $category = new Category();
                $category->category_name = $value1->title;
                $category->description = $value1->title;
                $category->keywords = $value1->title;
                $category->content = $value1->id . '-1';
                $category->enable = 1;
                $category->photo = '';
                $category->order = $value1->position;
                $category->parent_id = 0;
                $category->slug = $slug;
                $category->save();
                $id1 = $category->id;


                $level2 = DeCategories::where('parent_id', $value1->id)->get();
                //dump($level2);
                if (!$level2->isEmpty()) {
                    foreach ($level2 as $key2 => $value2) {

                        ////////
                        $slug2 = str_slug($value2->title);
                        $next2 = 1;
                        while (Category::where('slug', '=', $slug2)->exists()) {
                            $next2++;
                            $slug2 = str_slug($value2->title . '-' . $next2);
                        }
                        ////////
                        $category2 = new Category();
                        $category2->category_name = $value2->title;
                        $category2->description = $value2->title;
                        $category2->keywords = $value2->title;
                        $category2->content = $value2->id . '-2';
                        $category2->enable = 1;
                        $category2->photo = '';
                        $category2->order = $value2->position;
                        $category2->parent_id = $id1;
                        $category2->slug = $slug2;
                        $category2->save();

                        $id2 = $category2->id;


                        $level3 = DeCategories::where('parent_id', $value2->id)->get();
                        if (!$level3->isEmpty()  && $value2->id !=""  && $value2->id != null) {
                            foreach ($level3 as $key3 => $value3) {
                                ////////
                                $slug3 = str_slug($value3->title);
                                $next3 = 1;
                                while (Category::where('slug', '=', $slug3)->exists()) {
                                    $next3++;
                                    $slug3 = str_slug($value3->title . '-' . $next3);
                                }
                                ////////

                                $category3 = new Category();
                                $category3->category_name = $value3->title;
                                $category3->description = $value3->title;
                                $category3->keywords = $value3->title;
                                $category3->content = $value3->id . '-3';
                                $category3->enable = 1;
                                $category3->photo = '';
                                $category3->order = $value3->position;
                                $category3->parent_id = $id2;
                                $category3->slug = $slug3;
                                $category3->save();

                                $id3 = $category3->id;


                                $level4 = DeCategories::where('parent_id', $value3->id)->get();
                                if (!$level4->isEmpty()   && $value3->id !=""  && $value3->id != null) {
                                    foreach ($level4 as $key4 => $value4) {

                                        ////////
                                        $slug4 = str_slug($value4->title);
                                        $next4 = 1;
                                        while (Category::where('slug', '=', $slug4)->exists()) {
                                            $next4++;
                                            $slug4 = str_slug($value4->title . '-' . $next4);
                                        }
                                        ////////
                                        $category4 = new Category();
                                        $category4->category_name = $value4->title;
                                        $category4->description = $value4->title;
                                        $category4->keywords = $value4->title;
                                        $category4->content = $value4->id . '-4';
                                        $category4->enable = 1;
                                        $category4->photo = '';
                                        $category4->order = $value4->position;
                                        $category4->parent_id = $id3;
                                        $category4->slug = $slug4;
                                        $category4->save();

                                        $id4 = $category4->id;


                                        $level5 = DeCategories::where('parent_id', $value4->id)->get();
                                        if (!$level5->isEmpty()   && $value4->id !=""  && $value4->id != null) {
                                            foreach ($level5 as $key5 => $value5) {

                                                $slug5 = str_slug($value5->title);
                                                $next5 = 1;
                                                while (Category::where('slug', '=', $slug5)->exists()) {
                                                    $next5++;
                                                    $slug5 = str_slug($value5->title . '-' . $next5);
                                                }
                                                $category5 = new Category();
                                                $category5->category_name = $value5->title;
                                                $category5->description = $value5->title;
                                                $category5->keywords = $value5->title;
                                                $category5->content = $value5->id . '-5';
                                                $category5->enable = 1;
                                                $category5->photo = '';
                                                $category5->order = $value5->position;
                                                $category5->parent_id = $id4;
                                                $category5->slug = $slug5;
                                                $category5->save();

                                                $id5 = $category5->id;

                                                $level6 = DeCategories::where('parent_id', $value5->id)->get();
                                                if (!$level6->isEmpty()   && $value5->id !=""  && $value5->id != null) {
                                                    foreach ($level6 as $key6 => $value6) {

                                                        $slug6 = str_slug($value6->title);
                                                        $next6 = 1;
                                                        while (Category::where('slug', '=', $slug6)->exists()) {
                                                            $next6++;
                                                            $slug6 = str_slug($value6->title . '-' . $next6);
                                                        }
                                                        $category6 = new Category();
                                                        $category6->category_name = $value6->title;
                                                        $category6->description = $value6->title;
                                                        $category6->keywords = $value6->title;
                                                        $category6->content = $value6->id . '-6';
                                                        $category6->enable = 1;
                                                        $category6->photo = '';
                                                        $category6->order = $value6->position;
                                                        $category6->parent_id = $id5;
                                                        $category6->slug = $slug6;
                                                        $category6->save();

                                                        $id6 = $category6->id;


                                                        $level7 = DeCategories::where('parent_id', $value6->id)->get();
                                                        if (!$level7->isEmpty()  && $value6->id !=""  && $value6->id != null) {
                                                            foreach ($level7 as $key7 => $value7) {

                                                                $slug7 = str_slug($value7->title);
                                                                $next7 = 1;
                                                                while (Category::where('slug', '=', $slug7)->exists()) {
                                                                    $next7++;
                                                                    $slug7 = str_slug($value7->title . '-' . $next7);
                                                                }
                                                                $category7 = new Category();
                                                                $category7->category_name = $value7->title;
                                                                $category7->description = $value7->title;
                                                                $category7->keywords = $value7->title;
                                                                $category7->content = $value7->id . '-7';
                                                                $category7->enable = 1;
                                                                $category7->photo = '';
                                                                $category7->order = $value7->position;
                                                                $category7->parent_id = $id6;
                                                                $category7->slug = $slug7;
                                                                $category7->save();

                                                            }
                                                        }


                                                    }
                                                }


                                            }
                                        }

                                    }
                                }
                            }
                        }
                    }
                }
            }

        }
        echo 'finish';
    }

I need to copy records from DeCategories to Categories (about 1.7 million) along with "processing" (new slug etc).

Category use: https://packagist.org/packages/kalnoy/nestedset

The above script works fine, but works many days.

How to optimize / make it work faster?

I am beginner in Laravel. Please help

Jul
06
2 months ago
Activity icon

Started a new Conversation Problem With Dynamic Lightbox - Photos Is Not Visible

Hi, I am beginner web developer. I use in my project Bootstrap 4 and http://sachinchoolur.github.io/lightGallery/demos/dynamic.html.

I have this code:

    $('.showPrv').on('click', function() {
            $.ajax({
                headers: {
                    'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
                },
                url: '{{ route('dropzone.showDropZoneGallery') }}?id={{ $fileId }}',
                dataType: 'text',
                type: 'get',
                cache: false,
                data: $(this).serialize(),
                success: function (data, textStatus, jQxhr) {
                    $(this).lightGallery({
                        dynamic: true,
                        dynamicEl: [data],
                        thumbnail:true,
                        animateThumb: true,
                        download: true,
                        counter: true,
                        enableDrag: true,
                        enableSwipe: true
                    });
                    console.log(data);
                },
                error: function (jqXhr, textStatus, errorThrown) {
                    alert('Nastąpił problem z JSON. Proszę o kontakt z administratorem serwisu.');
                }
            });
        })

Console.log return:


But in Lightbox photos is not visible. I have

When I copy this array to html code:

                dynamicEl: [{"src":"http:\/\/name.test\/upload\/DZ_TEXT_PAGE\/3c5ed6a66822be7ea490b9e446de1451.jpeg","thumb":"http:\/\/name.test\/upload\/DZ_TEXT_PAGE\/3c5ed6a66822be7ea490b9e446de1451.jpeg","subHtml":"txt1"},{"src":"http:\/\/name.test\/upload\/DZ_TEXT_PAGE\/87dd197957c0e3720f59f049235d093a.jpeg","thumb":"http:\/\/name.test\/upload\/DZ_TEXT_PAGE\/87dd197957c0e3720f59f049235d093a.jpeg","subHtml":"txt2"}],

it's work fine.

How can I repair it?

Jun
25
3 months ago
Activity icon

Replied to Search And Save Items From The Array To The Database

Ok, I found solution.

I convert my array by this script:

$selectedCountertops = array();
        $selectedPlates = array();
        if (isset($sCountertops)) {
            foreach ($sCountertops as $key => $value) {
                $selectedCountertops['countertop[' . $value['countertops_id'] . '][max]'] = $value['maxvalue'];
                $selectedCountertops['countertop[' . $value['countertops_id'] . '][min]'] = $value['minvalue'];
                $selectedCountertops['countertop[' . $value['countertops_id'] . '][checkbox]'] = $value['status'];
            }
        }
        if (isset($sPlates)) {
            foreach ($sPlates as $key => $value) {
                $selectedPlates['plate[' . $value['plate_id'] . '][max]'] = $value['maxvalue'];
                $selectedPlates['plate[' . $value['plate_id'] . '][min]'] = $value['minvalue'];
                $selectedPlates['plate[' . $value['plate_id'] . '][checkbox]'] = $value['status'];
            }
        }

Maybe someone needs a solution :)

Thank you very much for help @michaloravec :)

Activity icon

Replied to Search And Save Items From The Array To The Database

Sorry, but I think we understand each other badly :) At the moment, this current code saves data to the database correctly. Thanks for helping with this.

I only have a problem inserting them into the blade form. And that's it. The controller has correct data (I put them in the code above). Everything saves and updates in its current form correctly :)

I have a problem to complete my form with these data:

array: 2 [▼
  0 => array: 8 [▼
    "id" => 1
    "countertops_id" => 8
    "product_id" => 10
    "status" => "1"
    "maxvalue" => "88.00"
    "minvalue" => "99.00"
    "created_at" => "2020-06-25T09: 44: 17.000000Z"
    "updated_at" => "2020-06-25T09: 44: 17.000000Z"
  ]
  1 => array: 8 [▼
    "id" => 2
    "countertops_id" => 9
    "product_id" => 10
    "status" => "1"
    "maxvalue" => "66.00"
    "minvalue" => "77.00"
    "created_at" => "2020-06-25T09: 44: 17.000000Z"
    "updated_at" => "2020-06-25T09: 44: 17.000000Z"
  ]
]

This is already database data. I want to put this data in the appropriate fields of the form :)