trifek

Member Since 1 Year Ago

Experience Points
5,600
Total
Experience

4,400 experience to go until the next level!

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

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

    Start Your Engines

    Earned once you have completed your first Laracasts lesson.

  • first-thousand Created with Sketch.

    First Thousand

    Earned once you have earned your first 1000 experience points.

  • 1-year Created with Sketch.

    One Year Member

    Earned when you have been with Laracasts for 1 year.

  • 2-years Created with Sketch.

    Two Year Member

    Earned when you have been with Laracasts for 2 years.

  • 3-years Created with Sketch.

    Three Year Member

    Earned when you have been with Laracasts for 3 years.

  • 4-years Created with Sketch.

    Four Year Member

    Earned when you have been with Laracasts for 4 years.

  • 5-years Created with Sketch.

    Five Year Member

    Earned when you have been with Laracasts for 5 years.

  • school-in-session Created with Sketch.

    School In Session

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

  • welcome-newcomer Created with Sketch.

    Welcome To The Community

    Earned after your first post on the Laracasts forum.

  • full-time-student Created with Sketch.

    Full Time Learner

    Earned once 100 Laracasts lessons have been completed.

  • pay-it-forward Created with Sketch.

    Pay It Forward

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

  • subscriber Created with Sketch.

    Subscriber

    Earned if you are a paying Laracasts subscriber.

  • lifer Created with Sketch.

    Lifer

    Earned if you have a lifetime subscription to Laracasts.

  • evangelist Created with Sketch.

    Laracasts Evangelist

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

  • chatty-cathy Created with Sketch.

    Chatty Cathy

    Earned once you have achieved 500 forum replies.

  • lara-veteran Created with Sketch.

    Laracasts Veteran

    Earned once your experience points passes 100,000.

  • 10k-strong Created with Sketch.

    Ten Thousand Strong

    Earned once your experience points hits 10,000.

  • lara-master Created with Sketch.

    Laracasts Master

    Earned once 1000 Laracasts lessons have been completed.

  • laracasts-tutor Created with Sketch.

    Laracasts Tutor

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

  • laracasts-sensei Created with Sketch.

    Laracasts Sensei

    Earned once your experience points passes 1 million.

  • top-50 Created with Sketch.

    Top 50

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

  • Community Pillar

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

Level 2
5,600 XP
May
12
4 days ago
Activity icon

Started a new Conversation Crop Out Image Margin In Base64

I am beginner php programmer. I have upload image system in my project. It's written in Laravel 8.

i have this code:

    $imageInBase64 = 'data:image/png;base64,iVBORw0KYq6hP//5zzmAc/DBB5f2XYxR/hpl06IVmU3FuqJaTZHJUSyf0GuUsosATVS3KW8xRsyTFOXlIuOnKJ0XfWr.......=';

I need cut 100px from left site my image.

Full code base64 with my image is here: https://paste-bin.xyz/25692

How can I make it?

Activity icon

Started a new Conversation Add A Chart In Lavacharts

Hi, I am beginner in Laravel. I write my project in Laravel 8. I want add to my website this charts: http://lavacharts.com/api/2.5/Khill/Lavacharts/DataTables/DataTable.html#method_addColumns , http://lavacharts.com/#examples

In result I need: https://ibb.co/cyxGNff

I make this code:

use Khill\Lavacharts\Lavacharts

$imgItems = \Lava::DataTable();

        $imgItems->addColumns([
            ['number', 'Miedź [CU]'],
            ['number', 'Złoto [Au]'],
            ['number', 'Srebro [Ag]'],
            ['number', 'Składnik 2 [Składnik 2]']
        ]);


        $rowData = [
            rand(10, 100), rand(10, 100), rand(10, 100), rand(10, 100)
        ];

        $imgItems->addRow($rowData);

       \Lava::ColumnChart('imgitems', $imgItems, [
            'title' => 'Raport',
            'axisTitlesPosition' => 'in',
            'legend' => [
                'position' => 'bottom'
            ],
            'titleTextStyle' => [
                'color' => '#eb6b2c',
                'fontSize' => 14
            ],
            'events' => [
            ]
        ]);

In result is: https://ibb.co/0yQxn7k

I have problem with:

  • I give 4 types of data: Miedź [CU], Złoto [Au], Srebro [Ag], Składnik 2 [Składnik 2] - and the graph shows 3
  • The X axis is to contain the element names as in the original image. There are currently some numbers in there

How can I fix it? Please help me

May
10
6 days ago
Activity icon

Started a new Conversation Save Charts To PDF In Laravel

Hi, I am beginner. I make my project in Laravel 8. I use components: https://www.chartjs.org and barryvdh/laravel-dompdf , fx3costa/laravelchartjs. In view I have chart. It's work fine, but in PDF my chart is invisible. I found info with information about Dompdf has problem with js.

Do you know any way to add charts to PDF in this library or some other?

May
08
1 week ago
Activity icon

Started a new Conversation Summary Records With A Specific Value In Laravel

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

I have this code:

$items = $this->selectedProductIngredient->where('single_product_analysis_id', $id)->where('group_id', 0)->where('type', 1)->get();

This is my items / values for report.

In result I have something like this:

