nacha

nacha

Member Since 7 Months Ago

Experience Points
2,780
Total
Experience

2,220 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
6
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
2,780 XP
Sep
27
22 hours ago
Activity icon

Replied to Laravel Query Builder

thank you @thewebartisan7 I used exact for brand like this


                AllowedFilter::exact('brand', 'brand_id'),

and for category code in productcontroller

AllowedFilter::custom('category', new FiltersCategories),

productController:

 $products = QueryBuilder::for(Product::class)
          
            ->allowedFilters([
                AllowedFilter::exact('brand', 'brand_id'),
                AllowedFilter::custom('category', new FiltersCategories),
                
                ])
            ->get();
        return view('site.pages.products', compact('products'));

and code in FiltersCategories.php

<?php

namespace App\Filters;

use Spatie\QueryBuilder\Filters\Filter;
use Illuminate\Database\Eloquent\Builder;

class FiltersCategories implements Filter
{
    public function __invoke(Builder $query, $value, string $property) : Builder
    {
        return $query->whereHas('categories', function ($query) use ($value) {
            if (is_array($value)) {
                return $query->whereIn('category_id', $value);
            }

            return $query->where('category_id', $value);
        });
    }
}

products.blade.php

       <p>Brands</p>
                <form method="get" action="{{ route('products.index') }}"> 
@foreach ($brands as $brand)
    <label class="m-checkbox">
        <input
            name="filter[brand]" type="checkbox" value="{{ $brand->id }}"
            @if (in_array($brand->id, explode(',', request()->input('filter.brand'))))
                checked
            @endif
        >
        {{ $brand->name }}
    </label>
@endforeach

<button type="submit">apply filter</button>
</form>
<p>Categories</p>
<form method="get" action="{{ route('products.index') }}"> 
@foreach ($categories as $category)
@if ($category->id!=1)
    <label>
        <input
            name="filter[category]" type="checkbox" value="{{ $category->id }}"
            @if (in_array($category->id, explode(',', request()->input('filter.category'))))
                checked
            @endif
        >
        {{ $category->name }}
    </label>
    @endif
@endforeach

<button type="submit">apply filter</button>

so when I did this It works for brand and category and get products belong to them but It show me just products belong to one Brand and one category if I check in by brand adidas and gucci it show me just products belong to adidas and the same for by category this is image: https://i.imgur.com/5Zm5TN9.png but when I type this

localhost/site/public/products?filter[brand]=1,6

this is image: https://i.imgur.com/xtCx1Hr.png it show me products belong to id=1(gucci) and id=6(adidas) thats mean it works with this url and it works for by category also

so how to fix my problem and get products like when I type this "localhost/site/public/products?filter[brand]=1,6" and when I add this

name="filter[brand][]"

it gives me error:

ErrorException (E_ERROR)
explode() expects parameter 2 to be string, array given (View: C:\wamp\www\site\resources\views\site\pages\products.blade.php)

thank you

Activity icon

Replied to ErrorException (E_ERROR) Undefined Variable: AttributeValues (View: C:\wamp\www\site\resources\views\site\pages\products.blade.php) And BadMethodCallException

when I write code in productcontroller and products.blade.php using spatie laravel query builder with allowefilters (exact and custom) It works for brand and category and get products belong to them but It show me just products belong to one Brand and one category if I check in by brand adidas and gucci it show me just products belong to adidas and the same for by category this is image: https://i.imgur.com/5Zm5TN9.png but when I type this

localhost/site/public/products?filter[brand]=1,6

and this is image: https://i.imgur.com/xtCx1Hr.png so how to fix my problem and get products like when I type this "localhost/site/public/products?filter[brand]=1,6" and I tried to do the same for by size and by color but it gives me the error

Sep
25
2 days ago
Activity icon

Replied to ErrorException (E_ERROR) Undefined Variable: AttributeValues (View: C:\wamp\www\site\resources\views\site\pages\products.blade.php) And BadMethodCallException

thank you @automica I used spatie laravel query builder and I used exact for brand like this


                AllowedFilter::exact('brand', 'brand_id'),

and for category code in productcontroller

AllowedFilter::custom('category', new FiltersCategories),

and code in FiltersCategories.php

<?php

namespace App\Filters;

use Spatie\QueryBuilder\Filters\Filter;
use Illuminate\Database\Eloquent\Builder;

class FiltersCategories implements Filter
{
    public function __invoke(Builder $query, $value, string $property) : Builder
    {
        return $query->whereHas('categories', function ($query) use ($value) {
            if (is_array($value)) {
                return $query->whereIn('category_id', $value);
            }

            return $query->where('category_id', $value);
        });
    }
}

so when I did this It works for brand and category and get products belong to them but It show me just products belong to one Brand and one category if I check in by category adidas and gucci it show me just products belong to adidas and the same for by brand but when I type this

localhost/site/public/products?filter[brand]=1,6

it show me products belong to id=1(gucci) and id=6(adidas) thats mean it works with this url and it works for by category also so I tried to do the same for by size and by color but it gives me the error

so how to fix my problem and get products like when I type this "localhost/site/public/products?filter[brand]=1,6"

when I write code in products.blade.php It gives me all size values and color values with checkbox and when I check a value to filter product with size forexemple size :s with checkbox it return this error:

BadMethodCallException
Call to undefined method App\Models\Product::attribute_values()

thank you

Activity icon

Replied to ErrorException (E_ERROR) Undefined Variable: AttributeValues (View: C:\wamp\www\site\resources\views\site\pages\products.blade.php) And BadMethodCallException

thank you very much @automica and if I change wherehas with AttributeValues it's show me the same error

logs:

[2020-09-25 18:46:06] local.ERROR: Undefined variable: attributeValues (View: C:\wamp\www\site\resources\views\site\pages\products.blade.php) {"exception":"[object] (ErrorException(code: 0): Undefined variable: attributeValues (View: C:\wamp\www\site\
esources\views\site\pages\products.blade.php) at C:\wamp\www\site\storage\framework\views\d38dffd63add89bc36a468f6e98ac7b77d3d250a.php:86, ErrorException(code: 0): Undefined variable: attributeValues at C:\wamp\www\site\storage\framework\views\d38dffd63add89bc36a468f6e98ac7b77d3d250a.php:86)
[stacktrace]
#0 C:\wamp\www\site\vendor\laravel\framework\src\Illuminate\View\Engines\PhpEngine.php(45): Illuminate\View\Engines\CompilerEngine->handleViewException(Object(ErrorException), 1)
#1 C:\wamp\www\site\vendor\laravel\framework\src\Illuminate\View\Engines\CompilerEngine.php(59): Illuminate\View\Engines\PhpEngine->evaluatePath('C:\\wamp\\www\\sit...', Array)
#2 C:\wamp\www\site\vendor\laravel\framework\src\Illuminate\View\View.php(142): Illuminate\View\Engines\CompilerEngine->get('C:\\wamp\\www\\sit...', Array)
#3 C:\wamp\www\site\vendor\laravel\framework\src\Illuminate\View\View.php(125): Illuminate\View\View->getContents()
#4 C:\wamp\www\site\vendor\laravel\framework\src\Illuminate\View\View.php(90): Illuminate\View\View->renderContents()
#5 C:\wamp\www\site\vendor\laravel\framework\src\Illuminate\Http\Response.php(42): Illuminate\View\View->render()
#6 C:\wamp\www\site\vendor\symfony\http-foundation\Response.php(205): Illuminate\Http\Response->setContent(Object(Illuminate\View\View))
#7 C:\wamp\www\site\vendor\laravel\framework\src\Illuminate\Routing\Router.php(748): Symfony\Component\HttpFoundation\Response->__construct(Object(Illuminate\View\View))
#8 C:\wamp\www\site\vendor\laravel\framework\src\Illuminate\Routing\Router.php(720): Illuminate\Routing\Router::toResponse(Object(Illuminate\Http\Request), Object(Illuminate\View\View))
#9 C:\wamp\www\site\vendor\laravel\framework\src\Illuminate\Routing\Router.php(680): Illuminate\Routing\Router->prepareResponse(Object(Illuminate\Http\Request), Object(Illuminate\View\View))
#10 C:\wamp\www\site\vendor\laravel\framework\src\Illuminate\Routing\Pipeline.php(30): Illuminate\Routing\Router->Illuminate\Routing\{closure}(Object(Illuminate\Http\Request))
#11 C:\wamp\www\site\vendor\laravel\framework\src\Illuminate\Routing\Middleware\SubstituteBindings.php(41): Illuminate\Routing\Pipeline->Illuminate\Routing\{closure}(Object(Illuminate\Http\Request))
#12 C:\wamp\www\site\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php(163): Illuminate\Routing\Middleware\SubstituteBindings->handle(Object(Illuminate\Http\Request), Object(Closure))
#13 C:\wamp\www\site\vendor\laravel\framework\src\Illuminate\Routing\Pipeline.php(53): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))
#14 C:\wamp\www\site\vendor\laravel\framework\src\Illuminate\Foundation\Http\Middleware\VerifyCsrfToken.php(75): Illuminate\Routing\Pipeline->Illuminate\Routing\{closure}(Object(Illuminate\Http\Request))
#15 C:\wamp\www\site\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php(163): Illuminate\Foundation\Http\Middleware\VerifyCsrfToken->handle(Object(Illuminate\Http\Request), Object(Closure))
#16 C:\wamp\www\site\vendor\laravel\framework\src\Illuminate\Routing\Pipeline.php(53): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))
#17 C:\wamp\www\site\vendor\laravel\framework\src\Illuminate\View\Middleware\ShareErrorsFromSession.php(49): Illuminate\Routing\Pipeline->Illuminate\Routing\{closure}(Object(Illuminate\Http\Request))
#18 C:\wamp\www\site\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php(163): Illuminate\View\Middleware\ShareErrorsFromSession->handle(Object(Illuminate\Http\Request), Object(Closure))
#19 C:\wamp\www\site\vendor\laravel\framework\src\Illuminate\Routing\Pipeline.php(53): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))
#20 C:\wamp\www\site\vendor\laravel\framework\src\Illuminate\Session\Middleware\StartSession.php(56): Illuminate\Routing\Pipeline->Illuminate\Routing\{closure}(Object(Illuminate\Http\Request))
#21 C:\wamp\www\site\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php(163): Illuminate\Session\Middleware\StartSession->handle(Object(Illuminate\Http\Request), Object(Closure))
#22 C:\wamp\www\site\vendor\laravel\framework\src\Illuminate\Routing\Pipeline.php(53): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))
#23 C:\wamp\www\site\vendor\laravel\framework\src\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse.php(37): Illuminate\Routing\Pipeline->Illuminate\Routing\{closure}(Object(Illuminate\Http\Request))
#24 C:\wamp\www\site\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php(163): Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse->handle(Object(Illuminate\Http\Request), Object(Closure))
#25 C:\wamp\www\site\vendor\laravel\framework\src\Illuminate\Routing\Pipeline.php(53): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))
#26 C:\wamp\www\site\vendor\laravel\framework\src\Illuminate\Cookie\Middleware\EncryptCookies.php(66): Illuminate\Routing\Pipeline->Illuminate\Routing\{closure}(Object(Illuminate\Http\Request))
#27 C:\wamp\www\site\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php(163): Illuminate\Cookie\Middleware\EncryptCookies->handle(Object(Illuminate\Http\Request), Object(Closure))
#28 C:\wamp\www\site\vendor\laravel\framework\src\Illuminate\Routing\Pipeline.php(53): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))
#29 C:\wamp\www\site\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php(104): Illuminate\Routing\Pipeline->Illuminate\Routing\{closure}(Object(Illuminate\Http\Request))
#30 C:\wamp\www\site\vendor\laravel\framework\src\Illuminate\Routing\Router.php(682): Illuminate\Pipeline\Pipeline->then(Object(Closure))
#31 C:\wamp\www\site\vendor\laravel\framework\src\Illuminate\Routing\Router.php(657): Illuminate\Routing\Router->runRouteWithinStack(Object(Illuminate\Routing\Route), Object(Illuminate\Http\Request))
#32 C:\wamp\www\site\vendor\laravel\framework\src\Illuminate\Routing\Router.php(623): Illuminate\Routing\Router->runRoute(Object(Illuminate\Http\Request), Object(Illuminate\Routing\Route))
#33 C:\wamp\www\site\vendor\laravel\framework\src\Illuminate\Routing\Router.php(612): Illuminate\Routing\Router->dispatchToRoute(Object(Illuminate\Http\Request))
#34 C:\wamp\www\site\vendor\laravel\framework\src\Illuminate\Foundation\Http\Kernel.php(176): Illuminate\Routing\Router->dispatch(Object(Illuminate\Http\Request))
#35 C:\wamp\www\site\vendor\laravel\framework\src\Illuminate\Routing\Pipeline.php(30): Illuminate\Foundation\Http\Kernel->Illuminate\Foundation\Http\{closure}(Object(Illuminate\Http\Request))
#36 C:\wamp\www\site\vendor\laravel\framework\src\Illuminate\Foundation\Http\Middleware\TransformsRequest.php(21): Illuminate\Routing\Pipeline->Illuminate\Routing\{closure}(Object(Illuminate\Http\Request))
#37 C:\wamp\www\site\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php(163): Illuminate\Foundation\Http\Middleware\TransformsRequest->handle(Object(Illuminate\Http\Request), Object(Closure))
#38 C:\wamp\www\site\vendor\laravel\framework\src\Illuminate\Routing\Pipeline.php(53): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))
#39 C:\wamp\www\site\vendor\laravel\framework\src\Illuminate\Foundation\Http\Middleware\TransformsRequest.php(21): Illuminate\Routing\Pipeline->Illuminate\Routing\{closure}(Object(Illuminate\Http\Request))
#40 C:\wamp\www\site\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php(163): Illuminate\Foundation\Http\Middleware\TransformsRequest->handle(Object(Illuminate\Http\Request), Object(Closure))
#41 C:\wamp\www\site\vendor\laravel\framework\src\Illuminate\Routing\Pipeline.php(53): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))
#42 C:\wamp\www\site\vendor\laravel\framework\src\Illuminate\Foundation\Http\Middleware\ValidatePostSize.php(27): Illuminate\Routing\Pipeline->Illuminate\Routing\{closure}(Object(Illuminate\Http\Request))
#43 C:\wamp\www\site\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php(163): Illuminate\Foundation\Http\Middleware\ValidatePostSize->handle(Object(Illuminate\Http\Request), Object(Closure))
#44 C:\wamp\www\site\vendor\laravel\framework\src\Illuminate\Routing\Pipeline.php(53): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))
#45 C:\wamp\www\site\vendor\laravel\framework\src\Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode.php(62): Illuminate\Routing\Pipeline->Illuminate\Routing\{closure}(Object(Illuminate\Http\Request))
#46 C:\wamp\www\site\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php(163): Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode->handle(Object(Illuminate\Http\Request), Object(Closure))
#47 C:\wamp\www\site\vendor\laravel\framework\src\Illuminate\Routing\Pipeline.php(53): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))
#48 C:\wamp\www\site\vendor\fideloper\proxy\src\TrustProxies.php(57): Illuminate\Routing\Pipeline->Illuminate\Routing\{closure}(Object(Illuminate\Http\Request))
#49 C:\wamp\www\site\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php(163): Fideloper\Proxy\TrustProxies->handle(Object(Illuminate\Http\Request), Object(Closure))
#50 C:\wamp\www\site\vendor\laravel\framework\src\Illuminate\Routing\Pipeline.php(53): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))
#51 C:\wamp\www\site\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php(104): Illuminate\Routing\Pipeline->Illuminate\Routing\{closure}(Object(Illuminate\Http\Request))
#52 C:\wamp\www\site\vendor\laravel\framework\src\Illuminate\Foundation\Http\Kernel.php(151): Illuminate\Pipeline\Pipeline->then(Object(Closure))
#53 C:\wamp\www\site\vendor\laravel\framework\src\Illuminate\Foundation\Http\Kernel.php(116): Illuminate\Foundation\Http\Kernel->sendRequestThroughRouter(Object(Illuminate\Http\Request))
#54 C:\wamp\www\site\public\index.php(55): Illuminate\Foundation\Http\Kernel->handle(Object(Illuminate\Http\Request))
#55 {main}
"} 
[2020-09-25 18:47:55] local.ERROR: Call to undefined method App\Models\Product::attribute_values() {"exception":"[object] (BadMethodCallException(code: 0): Call to undefined method App\Models\Product::attribute_values() at C:\wamp\www\site\vendor\laravel\framework\src\Illuminate\Support\Traits\ForwardsCalls.php:50)
[stacktrace]
#0 C:\wamp\www\site\vendor\laravel\framework\src\Illuminate\Support\Traits\ForwardsCalls.php(36): Illuminate\Database\Eloquent\Model::throwBadMethodCallException('attribute_value...')
#1 C:\wamp\www\site\vendor\laravel\framework\src\Illuminate\Database\Eloquent\Model.php(1618): Illuminate\Database\Eloquent\Model->forwardCallTo(Object(Illuminate\Database\Eloquent\Builder), 'attribute_value...', Array)
#2 C:\wamp\www\site\vendor\laravel\framework\src\Illuminate\Database\Eloquent\Concerns\QueriesRelationships.php(475): Illuminate\Database\Eloquent\Model->__call('attribute_value...', Array)
#3 [internal function]: Illuminate\Database\Eloquent\Builder->Illuminate\Database\Eloquent\Concerns\{closure}()
#4 C:\wamp\www\site\vendor\laravel\framework\src\Illuminate\Database\Eloquent\Relations\Relation.php(90): call_user_func(Object(Closure))
#5 C:\wamp\www\site\vendor\laravel\framework\src\Illuminate\Database\Eloquent\Concerns\QueriesRelationships.php(476): Illuminate\Database\Eloquent\Relations\Relation::noConstraints(Object(Closure))
#6 C:\wamp\www\site\vendor\laravel\framework\src\Illuminate\Database\Eloquent\Concerns\QueriesRelationships.php(33): Illuminate\Database\Eloquent\Builder->getRelationWithoutConstraints('attribute_value...')
#7 C:\wamp\www\site\vendor\laravel\framework\src\Illuminate\Database\Eloquent\Concerns\QueriesRelationships.php(146): Illuminate\Database\Eloquent\Builder->has('attribute_value...', '>=', 1, 'and', Object(Closure))
#8 C:\wamp\www\site\app\Filters\FiltersAttributeValues.php(18): Illuminate\Database\Eloquent\Builder->whereHas('attribute_value...', Object(Closure))
#9 C:\wamp\www\site\vendor\spatie\laravel-query-builder\src\AllowedFilter.php(49): App\Filters\FiltersAttributeValues->__invoke(Object(Illuminate\Database\Eloquent\Builder), 's', 'attributeValue')
#10 C:\wamp\www\site\vendor\spatie\laravel-query-builder\src\Concerns\FiltersQuery.php(37): Spatie\QueryBuilder\AllowedFilter->filter(Object(Spatie\QueryBuilder\QueryBuilder), 's')
#11 C:\wamp\www\site\vendor\laravel\framework\src\Illuminate\Support\Collection.php(475): Spatie\QueryBuilder\QueryBuilder->Spatie\QueryBuilder\Concerns\{closure}(Object(Spatie\QueryBuilder\AllowedFilter), 2)
#12 C:\wamp\www\site\vendor\spatie\laravel-query-builder\src\Concerns\FiltersQuery.php(47): Illuminate\Support\Collection->each(Object(Closure))
#13 C:\wamp\www\site\vendor\spatie\laravel-query-builder\src\Concerns\FiltersQuery.php(27): Spatie\QueryBuilder\QueryBuilder->addFiltersToQuery()
#14 C:\wamp\www\site\app\Http\Controllers\Site\ProductController.php(58): Spatie\QueryBuilder\QueryBuilder->allowedFilters(Array)
#15 [internal function]: App\Http\Controllers\Site\ProductController->index(Object(Illuminate\Http\Request))
#16 C:\wamp\www\site\vendor\laravel\framework\src\Illuminate\Routing\Controller.php(54): call_user_func_array(Array, Array)
#17 C:\wamp\www\site\vendor\laravel\framework\src\Illuminate\Routing\ControllerDispatcher.php(45): Illuminate\Routing\Controller->callAction('index', Array)
#18 C:\wamp\www\site\vendor\laravel\framework\src\Illuminate\Routing\Route.php(219): Illuminate\Routing\ControllerDispatcher->dispatch(Object(Illuminate\Routing\Route), Object(App\Http\Controllers\Site\ProductController), 'index')
#19 C:\wamp\www\site\vendor\laravel\framework\src\Illuminate\Routing\Route.php(176): Illuminate\Routing\Route->runController()
#20 C:\wamp\www\site\vendor\laravel\framework\src\Illuminate\Routing\Router.php(680): Illuminate\Routing\Route->run()
#21 C:\wamp\www\site\vendor\laravel\framework\src\Illuminate\Routing\Pipeline.php(30): Illuminate\Routing\Router->Illuminate\Routing\{closure}(Object(Illuminate\Http\Request))
#22 C:\wamp\www\site\vendor\laravel\framework\src\Illuminate\Routing\Middleware\SubstituteBindings.php(41): Illuminate\Routing\Pipeline->Illuminate\Routing\{closure}(Object(Illuminate\Http\Request))
#23 C:\wamp\www\site\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php(163): Illuminate\Routing\Middleware\SubstituteBindings->handle(Object(Illuminate\Http\Request), Object(Closure))
#24 C:\wamp\www\site\vendor\laravel\framework\src\Illuminate\Routing\Pipeline.php(53): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))
#25 C:\wamp\www\site\vendor\laravel\framework\src\Illuminate\Foundation\Http\Middleware\VerifyCsrfToken.php(75): Illuminate\Routing\Pipeline->Illuminate\Routing\{closure}(Object(Illuminate\Http\Request))
#26 C:\wamp\www\site\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php(163): Illuminate\Foundation\Http\Middleware\VerifyCsrfToken->handle(Object(Illuminate\Http\Request), Object(Closure))
#27 C:\wamp\www\site\vendor\laravel\framework\src\Illuminate\Routing\Pipeline.php(53): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))
#28 C:\wamp\www\site\vendor\laravel\framework\src\Illuminate\View\Middleware\ShareErrorsFromSession.php(49): Illuminate\Routing\Pipeline->Illuminate\Routing\{closure}(Object(Illuminate\Http\Request))
#29 C:\wamp\www\site\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php(163): Illuminate\View\Middleware\ShareErrorsFromSession->handle(Object(Illuminate\Http\Request), Object(Closure))
#30 C:\wamp\www\site\vendor\laravel\framework\src\Illuminate\Routing\Pipeline.php(53): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))
#31 C:\wamp\www\site\vendor\laravel\framework\src\Illuminate\Session\Middleware\StartSession.php(56): Illuminate\Routing\Pipeline->Illuminate\Routing\{closure}(Object(Illuminate\Http\Request))
#32 C:\wamp\www\site\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php(163): Illuminate\Session\Middleware\StartSession->handle(Object(Illuminate\Http\Request), Object(Closure))
#33 C:\wamp\www\site\vendor\laravel\framework\src\Illuminate\Routing\Pipeline.php(53): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))
#34 C:\wamp\www\site\vendor\laravel\framework\src\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse.php(37): Illuminate\Routing\Pipeline->Illuminate\Routing\{closure}(Object(Illuminate\Http\Request))
#35 C:\wamp\www\site\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php(163): Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse->handle(Object(Illuminate\Http\Request), Object(Closure))
#36 C:\wamp\www\site\vendor\laravel\framework\src\Illuminate\Routing\Pipeline.php(53): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))
#37 C:\wamp\www\site\vendor\laravel\framework\src\Illuminate\Cookie\Middleware\EncryptCookies.php(66): Illuminate\Routing\Pipeline->Illuminate\Routing\{closure}(Object(Illuminate\Http\Request))
#38 C:\wamp\www\site\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php(163): Illuminate\Cookie\Middleware\EncryptCookies->handle(Object(Illuminate\Http\Request), Object(Closure))
#39 C:\wamp\www\site\vendor\laravel\framework\src\Illuminate\Routing\Pipeline.php(53): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))
#40 C:\wamp\www\site\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php(104): Illuminate\Routing\Pipeline->Illuminate\Routing\{closure}(Object(Illuminate\Http\Request))
#41 C:\wamp\www\site\vendor\laravel\framework\src\Illuminate\Routing\Router.php(682): Illuminate\Pipeline\Pipeline->then(Object(Closure))
#42 C:\wamp\www\site\vendor\laravel\framework\src\Illuminate\Routing\Router.php(657): Illuminate\Routing\Router->runRouteWithinStack(Object(Illuminate\Routing\Route), Object(Illuminate\Http\Request))
#43 C:\wamp\www\site\vendor\laravel\framework\src\Illuminate\Routing\Router.php(623): Illuminate\Routing\Router->runRoute(Object(Illuminate\Http\Request), Object(Illuminate\Routing\Route))
#44 C:\wamp\www\site\vendor\laravel\framework\src\Illuminate\Routing\Router.php(612): Illuminate\Routing\Router->dispatchToRoute(Object(Illuminate\Http\Request))
#45 C:\wamp\www\site\vendor\laravel\framework\src\Illuminate\Foundation\Http\Kernel.php(176): Illuminate\Routing\Router->dispatch(Object(Illuminate\Http\Request))
#46 C:\wamp\www\site\vendor\laravel\framework\src\Illuminate\Routing\Pipeline.php(30): Illuminate\Foundation\Http\Kernel->Illuminate\Foundation\Http\{closure}(Object(Illuminate\Http\Request))
#47 C:\wamp\www\site\vendor\laravel\framework\src\Illuminate\Foundation\Http\Middleware\TransformsRequest.php(21): Illuminate\Routing\Pipeline->Illuminate\Routing\{closure}(Object(Illuminate\Http\Request))
#48 C:\wamp\www\site\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php(163): Illuminate\Foundation\Http\Middleware\TransformsRequest->handle(Object(Illuminate\Http\Request), Object(Closure))
#49 C:\wamp\www\site\vendor\laravel\framework\src\Illuminate\Routing\Pipeline.php(53): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))
#50 C:\wamp\www\site\vendor\laravel\framework\src\Illuminate\Foundation\Http\Middleware\TransformsRequest.php(21): Illuminate\Routing\Pipeline->Illuminate\Routing\{closure}(Object(Illuminate\Http\Request))
#51 C:\wamp\www\site\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php(163): Illuminate\Foundation\Http\Middleware\TransformsRequest->handle(Object(Illuminate\Http\Request), Object(Closure))
#52 C:\wamp\www\site\vendor\laravel\framework\src\Illuminate\Routing\Pipeline.php(53): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))
#53 C:\wamp\www\site\vendor\laravel\framework\src\Illuminate\Foundation\Http\Middleware\ValidatePostSize.php(27): Illuminate\Routing\Pipeline->Illuminate\Routing\{closure}(Object(Illuminate\Http\Request))
#54 C:\wamp\www\site\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php(163): Illuminate\Foundation\Http\Middleware\ValidatePostSize->handle(Object(Illuminate\Http\Request), Object(Closure))
#55 C:\wamp\www\site\vendor\laravel\framework\src\Illuminate\Routing\Pipeline.php(53): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))
#56 C:\wamp\www\site\vendor\laravel\framework\src\Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode.php(62): Illuminate\Routing\Pipeline->Illuminate\Routing\{closure}(Object(Illuminate\Http\Request))
#57 C:\wamp\www\site\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php(163): Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode->handle(Object(Illuminate\Http\Request), Object(Closure))
#58 C:\wamp\www\site\vendor\laravel\framework\src\Illuminate\Routing\Pipeline.php(53): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))
#59 C:\wamp\www\site\vendor\fideloper\proxy\src\TrustProxies.php(57): Illuminate\Routing\Pipeline->Illuminate\Routing\{closure}(Object(Illuminate\Http\Request))
#60 C:\wamp\www\site\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php(163): Fideloper\Proxy\TrustProxies->handle(Object(Illuminate\Http\Request), Object(Closure))
#61 C:\wamp\www\site\vendor\laravel\framework\src\Illuminate\Routing\Pipeline.php(53): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))
#62 C:\wamp\www\site\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php(104): Illuminate\Routing\Pipeline->Illuminate\Routing\{closure}(Object(Illuminate\Http\Request))
#63 C:\wamp\www\site\vendor\laravel\framework\src\Illuminate\Foundation\Http\Kernel.php(151): Illuminate\Pipeline\Pipeline->then(Object(Closure))
#64 C:\wamp\www\site\vendor\laravel\framework\src\Illuminate\Foundation\Http\Kernel.php(116): Illuminate\Foundation\Http\Kernel->sendRequestThroughRouter(Object(Illuminate\Http\Request))
#65 C:\wamp\www\site\public\index.php(55): Illuminate\Foundation\Http\Kernel->handle(Object(Illuminate\Http\Request))
#66 {main}
"} 
Sep
23
4 days ago
Activity icon

Started a new Conversation ErrorException (E_ERROR) Undefined Variable: AttributeValues (View: C:\wamp\www\site\resources\views\site\pages\products.blade.php) And BadMethodCallException

when I make a name of product in search bar and click enter there's this error

ErrorException (E_ERROR)
Undefined variable: attributeValues (View: C:\wamp\www\site\resources\views\site\pages\products.blade.php)
Previous exceptions
Undefined variable: attributeValues (0)

and when I check a value to filter product with size forexemple size :s with checkbox it return this error:

BadMethodCallException
Call to undefined method App\Models\Product::attribute_values()

relations:

class Product extends Model
{
 public function attributes()
    {
        return $this->hasMany(ProductAttribute::class);
    }
class ProductAttribute extends Model
{
    /**
     * @var string
     */
    protected $table = 'product_attributes';

    /**
     * @var array
     */
    protected $fillable = ['attribute_id', 'product_id', 'value', 'quantity', 'price'];

    /**
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function product()
    {
        return $this->belongsTo(Product::class);
    }

    /**
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function attribute()
    {
        return $this->belongsTo(Attribute::class);
    }
class Attribute extends Model
{
  
 public function values()
    {
        return $this->hasMany(AttributeValue::class);
    }
class AttributeValue extends Model
{
 public function productAttributes()
    {
        return $this->belongsToMany(ProductAttribute::class);
    }

products.blade.php:

h6 class="title">By size </h6>
                            </a>
                        </header>
                       
                        
                        <div class="filter-content collapse show" id="collapse46">
                            <div class="card-body">
                           <form method="get" action="{{ route('products.index') }}"> 
                              @foreach($attributeValues as $attributeValue)
                              @if ($attributeValue->attribute_id == 1)
                               
                                    <label for="size" class="form-check">
                                         <input name="filter[attributeValue]" type="checkbox" value="{{ $attributeValue->value }}"
                                        @if (in_array($attributeValue->value, explode(',', request()->input('filter.attributeValue'))))
                                        checked
                                        @endif
                                         >
                                        <span class="form-check-label">
                                      {{ $attributeValue->value }}
                                      
                                        </span>
                                    </label>
                                    <!-- form-check.// -->
                            
                                </form>
                              @endif 
                             
                            @endforeach
                        
                            </div>

<button type="submit">apply filter</button>
<h6 class="title">By color </h6>
                            </a>
                        </header>
                       
                        
                        <div class="filter-content collapse show" id="collapse46">
                            <div class="card-body">
                            <form method="get" action="{{ route('products.index') }}"> 
                              @foreach($attributeValues as $attributeValue)
                              @if ($attributeValue->attribute_id == 2)
                               
                                    <label for="color" class="form-check">
                                         <input name="filter[attributeValue]" type="checkbox" value="{{ $attributeValue->value }}"
                                        @if (in_array($attributeValue->value, explode(',', request()->input('filter.attributeValue'))))
                                        checked
                                        @endif
                                         >
                                        <span class="form-check-label">
                                      {{ $attributeValue->value }}
                                      
                                        </span>
                                    </label>
                                    <!-- form-check.// -->
                            
                                </form>
                              @endif 
                             
                            @endforeach
<button type="submit">apply filter</button>

productController:

 public function index( Request $request)
    {   
        
       $attributeValues=AttributeValue::all();
      
        
        $products = QueryBuilder::for(Product::class)
          
            ->allowedFilters([
                AllowedFilter::exact('brand', 'brand_id'),
                AllowedFilter::custom('category', new FiltersCategories),
                AllowedFilter::custom('attributeValue', new FiltersAttributeValues),
                ])
            ->get();
        return view('site.pages.products', compact('products','attributeValues'));

FiltersAttributeValues.php:

<?php

namespace App\Filters;

use Spatie\QueryBuilder\Filters\Filter;
use Illuminate\Database\Eloquent\Builder;

class FiltersAttributeValues implements Filter
{
    public function __invoke(Builder $query, $value, string $property) : Builder
    {
        return $query->whereHas('attribute_values', function ($query) use ($value) {
            if (is_array($value)) {
                return $query->whereIn('value', $value);
            }

            return $query->where('value', $value);
        });
    }
}

please how to fix that thank you

Sep
17
1 week ago
Activity icon

Replied to How To Make Checkbox Work For Product Filters?

@SilenceBringer any idea to make this work with all productfilters(category,brand,size,color) thank you

Activity icon

Replied to How To Make Checkbox Work For Product Filters?

thank you @automica

I tried some code but it's wrong and there's an error :

BadMethodCallException
Method Illuminate\Database\Eloquent\Collection::whereHas does not exist.

productcontroller

 public function index( Request $request)
    {   
       
      
        $categories = Category::all();

        
        $products = Product::all();
        
        
        

if (request('category')) {
 

        $products = $products->where('slug', request('category'))->whereHas('categories', 
		function($query) use ($categories) {
            		$query->where('category_id', $categories);
        	
        })->get();
    }

        $products=$products->where('status','1');
        
        return view('site.pages.products', compact('products','categories'));
       
}

products.blade.php

<p>Categories</p>
<form method="get" action="{{ route('products.index') }}"> 
@foreach ($categories as $category)
@if ($category->id!=1)
    <label>
        <input
            name="category" type="checkbox" value="{{ $category->id }}"
            @if (in_array($category->id, explode(',', request()->input('category'))))
                checked
            @endif
        >
        {{ $category->name }}
    </label>
    @endif
@endforeach

<button type="submit">apply filter</button>
Sep
16
1 week ago
Activity icon

Replied to Illuminate \ Database \ QueryException (42S22) SQLSTATE[42S22]: Column Not Found: 1054 Champ 'category_id' Inconnu Dans Where Clause (SQL: Select * From `products` Where `category_id` = 2)

thank you @laracoft but what about this

$addRelationConstraint = false;

QueryBuilder::for(User::class)
    ->join('posts', 'posts.user_id', 'users.id')
    ->allowedFilters(AllowedFilter::exact('posts.title', null, $addRelationConstraint));

in https://spatie.be/docs/laravel-query-builder/v2/features/filtering

I tried to write this code but the same error display

->join('categories', 'products.category_id', 'categories.id')
            ->allowedFilters([
                AllowedFilter::exact('brand', 'brand_id'),
                AllowedFilter::exact('category', null, $addRelationConstraint),
                ])
            ->get();
Activity icon

Replied to Illuminate \ Database \ QueryException (42S22) SQLSTATE[42S22]: Column Not Found: 1054 Champ 'category_id' Inconnu Dans Where Clause (SQL: Select * From `products` Where `category_id` = 2)

thank you @laracoft it's not in products table but in product_categories

class Category extends Model
{
 public function products()
    {
        return $this->belongsToMany(Product::class, 'product_categories', 'category_id', 'product_id');
    }
class Product extends Model
{
 public function categories()
    {
        return $this->belongsToMany(Category::class, 'product_categories', 'product_id', 'category_id');
    }
Activity icon

Started a new Conversation Illuminate \ Database \ QueryException (42S22) SQLSTATE[42S22]: Column Not Found: 1054 Champ 'category_id' Inconnu Dans Where Clause (SQL: Select * From `products` Where `category_id` = 2)

when I check for exemple category:Men to filter products by category return this problem

SQLSTATE[42S22]: Column not found: 1054 Champ 'category_id' inconnu dans where clause (SQL: select * from `products` where `category_id` = 2)

and when I check brand it works but when I check two brands and click filter it return just the products of the last or first brand I check (not both) I check prada and gucci it reurn products of prada or gucci not both thank you

productcontroller

public function index(Request $request)
    {   
       $values=ProductAttribute::all();
        $categories = Category::all();

        $brands = Brand::all();
    
        $products = QueryBuilder::for(Product::class)
            ->with('categories')
            ->with('brand')
           
            ->allowedFilters([
                AllowedFilter::exact('brand', 'brand_id'),
                AllowedFilter::exact('category', 'category_id'),
                AllowedFilter::exact('value', 'value'),
                ])
            ->get();
    
        return view('site.pages.products', compact('products','brands','categories','values'));
       
}

products.blade.php

    <p>Brands</p>
                <form method="get" action="{{ route('products.index') }}"> 
@foreach ($brands as $brand)
    <label class="m-checkbox">
        <input
            name="filter[brand]" type="checkbox" value="{{ $brand->id }}"
            @if (in_array($brand->id, explode(',', request()->input('filter.brand'))))
                checked
            @endif
        >
        {{ $brand->name }}
    </label>
@endforeach
<button type="submit">apply filter</button>
<p>Categories</p>
<form method="get" action="{{ route('products.index') }}"> 
@foreach ($categories as $category)
@if ($category->id!=1)
    <label>
        <input
            name="filter[category]" type="checkbox" value="{{ $category->id }}"
            @if (in_array($category->id, explode(',', request()->input('filter.category'))))
                checked
            @endif
        >
        {{ $category->name }}
    </label>
    @endif
@endforeach

<button type="submit">apply filter</button>
Sep
15
1 week ago
Activity icon

Replied to Laravel Query Builder

thank you @thewebartisan7 nothing change same error and about brand I mean that when I check two brands and click filter it return just the products of the last or first brand I check (not both) I check zara and hm it reurn products of hm or zara not both

Sep
14
1 week ago
Activity icon

Replied to Laravel Query Builder

thank you very very much @thewebartisan7 I'm tried what you suggested and it works with brand but when I check 2 brands it return just the products of the last or first brand I check not both and return the ids of the two brands

http://localhost/site/public/products?filter%5Bbrand%5D=1&filter%5Bbrand%5D=2

and for category if I check one or two of them it return this (without using join)

Illuminate \ Database \ QueryException (42S22)
SQLSTATE[42S22]: Column not found: 1054 Champ 'category_id' inconnu dans where clause (SQL: select * from `products` where `category_id` = 2)
Previous exceptions
SQLSTATE[42S22]: Column not found: 1054 Champ 'category_id' inconnu dans where clause (42S22)

and when I use (join) I don't know how to write this exactly it return error also

 ->join('categories', 'product.id', 'categories.product_id')
            ->allowedFilters([
                AllowedFilter::exact('brand', 'brand_id'),
                AllowedFilter::exact('category', null, $addRelationConstraint),
                ])
            ->get();
Illuminate \ Database \ QueryException (42S22)
SQLSTATE[42S22]: Column not found: 1054 Champ 'category' inconnu dans where clause (SQL: select * from `products` inner join `categories` on `product`.`id` = `categories`.`product_id` where `category` = 2)
Previous exceptions
SQLSTATE[42S22]: Column not found: 1054 Champ 'category' inconnu dans where clause (42S22)

category id

http://localhost/site/public/products?filter%5Bcategory%5D=2

so how to change that for attributes(size,color) also and thank you very much

Sep
13
2 weeks ago
Activity icon

Started a new Conversation Laravel Query Builder

hi I tried to use spatie laravel query builder to create filters(brand,category,size and color) in my project so it works just for brand and not for category so how to change code in productcontroller to make it work thank you

and this is an image to explain

https://i.imgur.com/qsFluwP.png

and how to add code in productcontroller and products.blade.php to filtering size and color with the best way

this is code:

relations:

class Category extends Model
{
 public function products()
    {
        return $this->belongsToMany(Product::class, 'product_categories', 'category_id', 'product_id');
    }
class Product extends Model
{
 public function categories()
    {
        return $this->belongsToMany(Category::class, 'product_categories', 'product_id', 'category_id');
    }
class Product extends Model
{
 public function attributes()
    {
        return $this->hasMany(ProductAttribute::class);
    }
class ProductAttribute extends Model
{
    /**
     * @var string
     */
    protected $table = 'product_attributes';

    /**
     * @var array
     */
    protected $fillable = ['attribute_id', 'product_id', 'value', 'quantity', 'price'];

    /**
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function product()
    {
        return $this->belongsTo(Product::class);
    }

    /**
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function attribute()
    {
        return $this->belongsTo(Attribute::class);
    }
class Attribute extends Model
{
  
 public function values()
    {
        return $this->hasMany(AttributeValue::class);
    }
class AttributeValue extends Model
{
 public function productAttributes()
    {
        return $this->belongsToMany(ProductAttribute::class);
    }

productcontroller:

 public function index(Request $request)
    {   
       $attributeValues=AttributeValue::all();
        $categories = Category::all();

        $brands = Brand::all();
    
        $products = QueryBuilder::for(Product::class)
            ->allowedFilters([
                AllowedFilter::exact('brand', 'brand_id'),
                AllowedFilter::exact('category', 'category_id'),
                ])
            ->get();
    
        return view('site.pages.products', compact('products','brands','categories','attributeValues'));
       
}

products.plade.php

@extends('site.app')
@section('title', 'products')
@section('content')
<section class="section-content bg padding-y">
    <div class="container">
    <div class="row">
    <aside class="col-sm-3">
    <div class="card card-filter">
   
                    
                    <div class="container">
        @if (session()->has('success_message'))
            <div class="alert alert-success">
                {{ session()->get('success_message') }}
            </div>
        @endif

        @if(count($errors) > 0)
            <div class="alert alert-danger">
                <ul>
                    @foreach ($errors->all() as $error)
                        <li>{{ $error }}</li>
                    @endforeach
                </ul>
            </div>
        @endif
    </div>
   
        <div>
            <div class="products-header">
                <h1 class="stylish-heading"></h1>
                <div>
                    <strong>Price: </strong>
                    <a href="{{ route('products.index', [ 'sort' => 'low_high']) }}">Low to High</a> |
                    <a href="{{ route('products.index', [ 'sort' => 'high_low']) }}">High to Low</a>

                </div>
            </div>
                    <!-- card-group-item.// -->
                  
                  
                </div>
                <p>Brands</p>
@foreach ($brands as $brand)
    <label class="m-checkbox">
        <input
            name="brand" type="checkbox" value="{{ $brand->id }}"
            @if (in_array($brand->id, explode(',', request()->input('filter.brand'))))
                checked
            @endif
        >
        {{ $brand->name }}
    </label>
@endforeach
<button type="button" id="filter">Filter</button>
<p>Categories</p>
@foreach ($categories as $category)
@if ($category->id!=1)
    <label>
        <input
            name="category" type="checkbox" value="{{ $category->id }}"
            @if (in_array($category->id, explode(',', request()->input('filter.category'))))
                checked
            @endif
        >
        {{ $category->name }}
    </label>
@endif
@endforeach

                
            </aside>
        
           
              
                    
                    <main class="col-sm-9">
        <div id="code_prod_complex">
        @if( session('status'))
                        <div class="alert alert-info">
                            {{ session('status')}}
                        </div>
                    @endif
                    <div class="container">
            <div class="row">
            
           
            @forelse($products as $product)
                    <div class="col-md-3">
                    <figure class="card card-product">
                            @if ($product->images->count() > 0)
                                <div class="img-wrap padding-y"><img src="{{ asset('storage/'.$product->images->first()->full) }}" alt=""></div>
                            @else
                                <div class="img-wrap padding-y"><img src="https://via.placeholder.com/176" alt=""></div>
                            @endif
                            <figcaption class="info-wrap">
                                <h4 class="title"><a href="{{ route('product.show', $product->slug) }}">{{ $product->name }}</a></h4>
                            </figcaption>
                           
                            <div class="bottom-wrap">
                                <a href="{{ route('product.show', $product->slug) }}" class="btn btn-sm btn-success float-right">View Details</a>
                               
                                
                                @if ($product->sale_price != 0)
                                    <div class="price-wrap h5">
                                        <span class="price"> {{ config('settings.currency_symbol').$product->sale_price }} </span>
                                        <del class="price-old"> {{ config('settings.currency_symbol').$product->price }}</del>
                                    </div>
                                @else
                                    <div class="price-wrap h5">
                                        <span class="price"> {{ config('settings.currency_symbol').$product->price }} </span>
                                    </div>
                                @endif
                  
                            </div>
                         
                        </figure>
                    </div>
                     
                        
                   
                    @empty
                    <p>No Products found </p>
                @endforelse
            </div>
             
        </div>
        </main>
        
    </div>
   
</section>
@stop
@push('scripts')
<script>
    function getIds(checkboxName) {
        let checkBoxes = document.getElementsByName(checkboxName);
        let ids = Array.prototype.slice.call(checkBoxes)
                        .filter(ch => ch.checked==true)
                        .map(ch => ch.value);
        return ids;
    }

    function filterResults () {
        let brandIds = getIds("brand");

        let catagoryIds = getIds("catagory");

        let href = 'products?';

        if(brandIds.length) {
            href += 'filter[brand]=' + brandIds;
        }

        if(catagoryIds.length) {
            href += '&filter[category]=' + catagoryIds;
        }

        document.location.href=href;
    }

    document.getElementById("filter").addEventListener("click", filterResults);
</script>
@endpush
Activity icon

Replied to How To Make Checkbox Work For Product Filters?

thank you @automica ok I will explain with image

when I make a filter section just "by category" and click the link of robe in 'by category' the products of robe display and there's no problem like this

https://i.imgur.com/7yH6ARy.png

and this is the code in category.blade.php:

<h3>By Category</h3>
            <ul>
                @foreach ($categories as $category)
               @if ($category->id!=1)
                    <li class=""><a href="{{ route('category.show', $category->slug) }}">{{ $category->name }}</a></li>
                @endif
                @endforeach
            </ul>

and in header there's the search bar , it works :

if i write bask in search bar it display all products in their name bask like bask, basket like this search: https://i.imgur.com/YmP1lXW.png

result: https://i.imgur.com/mWVA24H.png

and if write x: https://i.imgur.com/f0qI4yK.png result : search failed please try again with all products https://i.imgur.com/RG70Coa.png

and I made a filter section by price low_high high_low: productcontroller:

     if (request()->sort == 'low_high') {
            $products = Product::where('status', '1')->orderBy('price')->paginate($pagination);
        } elseif (request()->sort == 'high_low') {
            $products = Product::where('status', '1')->orderBy('price', 'desc')->paginate($pagination);
        } else {
           
       
       
       $products = Product::where('status', '1')->OrderBy('name', 'asc')->paginate($pagination);
    }
        return view('site.pages.products', compact('products','categories' ));
       
}

products.blade.php:

   <div>
                    <strong>Price: </strong>
                    <a href="{{ route('products.index', [ 'sort' => 'low_high']) }}">Low to High</a> |
                    <a href="{{ route('products.index', [ 'sort' => 'high_low']) }}">High to Low</a>

                </div>

image:high_low: https://i.imgur.com/b2F49BK.png image :low_high: https://i.imgur.com/Z0cYgjt.png

and this is code: header.blade.php:

<div class="col-lg-6 col-sm-6">
                    <form action="{{ url('products') }}" class="search-wrap" method="post" >
                    @csrf
                        <div class="input-group">
                            <input type="text" name="q" id="q" class="form-control" placeholder="Search">
                            <div class="input-group-append">
                                <button class="btn btn-primary" type="submit">
                                    <i class="fa fa-search"></i>
                                </button>
                            </div>
                        </div>
                    </form>
                </div>

products.blade.php:

@extends('site.app')
@section('title', 'products')
@section('content')
<section class="section-content bg padding-y">
    <div class="container">
    <div class="row">
    <aside class="col-sm-3">
    <div class="card card-filter">
   
                    
                    <div class="container">
        @if (session()->has('success_message'))
            <div class="alert alert-success">
                {{ session()->get('success_message') }}
            </div>
        @endif

        @if(count($errors) > 0)
            <div class="alert alert-danger">
                <ul>
                    @foreach ($errors->all() as $error)
                        <li>{{ $error }}</li>
                    @endforeach
                </ul>
            </div>
        @endif
    </div>
   
        <div>
            <div class="products-header">
                <h1 class="stylish-heading"></h1>
                <div>
                    <strong>Price: </strong>
                    <a href="{{ route('products.index', [ 'sort' => 'low_high']) }}">Low to High</a> |
                    <a href="{{ route('products.index', [ 'sort' => 'high_low']) }}">High to Low</a>

                </div>
            </div>
                    <!-- card-group-item.// -->
                  
                  
                </div>
                <!-- card.// -->
                
            </aside>
                    
                    <main class="col-sm-9">
        <div id="code_prod_complex">
        @if( session('status'))
                        <div class="alert alert-info">
                            {{ session('status')}}
                        </div>
                    @endif
                    <div class="container">
            <div class="row">
            
           
            @forelse($products as $product)
                    <div class="col-md-3">
                    <figure class="card card-product">
                            @if ($product->images->count() > 0)
                                <div class="img-wrap padding-y"><img src="{{ asset('storage/'.$product->images->first()->full) }}" alt=""></div>
                            @else
                                <div class="img-wrap padding-y"><img src="https://via.placeholder.com/176" alt=""></div>
                            @endif
                            <figcaption class="info-wrap">
                                <h4 class="title"><a href="{{ route('product.show', $product->slug) }}">{{ $product->name }}</a></h4>
                            </figcaption>
                           
                            <div class="bottom-wrap">
                                <a href="{{ route('product.show', $product->slug) }}" class="btn btn-sm btn-success float-right">View Details</a>
                               
                                
                                @if ($product->sale_price != 0)
                                    <div class="price-wrap h5">
                                        <span class="price"> {{ config('settings.currency_symbol').$product->sale_price }} </span>
                                        <del class="price-old"> {{ config('settings.currency_symbol').$product->price }}</del>
                                    </div>
                                @else
                                    <div class="price-wrap h5">
                                        <span class="price"> {{ config('settings.currency_symbol').$product->price }} </span>
                                    </div>
                                @endif
                  
                            </div>
                         
                        </figure>
                    </div>
                     
                        
                   
                    @empty
                    <p>No Products found </p>
                @endforelse
            </div>
            {{$products->links()}} 
        </div>
        </main>
        
    </div>
   
</section>
@stop

productcontroller:

public function search( Request $request) {
    $request->validate([
        'q' => 'required'
    ]);
    $q = $request->q;
   
    $products = Product::where('name', 'like', '%' . $q . '%')->where('status', '1')->paginate(15);
    if ($products->count()) {
        return view('site.pages.products')->with(
            'products' ,  $products
        );
    } else {
        
        return redirect('/products')->with(
            'status' , 'search failed ,, please try again'
  );
    }
    
}

route:

Route::view('/', 'site.pages.homepage');
Route::get('/category/{slug}', 'Site\[email protected]')->name('category.show');

Route::get('/product/{slug}', 'Site\[email protected]')->name('product.show');
Route::get('/products', 'Site\[email protected]')->name('products.index');
Route::post('/products', 'Site\[email protected]')->name('products.search');

when I click men->basket in navbar it works and I made the filter section (by category,by brand,...) with checkbox and select (it doesn't work and this is the problem) and this is the image https://i.imgur.com/eoQsXzA.png

https://i.imgur.com/pyR2s13.png so what I have to do now I want to make this work and organize it step by step thank you very much

Sep
11
2 weeks ago
Activity icon

Replied to How To Make Checkbox Work For Product Filters?

thank you @automica but it give me this error

BadMethodCallException
Method Illuminate\Database\Eloquent\Collection::orderBy does not exist.

but when I change this

$products = $products->orderBy('id', 'desc')->paginate(10);

to this

$products = Product::orderBy('id', 'desc')->paginate(10);

there's no error and nothing change I did

  <form method="get" action="{{ route('category.show', $category->slug) }}"> 
                                
                @foreach ($categories as $category)
                
                                    <label class="form-check">
                                    <input class="form-check-input" name="category[]" value="{{ $category->slug }}" type="checkbox">
                                    
                                        <span class="form-check-label">
                    <span class="float-right badge badge-light round"></span> {{ $category->name }}
                                        </span>
                                    </label>
                                    
                                    
                                    
            
                                    
            @endforeach 
            <button type="submit">apply filter</button>

and this code to display products by category and the categories in navbar

  @forelse($category->products as $product)
                    <div class="col-md-3">
                        <figure class="card card-product">
                            @if ($product->images->count() > 0)
                                <div class="img-wrap padding-y"><img src="{{ asset('storage/'.$product->images->first()->full) }}" alt=""></div>
                            @else
                                <div class="img-wrap padding-y"><img src="https://via.placeholder.com/176" alt=""></div>
                            @endif
                            <figcaption class="info-wrap">
                                <h4 class="title"><a href="{{ route('product.show', $product->slug) }}">{{ $product->name }}</a></h4>
                            </figcaption>
                            <div class="bottom-wrap">
                                <a href="{{ route('product.show', $product->slug) }}" class="btn btn-sm btn-success float-right">View Details</a>
                                @if ($product->sale_price != 0)
                                    <div class="price-wrap h5">
                                        <span class="price"> {{ config('settings.currency_symbol').$product->sale_price }} </span>
                                        <del class="price-old"> {{ config('settings.currency_symbol').$product->price }}</del>
                                    </div>
                                @else
                                    <div class="price-wrap h5">
                                        <span class="price"> {{ config('settings.currency_symbol').$product->price }} </span>
                                    </div>
                                @endif
                            </div>
                        </figure>
                    </div>
                  
                @empty
                    <p>No Products found in {{ $category->name }}.</p>
                    
                @endforelse
                
            </div>
Activity icon

Replied to How To Make Checkbox Work For Product Filters?

oh thank you @automica I will try it

Activity icon

Replied to How To Make Checkbox Work For Product Filters?

thank you @automica I did it like this

    @foreach($products as $product)              
                @foreach ($product->categories as $category)
                @foreach ($category->products as $category)

I just try it and nothing change

Activity icon

Replied to How To Make Checkbox Work For Product Filters?

hi @Sinnbeck please can you give me a solution how to solve this and what change and what delete in this code thank you very much

Activity icon

Replied to How To Make Checkbox Work For Product Filters?

thank you @automica I tried this

  if (request()->category) {
            $products = Product::where('slug', request('category'))->OrderBy('id', 'desc');
                    
        };
      $products = Product::orderBy('id', 'desc')->paginate(10);
        return view('site.pages.category', compact('category','products'));
    }

and this

 if (request()->category) {
            $products = Product::with('categories')->whereHas('categories', function ($query) {
                $query->where('slug', request()->category);
            });

nothing change

Sep
10
2 weeks ago
Activity icon

Replied to How To Make Checkbox Work For Product Filters?

thank you @automica very much I made some changes but nothing change still the same problem so if you suggest any change or give me an exemple to change some code (sorry sorry but I'm beginner and try to improve my self) maybe you find a fault and you know how to change the code and thank you very much

Activity icon

Replied to How To Make Checkbox Work For Product Filters?

thank you @automica very much but when I choose robe(category) display products of robe that's okay and in category page I have the filter section so when I choose sandal with checkbox and click apply filter return the same page with the products of robe and not for sandal and the link like this

http://localhost/site/public/category/robe?category%5B%5D=sandal

how to fix that thank you

Activity icon

Replied to How To Make Checkbox Work For Product Filters?

thank you @automica but the problem is with checkbox when I click for exemple color:red nothing change still the same page and the same products so I want when check for exemple brand:zara and color:red with checkbox display all products related to zara and red how to do it thank you

Sep
08
2 weeks ago
Activity icon

Started a new Conversation How To Make Checkbox Work For Product Filters?

I want when check one or multiple category,brand,size,color,... with checkbox display the products related to the categories(product filters) (for exemple check dress and basket display products of dress and basket) and also for brand,size,... I mean: On the category page, you can load the product attributes such as color or size and make a filtering section

how to change this code to display products? thank you

category.blade.php:

                              <h6 class="title">By Category </h6>
                            </a>
                        </header>
                        <div class="filter-content collapse show" id="collapse44">
                            <div class="card-body">
                                <form>
                                <form method="get" action="{{ route('category.show', $category->slug) }}"> 
                                
                @foreach ($categories as $category)
                
                                    <label class="form-check">
                                    <input class="form-check-input" name="category[]" value="{{ $category->slug }}" type="checkbox">
                                    
                                        <span class="form-check-label">
                    <span class="float-right badge badge-light round"></span> {{ $category->name }}
                                        </span>
                                    </label>
                                    
                                    
                                    
            
                                    
            @endforeach 
            <button type="submit">apply filter</button>
                                    </form>
                                    

By Brand

 <div class="filter-content collapse show" id="collapse45">
                    @foreach($brands as $brand)
                        <div class="card-body">
                        
                            <form>
                            
                                <label for="brand_id" class="form-check">
                                
                                    <input class="form-check-input" id="brand_id" value="{{$brand->id}}" type="checkbox">
                                    <span class="form-check-label">
                                  {{ $brand->name }}
                                    </span>
             by brand
                         <h6 class="title">By Brand </h6>
                     </a>
                 </header>
                 <form method="get" action="{{ route('category.show', $category->slug) }}"> 
                 <div class="filter-content collapse show" id="collapse48">
             
                                     <select name="brand_id" id="brand_id" class="form-control @error('brand_id') is-invalid @enderror">
                                         <option value="0">Select a brand</option>
                                         @foreach($brands as $brand)
                                             <option @if(request()->brand) selected @endif value="{{$brand->id}}">{{ $brand->name }}</option>
                                         @endforeach
                                     </select>
                                     </div>
                
                                     <button type="submit">apply filter</button>

by size

    <div class="filter-content collapse show" id="collapse46">
                        <div class="card-body">
                        @foreach($products as $product)
                          @foreach($product->attributes as $attributeValue)
                          @if ($attributeValue->attribute_id == 1)
                            <form>
                                <label for="size" class="form-check">
                                    <input class="form-check-input" id="attribute" value="{{$attributeValue->value}}" type="checkbox">
                                    <span class="form-check-label">
                                  {{ $attributeValue->value }}
                                  
                                    </span>

by color

      <h6 class="title">By color </h6>
                          </a>
                      </header>
                     
                      
                      <div class="filter-content collapse show" id="collapse47">
                          <div class="card-body">
                          @foreach($products as $product)
                          @foreach($product->attributes as $attribute)
                          @foreach($product->attributes as $attributeValue)
                         
                          @if ($attribute->id == 2)
                              <form>
                                  <label for="color" class="form-check">
                                      <input class="form-check-input" id="{{$attributeValue->id}}" value="{{$attributeValue->value}}" type="checkbox">
                                      <span class="form-check-label">
                                    {{ $attributeValue->value}}
                                    
                                      </span>

category controller:

<?php

namespace App\Http\Controllers\Site;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Contracts\CategoryContract;
use App\Models\Product;
use App\Models\Category;
use App\Models\Brand;

class CategoryController extends Controller
{
    protected $categoryRepository;

    public function __construct(CategoryContract $categoryRepository)
    {
        $this->categoryRepository = $categoryRepository;
    }
public function show($slug)
    {
        $category = $this->categoryRepository->findBySlug($slug);
        $pagination = 2;
        
        
       
        if (request()->category) { 
            $products = Product::with('categories')->whereHas('categories', function ($query) {
                $query->whereIn('id', request('category'));
             });
            };
            
     
        if (request()->brand) {
            $products = Product::when($brand, function ($query, $brand) {
                return $query->where('brand_id', $brand);
            });
           
            
            };
      
      
                if (request()->size) {
                    $products = ProductAttribute::where('id','=',1)->where('id', request('size'))->OrderBy('id', 'desc')->paginate($pagination);
                    
                    };
                    if (request()->color) {
                        $products = ProductAttribute::where('id','=',2)->where('id', request('color'))->OrderBy('id', 'desc')->paginate($pagination);
                        
                        };
        if (request()->sort == 'low_high') {
            $products = Product::orderBy('price')->paginate($pagination);
        } elseif (request()->sort == 'high_low') {
            $products = Product::orderBy('price', 'desc')->paginate($pagination);
        } 
           
        
        
   
    
       
        return view('site.pages.category', compact('category'));
    }
}

Aug
21
1 month ago
Activity icon

Replied to About Laravel 5.8

thank you @jlrdw

Activity icon

Started a new Conversation About Laravel 5.8

how long(years) can I use laravel 5.8 to still making an e-commerce site? thank you

Apr
25
5 months ago
Activity icon

Replied to Error: Request Failed With Status Code 404 :attributevalues And ProductAttribute With Laravel And Vuejs

thank you very much @rizwanjaved sorry, but I don't understand what I have to do so please if you can explain how to do that step by step(to help all beginners like me) and thank you very much

Mar
30
5 months ago
Activity icon

Replied to Error: Request Failed With Status Code 404 :attributevalues And ProductAttribute With Laravel And Vuejs

when I try to add attribute value (example :red) and it's price(example:10)

(attribute values for products example dress has a red color ) (attribute:color and attribute values:red)and click save I can't save neither price nor value and there's nothing change but in devtools (f12 then console) there's error like this

error:Failed to load resource: the server responded with a status of 404 (Not Found)

error in : /admin/attributes/get-values:1


 Failed to load resource: the server responded with a status of 404 (Not Found)
 Error: Request failed with status code 404
Activity icon

Replied to Error: Request Failed With Status Code 404 :attributevalues And ProductAttribute With Laravel And Vuejs

thank you @snapey

in admin dashboard(route:/admin) admin can add or update attributes and attribute values (and their price )(admin/attributes/add-values)(laravel and vuejs)

I have this problem in local server I can't save neither price nor value ( the error in devtools) but when I tried in 000webhost in attribute values there's value and price when I write red in value and click save it works but when I add value and price I can't save and display this error too

Mar
27
6 months ago
Activity icon

Replied to Error: Request Failed With Status Code 404 :attributevalues And ProductAttribute With Laravel And Vuejs

@snapey What route does this POST http://localhost/admin/attributes/add-values hit

Not Found
The requested URL was not found on this server.

Apache/2.4.41 (Win32) PHP/7.3.12 Server at localhost Port 80
Activity icon

Replied to Error: Request Failed With Status Code 404 :attributevalues And ProductAttribute With Laravel And Vuejs

thank you

route

 Route::group(['prefix'  =>   'attributes'], function() {

            Route::get('/', 'Admin\[email protected]')->name('admin.attributes.index');
            Route::get('/create', 'Admin\[email protected]')->name('admin.attributes.create');
            Route::post('/store', 'Admin\[email protected]')->name('admin.attributes.store');
            Route::get('/{id}/edit', 'Admin\[email protected]')->name('admin.attributes.edit');
            Route::post('/update', 'Admin\[email protected]')->name('admin.attributes.update');
            Route::get('/{id}/delete', 'Admin\[email protected]')->name('admin.attributes.delete');
            
            Route::post('/get-values', 'Admin\[email protected]');
            Route::post('/add-values', 'Admin\[email protected]');
            Route::post('/update-values', 'Admin\[email protected]');
            Route::post('/delete-values', 'Admin\[email protected]');
    

controller

 <?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Models\AttributeValue;
use App\Http\Controllers\Controller;
use App\Contracts\AttributeContract;

class AttributeValueController extends Controller
{
    protected $attributeRepository;

    public function __construct(AttributeContract $attributeRepository)
    {
        $this->attributeRepository = $attributeRepository;
    }

    public function getValues(Request $request)
    {
        $attributeId = $request->input('id');
        $attribute = $this->attributeRepository->findAttributeById($attributeId);

        $values = $attribute->values;

        return response()->json($values);
    }

    public function addValues(Request $request)
    {
        $value = new AttributeValue();
        $value->attribute_id = $request->input('id');
        $value->value = $request->input('value');
        $value->price = $request->input('price');
        $value->save();

        return response()->json($value);
    }

    public function updateValues(Request $request)
    {
        $attributeValue = AttributeValue::findOrFail($request->input('valueId'));
        $attributeValue->attribute_id = $request->input('id');
        $attributeValue->value = $request->input('value');
        $attributeValue->price = $request->input('price');
        $attributeValue->save();

        return response()->json($attributeValue);
    }

    public function deleteValues(Request $request)
    {
        $attributeValue = AttributeValue::findOrFail($request->input('id'));
        $attributeValue->delete();

        return response()->json(['status' => 'success', 'message' => 'Attribute value deleted successfully.']);
    }
}