#items: array:3 [▼
    0 => App\Models\SelectedProductIngredient {#1964 ▼
      #fillable: array:6 [▶]
      #guarded: array:1 [▶]
      #dates: array:2 [▶]
      #casts: array:2 [▶]
      #connection: "mysql"
      #table: "selected_product_ingredients"
      #primaryKey: "id"
      #keyType: "int"
      +incrementing: true
      #with: []
      #withCount: []
      #perPage: 15
      +exists: true
      +wasRecentlyCreated: false
      #attributes: array:9 [▼
        "id" => 304
        "product_id" => 10
        "ingredient_id" => 7
        "single_product_analysis_id" => 31
        "weight" => "11.000"
        "type" => "1"
        "group_id" => 0
        "created_at" => "2021-05-07 16:50:18"
        "updated_at" => "2021-05-07 16:50:18"
      ]
      #original: array:9 [▶]
      #changes: []
      #classCastCache: []
      #dateFormat: null
      #appends: []
      #dispatchesEvents: []
      #observables: []
      #relations: array:1 [▶]
      #touches: []
      +timestamps: true
      #hidden: []
      #visible: []
    }
    1 => App\Models\SelectedProductIngredient {#1963 ▶}
    2 => App\Models\SelectedProductIngredient {#1962 ▶}

My migration:

Schema::create('selected_product_ingredients', function (Blueprint $table) {
            $table->id();
            $table->bigInteger('product_id')->unsigned()->default(0);
            $table->foreign('product_id')->references('id')->on('products')->onDelete('cascade');
            $table->bigInteger('ingredient_id')->unsigned()->default(0);
            $table->bigInteger('group_id')->unsigned()->default(0);
            $table->bigInteger('single_product_analysis_id')->unsigned()->default(0);
            $table->boolean('type')->default(false);
            $table->decimal('weight', 12, 3)->nullable()->default(0);
            $table->foreign('ingredient_id')->references('id')->on('laboratoryingredients')->onDelete('cascade');
            $table->timestamps();
        });

And I create array for report:

$names = [];
$data = [];
foreach ($items as $item){
            array_push($names, $item-> ingredient_id');
            array_push($data, $item->weight);
        }

I have 2 small problems:

  1. I have different values for ingredient_id in the database. (multiple records). I need to add them up weight based on ingredient_id.

  2. In foreach, I need get only first 15 summary weight (based on ingredient_id) ordered by max weight DESC.

How can I make it?

Please help me.

Apr
30
2 weeks ago
Activity icon

Started a new Conversation View Records Related To Other Records In Laravel

Hi, I am beginner in Laravel. I write my project in Laravel 8.

I have this migration:

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->bigInteger('company_id')->unsigned();
            $table->foreign('company_id')->references('id')->on('companies')->onDelete('cascade');
            $table->bigInteger('category_id1')->default(0);
            $table->bigInteger('category_id2')->default(0);
            $table->bigInteger('category_id3')->default(0);
            $table->bigInteger('category_id4')->default(0);
            $table->bigInteger('category_id5')->default(0);
            $table->bigInteger('category_id6')->default(0);
            $table->bigInteger('category_id7')->default(0);
            $table->bigInteger('category_id8')->default(0);
            $table->decimal('price', 12, 2)->default(0);
            $table->decimal('price_promo', 12, 2)->default(0);
            $table->bigInteger('vat_id')->unsigned();
            $table->foreign('vat_id')->references('id')->on('vat_types');
            $table->bigInteger('category_id')->unsigned();
            //$table->foreign('category_id')->references('id')->on('categories');
            $table->bigInteger('producer_id')->unsigned();
            $table->smallInteger('classification')->unsigned()->default(0);
            $table->integer('quantity')->unsigned()->default(0);
            $table->string('code_qr', 250)->nullable();
            $table->string('code_oe', 250)->nullable();
            $table->string('vin', 250)->nullable();
            $table->smallInteger('origin_head')->unsigned()->default(0);
            $table->smallInteger('origin_complete_car')->unsigned()->default(0);
            $table->smallInteger('origin_incomplete_car')->unsigned()->default(0);
            $table->boolean('enable')->default(false);
            $table->boolean('used_product')->default(true);
            $table->boolean('used_product_sold')->default(false);
            $table->string('slug', 160);
            $table->softDeletes();
            $table->timestamps();
            $table->engine = "InnoDB";
            $table->charset = 'utf8mb4';
            $table->collation = 'utf8mb4_unicode_ci';
        });


Schema::create('selected_product_ingredients', function (Blueprint $table) {
            $table->id();
            $table->bigInteger('product_id')->unsigned()->default(0);
            $table->foreign('product_id')->references('id')->on('products')->onDelete('cascade');
            $table->bigInteger('ingredient_id')->unsigned()->default(0);
            $table->bigInteger('group_id')->unsigned()->default(0);
            $table->boolean('type')->default(false);
            $table->decimal('weight', 12, 3)->nullable()->default(0);
            $table->foreign('ingredient_id')->references('id')->on('laboratoryingredients')->onDelete('cascade');
            $table->timestamps();
        });

I need to display all products that relate to products in the lab (selected_product_ingredients)

I make:

Product->where('enable', 1)->get();

I don't know how to add checking if a product has any records in selected_product_ingredients. How can I do this?

Please help.

Apr
26
2 weeks ago
Activity icon

Started a new Conversation Filtering On The Created_at Field

Hi, I am beginner in Laravel. I write my project using Laravel 8.

I have this migration:

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->bigInteger('company_id')->unsigned();
            $table->foreign('company_id')->references('id')->on('companies')->onDelete('cascade');
            $table->bigInteger('category_id1')->default(0);
            $table->bigInteger('category_id2')->default(0);
            $table->bigInteger('category_id3')->default(0);
            $table->bigInteger('category_id4')->default(0);
            $table->bigInteger('category_id5')->default(0);
            $table->bigInteger('category_id6')->default(0);
            $table->bigInteger('category_id7')->default(0);
            $table->bigInteger('category_id8')->default(0);
            $table->decimal('price', 12, 2)->default(0);
            $table->decimal('price_promo', 12, 2)->default(0);
            $table->bigInteger('vat_id')->unsigned();
            $table->foreign('vat_id')->references('id')->on('vat_types');
            $table->bigInteger('category_id')->unsigned();
            //$table->foreign('category_id')->references('id')->on('categories');
            $table->bigInteger('producer_id')->unsigned();
            $table->smallInteger('classification')->unsigned()->default(0);
            $table->integer('quantity')->unsigned()->default(0);
            $table->string('code_qr', 250)->nullable();
            $table->string('code_oe', 250)->nullable();
            $table->string('vin', 250)->nullable();
            $table->smallInteger('origin_head')->unsigned()->default(0);
            $table->smallInteger('origin_complete_car')->unsigned()->default(0);
            $table->smallInteger('origin_incomplete_car')->unsigned()->default(0);
            $table->boolean('enable')->default(false);
            $table->boolean('used_product')->default(true);
            $table->boolean('used_product_sold')->default(false);
            $table->string('slug', 160);
            $table->softDeletes();
            $table->timestamps();
            $table->engine = "InnoDB";
            $table->charset = 'utf8mb4';
            $table->collation = 'utf8mb4_unicode_ci';
        });

and my controller:


public function __construct(Product $product)
    {
        $this->product = $product;
    }

    public function download(Request $request)
    {
		$dataTo = $request->input('data_to');
		$products = $this->product->whereDate('created_at', $dataTo)->get();
	}

This works fine, however, it only displays products for the selected day. I would like products to be displayed from the beginning to the selected day. How can I do this?

Please help,

Apr
22
3 weeks ago
Activity icon

Started a new Conversation Adding A Div Row For A New Row In Laravel

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

I have this code:

@foreach($productIngredients as $productIngredient)
                                    @php
                                        if($selectedProductIngredients->contains('ingredient_id', $productIngredient->id) === true){
                                            $item = \App\Models\SelectedProductIngredient::where('product_id', $product->id)->where('ingredient_id', $productIngredient->id)->first();
                                            $weight = $item->weight;
                                        } else {
                                            $weight = null;
                                        }
                                    @endphp

                                    <div class="col-6">
                                        <div class="form-check py-2">
                                            <input id="productIngredientId-{{ $productIngredient->id }}"
                                                   class="form-check-input enableInput" style="margin-top:10px"
                                                   name="productIngredient[]" type="checkbox"
                                                   value="{{ $productIngredient->id }}"
                                                   @if($selectedProductIngredients->contains('ingredient_id', $productIngredient->id) === true) checked @endif>
                                            <label class="form-check-label" for="flexCheckChecked">
                                                {{ $productIngredient->name }} [{{ $productIngredient->short_name }}]
                                            </label>
                                            <input id="productIngredient-{{ $productIngredient->id }}" type="text"
                                                   name="productIngredient-{{ $productIngredient->id }}" maxlength="10"
                                                   class="form-control weight-input weightMask"
                                                   style="width:100px;display: inline; margin-left:20px" placeholder=""
                                                   value="{{ $weight }}">
                                        </div>
                                    </div>
                                @endforeach

It's work fine.

I would like there to be 2 records in 1 row. So I would like to add at the beginning and close div in case of the last record

How can I do this?

Please help me.

Apr
08
1 month ago
Activity icon

Started a new Conversation Manual User Logout

Hi, I have project in Laravel 8. I need make route to auto logout user.

I make this:

Route::get('/autoLogoutUser', '[email protected]')->name('autoLogoutUser');
public function autoLogoutUser(Request $request){
        Auth::logout();
        $request->session()->invalidate();
        return redirect('/login');
    }

I have problem in firefox. Firefox cache my view, when I was login and I have problem with login again (in login form). When I make F5 in my browser, then it's work fine again.

How can I repair it?

Feb
19
2 months ago
Activity icon

Started a new Conversation Module Build Failed When Build Sass In Laravel

Hi, I am beginner Laravel developer. I use in my project Laravel 8. I have in my resources/scss/front/app.js this code:

// Fonts
@import url('https://fonts.googleapis.com/css?family=Nunito');

// Variables
@import 'utils/variables';

// Bootstrap
@import '~bootstrap/scss/bootstrap';
@import '~animate.css';
@import '~jquery-colorbox';

@import "main";
@import "layout/contact";
@import "layout/gallery";
@import "layout/home";
@import "layout/occupation";
@import "layout/splash";
@import "layout/staff";
@import "layout/tariff";
@import "layout/txt";

@import "layout/partials/top";
@import "layout/partials/footer";

When I compile my code (nom run watch) I have error:

ERROR in ./resources/sass/front/app.scss
Module build failed (from ./node_modules/css-loader/index.js):
ModuleBuildError: Module build failed (from ./node_modules/sass-loader/dist/cjs.js):
SassError: Can't find stylesheet to import.
   ╷
10 │ @import 'node_modules/jquery-colorbox';

How can I repair it?

Feb
18
2 months ago
Activity icon

Started a new Conversation Problem With Slug Translate

Hi, I am beginner in Laravel. I use in. my project Laravel 8. I have this migration:

public function up()
    {
        Schema::create('pages', function (Blueprint $table) {
            $table->id();
            $table->string('titlePL', 155);
            $table->string('descriptionPL', 155)->nullable();
            $table->string('keywordsPL', 155)->nullable();
            $table->longText('contentPL')->nullable();

            $table->string('titleEN', 155);
            $table->string('descriptionEN', 155)->nullable();
            $table->string('keywordsEN', 155)->nullable();
            $table->longText('contentEN')->nullable();

            $table->boolean('enable')->default(false);
            $table->boolean('system')->default(false);
            $table->string('slugPL', 160);
            $table->string('slugEN', 160);
            $table->timestamps();
            $table->engine = "InnoDB";
            $table->charset = 'utf8mb4';
            $table->collation = 'utf8mb4_unicode_ci';
        });
    }

and model:

class Page extends Model
{
    use ScopeActiveTrait,
        HasSlug;

    protected $guarded = ['id'];

    protected $fillable = [
        'titlePL',
        'descriptionPL',
        'keywordsPL',
        'contentPL',
        'enable',
        'slugPL',
        'slugEN',
        'titleEN',
        'descriptionEN',
        'keywordsEN',
        'contentEN',
    ];

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

    protected $casts = [
        'enable'=>'boolean'
    ];

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

    public function setSlugENAttribute($value)
    {
        if (static::where('slugEN', str_slug($this->slugEN))->exists()) {
            $this->attributes['slugEN'] = "{str_slug($this->slugEN)}-{$this->id}";
        }
        $this->attributes['slugEN'] = str_slug($this->slugEN);
    }

}

I use in my project Spatie\Sluggable, but it's not working with translations.

For slugEN I want create unique slug manuals.

I have problem with setSlugENAttribute - it's not working.

If I save my data by this function:

public function store(PageCreateRequest $request)
    {
        $data = $request->only(['titlePL', 'contentPL', 'titleEN', 'contentEN']);
        $data['descriptionPL'] = $request->input('descriptionPL') ?? $request->input('titlePL');
        $data['keywordsPL'] = $request->input('keywordsPL') ?? $request->input('titlePL');
        $data['descriptionEN'] = $request->input('descriptionEN') ?? $request->input('titleEN');
        $data['keywordsEN'] = $request->input('keywordsEN') ?? $request->input('titleEN');
        $data['enable'] = $request->enable ?? 0;
        $this->model->create($data);
        return redirect()->route('pages.index')->with('success', 'Nowy rekord zapisany poprawnie');
    }

I have in result only slugPL. How can I repair it?

Feb
12
3 months ago
Activity icon

Replied to Redirect To Login Page If User Not Login

Can you show me how can I make it? (no middleware copying to each route)

Activity icon

Replied to Redirect To Login Page If User Not Login

Can I use this global for all routes in:

Route::group(['prefix' => '', 'middleware' => ['role:superadmin|admin|seller|telemarketer']], function () {
...
"

??

Activity icon

Started a new Conversation Redirect To Login Page If User Not Login

Hi, I have this route file:

use Illuminate\Support\Facades\Route;


/* Password Remind */

Route::get('remind-admin-password', '[email protected]')->name('cms.remind_admin_password');
Route::post('update-admin-password', '[email protected]')->name('cms.remind_admin_update');


Route::name('cms.')->group(function () {
    Auth::routes(['register' => false, 'reset' => false, 'confirm' => false, 'verify' => false]);


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


Route::group(['prefix' => '', 'middleware' => ['role:superadmin|admin|seller|telemarketer']], function () {
    Route::get('/', '[email protected]')->name('cms.home');
    //    Route::prefix('admin') ->middleware('auth') ->group(function () {

    /* Pages */
    Route::resource('pages', 'PageController')->only(['index', 'create', 'store', 'edit', 'update', 'destroy']);
    Route::get('/pages/dataTable', '[email protected]')->name('pages.dataTable');

    /* Users */
    Route::resource('clients', 'ClientController')->only(['index', 'create', 'store', 'edit', 'update', 'destroy']);
    Route::get('/clients/dataTable', '[email protected]')->name('clients.dataTable');
    Route::get('/clients/dataTableOrder', '[email protected]')->name('clients.dataTableOrder');


});

It's work fine. Problem is when user in not login. I put to browser url: domain.com/cms/pages - and I have error: 403 USER IS NOT LOGGED IN.

I need redirect in this situation to domain.com/cms/login

I use Laravel 7 in my project.

How can I make it?

Jan
28
3 months ago
Activity icon

Started a new Conversation .Htaccess Index Php / Html Redirect To Main Page

I have this .htaccess. I would like:

That he would direct from www.domena.pl to domena.pl (I have it done) to always point to https after entering domena.pl/index php or index html -> redirected to https domena.pl How can I make it?

My htacess:

  RewriteEngine On
     # Redirect to non www
     RewriteCond% {HTTP_HOST} ^ www.domena.pl $ [NC]
     RewriteRule ^ (. *) $ Https://domena.pl/ [R = 301, L] 

Please help

Jan
26
3 months ago
Activity icon

Replied to Search In Laravel Relation Using Json Column

I know, it would be the easiest way. Unfortunately, I cannot change the tables / columns anymore. :(

Activity icon

Started a new Conversation Search In Laravel Relation Using Json Column

Hi, I have problem with search in json column.

I have 3 relations:

  • products

  • feature products

  • feature_values

My tables:

My migrations:

Product:

class Product extends Model implements Presentable
{
....
public function featureProducts()
    {
       return $this->hasMany(FeatureProduct::class, 'product_id');
        //return $this->belongsToMany(Feature::class, 'feature_product', 'id');
    }
}

FeatureProduct

class FeatureProduct extends Model
{
    protected $table = "feature_product";

    protected $with = [
        'values'
    ];

    public function values()
    {
        return $this->belongsTo(FeatureValue::class, 'feature_values_ids', 'id');
    }

}

FeatureValues:

class FeatureValue extends Model
{
    use SoftDeletes,
        Translatable;

    protected $fillable = [
        'feature_id',
        'value'
    ];

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

    protected $translatable = [
        'value'
    ];

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

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

I need to show products with features and assigned features_values

I heve problem with search in json column: feature_product. feature_values_ids

When I have INT in this column, then this is working fine:

public function values()
    {
        return $this->belongsTo(FeatureValue::class, 'feature_values_ids', 'id');
    }

When I have:

["1", "2","3"]

I haven't any results :(

Haw can I repair it?

Activity icon

Replied to Array To String Conversion With Sync) Error

I want save my array to DB :) I change in my code field "feature_values_ids" from NUMBER to JSON and now I have this problem.

I found problem in this line: $model->features()->sync($featuresData);

Activity icon

Started a new Conversation Array To String Conversion With Sync) Error

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

$featuresData = collect($request->get('features'))->filter(function ($values, $featureId) {
            return count(array_filter($values)) > 0;
        })->toArray();

This return me:

array:2 [▼
  5 => array:2 [▼
    "feature_values_ids" => array:2 [▼
      0 => "4"
      1 => "6"
    ]
    "custom_value" => "111"
  ]
  6 => array:2 [▼
    "feature_values_ids" => array:2 [▼
      0 => "1"
      1 => "2"
    ]
    "custom_value" => "222"
  ]
]

I want save my array to DB. I change in my original code field "feature_values_ids" from NUMBER to JSON and now I have this problem.

I found problem in this line: $model->features()->sync($featuresData);

When I run this code I have this error:


[2021-01-26 12:13:52] local.ERROR: Array to string conversion {"userId":1,"exception":"[object] (ErrorException(code: 0): Array to string conversion at /www/vendor/laravel/framework/src/Illuminate/Support/Str.php:488)
[stacktrace]
#0 /www/vendor/laravel/framework/src/Illuminate/Support/Str.php(488): Illuminate\Foundation\Bootstrap\HandleExceptions->handleError(8, 'Array to string...', '/Users/...', 488, Array)
#1 /www/vendor/laravel/framework/src/Illuminate/Database/QueryException.php(57): Illuminate\Support\Str::replaceArray('?', Array, 'insert into `fe...')
#2 /www/vendor/laravel/framework/src/Illuminate/Database/QueryException.php(40): Illuminate\Database\QueryException->formatMessage('insert into `fe...', Array, Object(ErrorException))
#3 /www/vendor/laravel/framework/src/Illuminate/Database/Connection.php(672): Illuminate\Database\QueryException->__construct('insert into `fe...', Array, Object(ErrorException))
#4 /www/vendor/laravel/framework/src/Illuminate/Database/Connection.php(631): Illuminate\Database\Connection->runQueryCallback('insert into `fe...', Array, Object(Closure))
#5 /www/vendor/laravel/framework/src/Illuminate/Database/Connection.php(465): Illuminate\Database\Connection->run('insert into `fe...', Array, Object(Closure))
#6 /www/vendor/laravel/framework/src/Illuminate/Database/Connection.php(417): Illuminate\Database\Connection->statement('insert into `fe...', Array)
#7 /www/vendor/laravel/framework/src/Illuminate/Database/Query/Builder.php(2827): Illuminate\Database\Connection->insert('insert into `fe...', Array)
#8 /www/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Relations/Concerns/InteractsWithPivotTable.php(254): Illuminate\Database\Query\Builder->insert(Array)
#9 /www/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Relations/Concerns/InteractsWithPivotTable.php(160): Illuminate\Database\Eloquent\Relations\BelongsToMany->attach(5, Array, false)
#10 /www/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Relations/Concerns/InteractsWithPivotTable.php(112): Illuminate\Database\Eloquent\Relations\BelongsToMany->attachNew(Array, Array, false)
#11 /www/app/Repositories/ProductRepository.php(40): Illuminate\Database\Eloquent\Relations\BelongsToMany->sync(Array)

My Databases: https://ibb.co/Bt4v11H

Model Product:

<?php

namespace App\Models\Catalog;

use App\Interfaces\Presentable;
use App\Models\{Discount, FeatureProduct, Image, ProductCategory, VatType};
use App\Presenters\{
    AbstractAdminUrlPresenter,
    Admin\ProductUrlPresenter,
    Front\ProductUrlPresenter as FrontUrlPresenter
};
use App\Traits\{
    Deactivation,
    Filterable,
    Imageable,
    Seoable,
    Taggable,
    Translatable
};
use Illuminate\Database\Eloquent\{
    Builder,
    Model,
    Relations\BelongsTo,
    SoftDeletes
};
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Support\Collection;
use Illuminate\Support\Str;

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

    const AVAILABILITY_IN_STOCK = 'in_stock';
    const AVAILABILITY_OUT_OF_STOCK = 'out_of_stock';
    const AVAILABILITY_PREORDER = 'preorder';

    const AVAILABILITY_OPTIONS = [
        self::AVAILABILITY_IN_STOCK => '24 godziny',
        self::AVAILABILITY_OUT_OF_STOCK => '7 dni',
        self::AVAILABILITY_PREORDER => 'Preorder'
    ];

    /**
     * Discount for price
     *
     * @var Discount|null
     */
    public $discount = null;

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

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

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

    protected $with = [
        'features'
    ];

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

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

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


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

    public function getUrlAttribute()
    {
        return new FrontUrlPresenter($this);
    }

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

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

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

    public function featureValue($key, $default = ""): ?string
    {
        if(! $this->relationLoaded('features')) {
            return $default;
        }

        $feature = $this->features->firstWhere('key', $key);

        return $this->getValueOfFeature($feature, $default);
    }

    private function getValueOfFeature(?Feature $feature, $default = ""): ?string {
        if(is_null($feature)) {
            return $default;
        }

        if(is_null($featureValueId = data_get($feature, 'pivot.feature_values_ids'))) {
            return data_get_empty_check($feature, 'pivot.custom_value', $default);
        }

        if(is_null($featureValue = $feature->values->firstWhere('id', $featureValueId)) || empty($featureValue->value)) {
            return $default;
        }

        return $featureValue->value;
    }

    public static function availabilityOptionsList(): array {
        return collect(self::AVAILABILITY_OPTIONS)->map(function($value, $key) {
            return [
                'key' => $key,
                'value' => __($value)
            ];
        })->values()->toArray();
    }

    public function isPreorder() :bool
    {
        return $this->preorder_release_date > today()->format("Y-m-d");
    }

    public function isInStock(): bool
    {
        return $this->stock_quantity > 0;
    }

    public function getStockDetailsAttribute(): string
    {
        if($this->isPreorder()) {
            return __('Preorder');
        }

        return $this->isInStock()
            ? __('Wysyłamy w 24 godziny')
            : __('Wysyłamy w 7 dni');
    }

    public function featureValues($skipFields = []): Collection {
        return $this->features->filter(function($feature) use($skipFields) {
            return ! in_array($feature->key, $skipFields);
        })->map(function($feature) {
            return [
                'name' => $feature->name,
                'value' => $this->getValueOfFeature($feature)
            ];
        })->values()->filter(function($item) {
            return !empty($item['value']);
        });
    }

    public function loadDiscount(): self
    {
        if (empty($this->id)) {
            return $this;
        }

        $this->discount = $this->getDiscount();

        return $this;
    }

    private function getDiscount(): ?Discount
    {
        return Discount::where(function (Builder $query) {
            $query->whereHas('products', function (Builder $q) {
                $q->where('products.id', '=', $this->id);
            })->orWhereHas('categories', function (Builder $q) {
                $q->where('product_categories.id', '=', $this->productCategory->id);
            });
        })
            ->get()
            ->sortBy(function (Discount $discount) {
                return $discount->calculatePrice($this->price);
            })
            ->first();
    }

    public function scopeWithDiscount(Builder $query)
    {
        $subQuery = Discount::selectRaw("case
                when discounts.type = '" . Discount::DISCOUNT_AMOUNT . "' then products.price - discounts.value
                when discounts.type = '" . Discount::DISCOUNT_PERCENT . "' then ROUND((1 - discounts.value/100) * products.price, 2)
                else products.price
                end final_price"
        )
            ->leftJoin('discountables', 'discountables.discount_id', '=', 'discounts.id')
            ->where(function($q) {
                return $q->whereRaw("discountables.discountable_type = '" . addslashes(Product::class) . "'")
                    ->whereColumn('discountables.discountable_id', 'products.id');
            })
            ->orWhere(function($q) {
                return $q->whereRaw("discountables.discountable_type = '" . addslashes(ProductCategory::class) . "'")
                    ->whereColumn('discountables.discountable_id', 'products.product_category_id');
            })
            ->orderBy('final_price')
            ->limit(1);

        return $query->addSelect([
            'final_price' =>  function ($query) use($subQuery) {
                $query->selectRaw('ifnull((' . $subQuery->toSql() . '), products.price)');
            }
        ]);
    }
}

How can I repair it?

Jan
12
4 months ago
Activity icon

Started a new Conversation Get Value From Model To Blade In Laravel

Hi, I am beginner in Laravel. I have model:

    class Discount extends Model
    {
        use Deactivation,
            SoftDeletes;
    
        const DISCOUNT_AMOUNT = 'amount';
        const DISCOUNT_PERCENT = 'percent';
    
        const DISCOUNT_TYPES = [
            self::DISCOUNT_AMOUNT => 'kwotowy',
            self::DISCOUNT_PERCENT => 'procentowy'
        ];
    
        protected $guarded = ['id'];
    
        protected $fillable = [
            'name',
            'value',
            'type',
            'deactivated_at'
        ];
    
        protected $dates = [
            'created_at',
            'updated_at',
            'deleted_at'
        ];
    
    
        public function getAdminUrlAttribute(): AbstractAdminUrlPresenter
        {
            return new DiscountUrlPresenter($this);
        }
    
        public function products()
        {
            return $this->morphedByMany(Product::class, 'discountable');
        }
    
        public function categories()
        {
            return $this->morphedByMany(ProductCategory::class, 'discountable');
        }
    
        public function getProductsListAttribute()
        {
            return $this->products->pluck('id')->toArray();
        }
    
        public function getCategoriesListAttribute()
        {
            return $this->categories->pluck('id')->toArray();
        }
    
        public function getDiscountTypeNameAttribute(): string
        {
            return __(data_get(self::DISCOUNT_TYPES, $this->type, ''));
        }
    
    }

And I have blade file:

My discount types is: {{ dd($discount) }}

I need show my array from model (DISCOUNT_TYPES).

In result my code I have this:

    App\Models\Discount {#1504 ▼
      #guarded: array:1 [▼
        0 => "id"
      ]
      #fillable: array:4 [▼
        0 => "name"
        1 => "value"
        2 => "type"
        3 => "deactivated_at"
      ]
      #dates: array:3 [▼
        0 => "created_at"
        1 => "updated_at"
        2 => "deleted_at"
      ]
      #connection: null
      #table: null
      #primaryKey: "id"
      #keyType: "int"
      +incrementing: true
      #with: []
      #withCount: []
      #perPage: 15
      +exists: false
      +wasRecentlyCreated: false
      #attributes: []
      #original: []
      #changes: []
      #casts: array:1 [▼
        "deleted_at" => "datetime"
      ]
      #classCastCache: []
      #dateFormat: null
      #appends: []
      #dispatchesEvents: []
      #observables: []
      #relations: array:2 [▼
        "categories" => Illuminate\Database\Eloquent\Collection {#1528 ▶}
        "products" => Illuminate\Database\Eloquent\Collection {#1532 ▶}
      ]
      #touches: []
      +timestamps: true
      #hidden: []
      #visible: []
      #forceDeleting: false
    }

I try make this: data_get($discount, 'products_list', [$discount->getDiscountTypeName]),

but it's not working :(

How can I make it?

Jan
08
4 months ago
Activity icon

Replied to Replace String By Values From Collection In Laravel

Yes.

From my value string: {osoba_odpowiedzialna} i want replaye by $collection-> osoba_odpowiedzialna

Activity icon

Started a new Conversation Replace String By Values From Collection In Laravel

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

        $value = "Szanowni Państwo,
        Status został zmieniony.
        <br/><br/>
        
        Osoba odp.: {osoba_odpowiedzialna}<br/>";
        
    $collection = collect(
                (object) [
                    'osoba_odpowiedzialna' => $responsiblePerson,
                    'rodzaj' => data_get($term, 'termType.name'),
                    'klient' => data_get($term, 'client.name'),
                    'sprawa' => data_get($term, 'caseInstance.internal_signature'),
                    'status' => data_get($term, 'termStatus.name'),
                    'adres' => route('calendar.index')
                ]
            );

in result $collection I have:

https://ibb.co/Kz18CJ1

I need replace my $value - values from $collection by key: osoba_odpowiedzialna, klient, rodzaj etc.

How can I make it?

Dec
18
4 months ago
Activity icon

Replied to Create Collection With Selected Data

This unfortunately doesn't work when I have a couple of the same names :(

Activity icon

Started a new Conversation Create Collection With Selected Data

Hi, I have this code:

$terms = $this->model
            ->where('course_terms.is_active', true)
            ->where(function ($query) use ($dateFrom, $dateTo) {
                if ($dateFrom != "" && $dateTo == "") {
                    $query->whereDate('starting_at', '>=', $dateFrom);
                } elseif ($dateFrom == "" && $dateTo != "") {
                    $query->whereDate('starting_at', '<=', $dateTo);
                } else {
                    $query->whereBetween('starting_at', [$dateFrom, $dateTo]);
                }
            })
            ->select(['courses.short_name AS short_name', 'course_terms.*'])
            ->leftJoin('courses', 'courses.id', '=', 'course_terms.course_id')
            ->orderBy('starting_at', 'asc')
            ->get();
        
        $termsArray = [];
        foreach ($terms as $term)
        {
            dump($term);
        }

It's return me:

 Illuminate\Database\Eloquent\Collection {#1814 ▼
  #items: array:3 [▼
    0 => App\Models\CourseTerm {#1815 ▼
      #fillable: array:8 [▶]
      #dates: array:5 [▶]
      #casts: array:6 [▶]
      #appends: array:1 [▶]
      #connection: "mysql"
      #table: "course_terms"
      #primaryKey: "id"
      #keyType: "int"
      +incrementing: true
      #with: []
      #withCount: []
      #perPage: 15
      +exists: true
      +wasRecentlyCreated: false
      #attributes: array:16 [▼
        "short_name" => "nazwa 1"
        "id" => 2
        "starting_at" => "2020-12-22"
        "days" => 123
        "course_id" => 1
        "max_participants" => 12312
        "additional_notes" => "Fajny kurs 1213"
        "is_active" => 1
        "is_confirmed" => 1
        "created_at" => "2020-12-14 12:24:37"
        "updated_at" => "2020-12-14 12:39:22"
        "deleted_at" => null
        "created_by" => 1
        "updated_by" => 1
        "deleted_by" => null
        "diary_generated_at" => "2020-12-14 13:40:40"
      ]
      #original: array:16 [▶]
      #changes: []
      #classCastCache: []
      #dateFormat: null
      #dispatchesEvents: []
      #observables: []
      #relations: []
      #touches: []
      +timestamps: true
      #hidden: []
      #visible: []
      #guarded: array:1 [▶]
      #forceDeleting: false
    }
    1 => App\Models\CourseTerm {#1816 ▼
      #fillable: array:8 [▶]
      #dates: array:5 [▶]
      #casts: array:6 [▶]
      #appends: array:1 [▶]
      #connection: "mysql"
      #table: "course_terms"
      #primaryKey: "id"
      #keyType: "int"
      +incrementing: true
      #with: []
      #withCount: []
      #perPage: 15
      +exists: true
      +wasRecentlyCreated: false
      #attributes: array:16 [▼
        "short_name" => "nazwa 1"
        "id" => 1
        "starting_at" => "2020-12-25"
        "days" => 12
        "course_id" => 1
        "max_participants" => 12
        "additional_notes" => "Fajny kurs"
        "is_active" => 1
        "is_confirmed" => 1
        "created_at" => "2020-12-14 11:34:30"
        "updated_at" => "2020-12-14 12:39:26"
        "deleted_at" => null
        "created_by" => 1
        "updated_by" => 1
        "deleted_by" => null
        "diary_generated_at" => "2020-12-14 12:39:26"
      ]
      #original: array:16 [▶]
      #changes: []
      #classCastCache: []
      #dateFormat: null
      #dispatchesEvents: []
      #observables: []
      #relations: []
      #touches: []
      +timestamps: true
      #hidden: []
      #visible: []
      #guarded: array:1 [▶]
      #forceDeleting: false
    }
    2 => App\Models\CourseTerm {#1817 ▼
      #fillable: array:8 [▶]
      #dates: array:5 [▶]
      #casts: array:6 [▶]
      #appends: array:1 [▶]
      #connection: "mysql"
      #table: "course_terms"
      #primaryKey: "id"
      #keyType: "int"
      +incrementing: true
      #with: []
      #withCount: []
      #perPage: 15
      +exists: true
      +wasRecentlyCreated: false
      #attributes: array:16 [▼
        "short_name" => "nazwa 2"
        "id" => 3
        "starting_at" => "2020-12-27"
        "days" => 12
        "course_id" => 2
        "max_participants" => 12
        "additional_notes" => "kurs na 100"
        "is_active" => 1
        "is_confirmed" => 1
        "created_at" => "2020-12-14 15:31:44"
        "updated_at" => null
        "deleted_at" => null
        "created_by" => 1
        "updated_by" => 1
        "deleted_by" => null
        "diary_generated_at" => "2020-12-14 14:32:01"
      ]
      #original: array:16 [▶]
      #changes: []
      #classCastCache: []
      #dateFormat: null
      #dispatchesEvents: []
      #observables: []
      #relations: []
      #touches: []
      +timestamps: true
      #hidden: []
      #visible: []
      #guarded: array:1 [▶]
      #forceDeleting: false
    }
  ]
}

It's work fine.

I need show in my blade something like this (by course_id):

  • nazwa 1 (short_name) has terms: 2020-12-22 , 2020-12-25 (starting_at)

  • nazwa 2 (short_name) has terms: 2020-12-27 (starting_at)

How can I make it?

I need collection with this form: 'name'=> nazwa 1, [2020-12-22 , 2020-12-25]. How can I make this?

Dec
15
5 months ago
Activity icon

Started a new Conversation Updating Large Amounts Of Data In Laravel

Hi, I have problem with updating my database. I have iMac i5 16GB Ram with SSD + MAMP PRO.

I have this model:

use Illuminate\Database\Eloquent\SoftDeletes;
use Kalnoy\Nestedset\NodeTrait;
use Spatie\Sluggable\HasSlug;
use Spatie\Sluggable\SlugOptions;

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

    protected $guarded = ['id'];

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

    public $timestamps = false;

    protected $dates = [
        'deleted_at'
    ];

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

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

}

Migration:

class CreateFailedJobsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('failed_jobs', function (Blueprint $table) {
            $table->id();
            $table->string('uuid')->unique();
            $table->text('connection');
            $table->text('queue');
            $table->longText('payload');
            $table->longText('exception');
            $table->timestamp('failed_at')->useCurrent();
        });
    }

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

And controller:

public function index(Category $category)
    {
        echo 'START';
        $categories = $category->where('value', null)->orWhere('value', '')->orderBy('id', 'ASC')->get();
        foreach ($categories as $item) {
            $path = null;
            $tmpProduct = $item->ancestorsAndSelf($item->id);
            foreach ($tmpProduct as $pathItem) {
                $path .= $pathItem->category_name . ' - ';
            }
            $path = substr($path, 0, -3);
            $item->update(['value' => $path]);
        }

        echo 'finish';
    }

It's work fine, but very slow. I use this package in my model: https://packagist.org/packages/kalnoy/nestedset

How can I optimize this update? My database has 170,000 records.

Please help me

Dec
14
5 months ago
Activity icon

Replied to Search And Sort By Relation

select * from `courses` where `is_active` = 1 and exists (select * from `course_terms` where `courses`.`id` = `course_terms`.`course_id` and `starting_at` between '2020-12-25' and '2020-12-31' and `course_terms`.`deleted_at` is null order by `starting_at` asc) and `courses`.`deleted_at` is null

select * from courses where is_active = ? and exists (select * from course_terms where courses.id = course_terms.course_id and starting_at between ? and ? and course_terms.deleted_at is null order by starting_at asc) and courses.deleted_at is null

Activity icon

Started a new Conversation Search And Sort By Relation

Hi, I have project in Laravel 5.8.

I have this function:

public function getCourserFromDates(string $dateFrom, string $dateTo)
    {
        return $this->model->getCourserFromDates( $dateFrom,  $dateTo)->get();
    }

And my models:

class Course extends Model implements Sitemapable
{
    use HasSitemap,
        Seoable,
        SoftDeletes;

    protected $fillable = [
        'course_category_id',
        'basic_course_id',
        'default_currency_id',
        'short_name',
        'color',
        'price',
        'has_negotiable_price',
        'deposit',
        'certificate_title',
        'certificate_description',
        'certificate_number',
        'is_active',
        'created_by',
        'updated_by',
        'deleted_by'
    ];

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

    protected $casts = [
        'course_category_id' => 'integer',
        'basic_course_id' => 'integer',
        'default_currency_id' => 'integer',
        'is_active' => 'boolean',
        'price' => 'float',
        'deposit' => 'float',
        'created_by' => 'integer',
        'updated_by' => 'integer',
        'deleted_by' => 'integer'
    ];

    protected $appends = [
        'name'
    ];

    protected $with = [
        'courseDescriptions'
    ];

    public function courseCategory()
    {
        return $this->belongsTo(CourseCategory::class);
    }

    public function basicCourse()
    {
        return $this->belongsTo(self::class);
    }

    public function defaultCurrency()
    {
        return $this->belongsTo(Currency::class);
    }

    public function courseTerms()
    {
        return $this->hasMany(CourseTerm::class);
    }

    public function closestCourseTerms()
    {
        return $this
            ->courseTerms()
            ->where('is_active', true)
            ->whereDate('starting_at', '>', today()->format('Y-m-d'))
            ->whereDate('starting_at', '<=', today()->addDays(config('courses.closest_terms_within_days', 0)))
            ->orderBy('starting_at');
    }

    public function getCourserFromDates(string $dateFrom, string $dateTo)
    {
        return $this
            ->with('courseTerms')
            ->where('is_active', true)
            ->whereHas('courseTerms', function ($query) use ($dateFrom, $dateTo){
                $query->whereBetween('starting_at', [$dateFrom, $dateTo]);
                $query->orderBy('starting_at');
            });
    }

    public function closestConfirmedCourseTerms()
    {
        return $this->closestCourseTerms
            ->where('is_confirmed', true)->all();
    }

    public function closestNotConfirmedCourseTerms()
    {
        return $this->closestCourseTerms
            ->where('is_confirmed', false)->all();
    }

    public function closestCourseTerm()
    {
        return $this
            ->hasOne(CourseTerm::class)
            ->withCount('courseParticipants')
            // ->select(['id','course_id','starting_at','is_confirmed','days'])
            ->where('is_active', true)
            ->whereDate('starting_at', '>', today()->format('Y-m-d'))
            ->orderBy('starting_at');
    }

    public function courseParticipants()
    {
        return $this->hasManyThrough('App\Models\CourseParticipant','App\Models\CourseTerm');
    }

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

    public static function allForSitemap(): Collection
    {
        return self::where('is_active', true)
            ->select(['id','is_active', 'created_at', 'updated_at'])
            ->get();
    }

    public function hasTranslation($locale = null)
    {
        $courseDescriptions = $this->courseDescriptions ?? $this->courseDescriptions();

        return $courseDescriptions
            ->where('locale', $locale ?: \App::getLocale() )
            ->count() === 1;
    }

    public function translatedDescriptions($locale = null)
    {
        $courseDescriptions = $this->courseDescriptions ?? $this->courseDescriptions();

        if( $this->hasTranslation($locale) )
        {
            return $courseDescriptions->where('locale', $locale ?: \App::getLocale() )->first();
        }
        /*
         * Playin' dirty
         */
        if( $this->hasTranslation('pl') )
        {
            return $courseDescriptions->where('locale', 'pl' )->first();
        }

        throw new \Exception('Requested language not found');
    }

    public function getNameAttribute() {
        $description = $this->courseDescriptions->where('locale', \App::getLocale())->first();

        return $description instanceof CourseDescription
            ? $description->name
            : $this->short_name;
    }

    public function getShortDescriptionAttribute() {
        return data_get($this->courseDescriptions->where('locale', \App::getLocale())->first(), 'short_description', "");
    }

    public function getDescriptionAttribute() {
        return data_get($this->courseDescriptions->where('locale', \App::getLocale())->first(), 'description', "");
    }

    public function getSlugAttribute() {
        return data_get($this->courseDescriptions->where('locale', \App::getLocale())->first(), 'slug', "");
    }

    public function getIsRenewalAttribute() : bool {
        return $this->basicCourse instanceof self;
    }

    public function courseTags()
    {
        return $this->hasMany(CourseTag::class);
    }

    public function tags()
    {
        return $this->belongsToMany(Tag::class)->using(CourseTag::class);
    }

    public function getUrlAttribute() {
        return ! empty($slug = $this->slug)
            ? route('front.course.show', ['slug' => $slug])
            : route('front.course.find', ['id' => $this->id]);
    }

    /**
     * @param Builder $query
     * @return Builder
     */
    public function scopeWhereActiveWithTerms(Builder $query) : Builder
    {
        return $query
            ->where('is_active', true)
            ->whereExists(function ($query) {
                $query->select(DB::raw(1))
                    ->from('course_terms')
                    ->whereRaw("course_id = courses.id and is_active = 1 and starting_at > '" . today()->format('Y-m-d') . "'");
        });
    }

    public function getCourseCategoryUrlAttribute() {
        if(empty($this->courseCategory)) {
            return null;
        }

        if(is_null($this->courseCategory->parent_category_id)) {
            return $this->courseCategory->url;
        }

        return $this->courseCategory->parentCategory->url;
    }

    public function getLocalizedUrlsAttribute() {
        $urls = [];

        foreach(LaravelLocalization::getSupportedLocales() as $locale => $properties) {
            if(! is_null($slug = $this->getSlug($locale))) {
                $urls[$locale] = array_merge($properties, [
                    'url' => LaravelLocalization::getURLFromRouteNameTranslated($locale,  'routes.front.course.show', ['slug' => $slug])
                ]);
            }
        }

        return $urls;
    }

    public function getSlug($locale): string {
        return data_get($this->courseDescriptions->where('locale', $locale)->first(), 'slug', "");
    }

    public function getGtagViewItemDataAttribute(): array
    {
        $viewItemData = [
            'id' => $this->id,
            'name' => $this->name,
            'category' => data_get($this->courseCategory, 'name', '')
        ];

        if(! $this->has_negotiable_price)
        {
            $viewItemData['price'] = $this->price;
        }

        return $viewItemData;
    }
}



class CourseTerm extends Model
{
    use SoftDeletes;

    protected $fillable = [
        'starting_at',
        'days',
        'course_id',
        'max_participants',
        'additional_notes',
        'is_active',
        'is_confirmed',
        'diary_generated_at'
    ];

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

    protected $casts = [
        'course_id' => 'integer',
        'days' => 'integer',
        'max_participants' => 'integer',
        'is_active' => 'boolean',
        'is_confirmed' => 'boolean',
        'starting_at' => 'date:Y-m-d'
    ];

    protected $appends = [
        'date'
    ];

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

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

    public function freeReservations() : int
    {
        return (int) array_key_exists('course_participants_count', $this->attributes)
            ? $this->max_participants - $this->course_participants_count
            : $this->max_participants - $this->courseParticipants()->count();
    }

    public function getHasFreeReservationsAttribute() : bool {
        return $this->freeReservations() > 0;
    }

    public function getReservationsProgressInPercentAttribute() : int {
        if($this->max_participants == 0) {
            return 0;
        }

        return (int) round(($this->max_participants - $this->freeReservations())/ $this->max_participants * 100);
    }

    public function getUnifiedDaysAttribute() : int {
        return max($this->days - 1, 0);
    }

    public function getEndingAtAttribute() : Carbon {
        return Carbon::parse($this->starting_at)->addDays($this->unified_days);
    }

    public function getDateAttribute($value) : string
    {
        if($this->unified_days == 0) {
            return $this->starting_at->format("d-m-Y");
        }

        $endingAt = $this->ending_at;

        if($this->starting_at->isSameMonth($endingAt)) {
            return $this->starting_at->format('d') . '-' . $endingAt->format('d.m.Y');
        } else if($this->starting_at->isSameYear($endingAt)) {
            return $this->starting_at->format('d.m') . '-' . $endingAt->format('d.m.Y');
        } else {
            return $this->starting_at->format('d.m.Y') . '-' . $endingAt->format('d.m.Y');
        }
    }

    public function getStartingAtForHumansAttribute() : string {
        return Date::parse($this->starting_at)->format('j F Y');
    }

    public function getEndingAtForHumansAttribute() : string {
        return Date::parse($this->starting_at)
            ->addDays($this->unified_days)
            ->format('j F Y');
    }

    public function getDaysToAttribute() : int {
        return Carbon::parse($this->starting_at)->diffInDays(today());
    }

    public function getSignUrlAttribute() : string {
        if(! $this->has_free_reservations) {
            return "#";
        }

        return route('front.order.sign', ['courseTermId' => $this->id]);
    }

    public function hasActiveCourse() : bool {
        return $this->course instanceof Course && $this->course->is_active;
    }

    public function canSignByDate(): bool {
        return $this->starting_at > today()->format('Y-m-d');
    }
}

I have problem with this part of my code:

public function getCourserFromDates(string $dateFrom, string $dateTo) { return $this ->with('courseTerms') ->where('is_active', true) ->whereHas('courseTerms', function ($query) use ($dateFrom, $dateTo){ $query->whereBetween('starting_at', [$dateFrom, $dateTo]); $query->orderBy('starting_at'); }); }

Here's what I need:

  1. Courses with dates within the given range
  2. Sort the results (course_terms) by startet_at ASC

Currently, I have records in the database for 2020-12-22 - 2020-12-27. When my data_from is 2020-12-25, I can still see the cource_terms for 2020-12-22.

How can this be fixed?

Nov
19
5 months ago
Activity icon

Replied to Search Results In Laravel

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

Nov
18
5 months ago
Activity icon

Replied to Search Results In Laravel

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

Activity icon

Replied to Search Results In Laravel

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

Activity icon

Replied to Search Results In Laravel

No, I haven't result :(

Activity icon

Replied to Search Results In Laravel

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

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

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

Activity icon

Replied to Search Results In Laravel

this is not working :(

Activity icon

Replied to Search Results In Laravel

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

Activity icon

Replied to Search Results In Laravel

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

Activity icon

Started a new Conversation Search Results In Laravel

Hi, I have small problem.

I have this code:

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

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


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

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

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

How can I repair my code?

Please help me