MattB

MattB

Member Since 6 Months Ago

Experience Points
3,560
Total
Experience

1,440 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
1
Lessons
Completed
Best Reply Awards
0
Best Reply
Awards
  • start-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-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-token Created with Sketch.

    Subscriber

    Earned if you are a paying Laracasts subscriber.

  • lifer-token Created with Sketch.

    Lifer

    Earned if you have a lifetime subscription to Laracasts.

  • lara-evanghelist Created with Sketch.

    Laracasts Evangelist

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

  • chatty-cathy Created with Sketch.

    Chatty Cathy

    Earned once you have achieved 500 forum replies.

  • lara-veteran Created with Sketch.

    Laracasts Veteran

    Earned once your experience points passes 100,000.

  • 10k-strong Created with Sketch.

    Ten Thousand Strong

    Earned once your experience points hits 10,000.

  • lara-master Created with Sketch.

    Laracasts Master

    Earned once 1000 Laracasts lessons have been completed.

  • laracasts-tutor Created with Sketch.

    Laracasts Tutor

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

  • laracasts-sensei Created with Sketch.

    Laracasts Sensei

    Earned once your experience points passes 1 million.

  • top-50 Created with Sketch.

    Top 50

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

Level 1
3,560 XP
Oct
23
2 weeks ago
Activity icon

Replied to URL Appended To Website URL But It's Not Wanted There

I get the link exactly as it's written in the db. If it's www.google.com in the db, the DD shows www.google.com exactly

Activity icon

Replied to URL Appended To Website URL But It's Not Wanted There

Yes I know, that's what I have done. Accessing them isn't the problem

Activity icon

Replied to URL Appended To Website URL But It's Not Wanted There

They're just ones like: www.google.com www.bbc.co.uk etc

Even ones like http://consolepassion do the same thing too

Activity icon

Started a new Conversation URL Appended To Website URL But It's Not Wanted There

Sorry, don't know how to explain the title better...I have the below line of code which grabs a URL from my database. When it shows on the site, it appends the url to be after the websites URL, ie it will go to www.sitename.com/website_from_db rather than www.webstite_from_db. How can I stop this, bearing in mind, the site in the database can be pasted in with http/https or just www. site name?

<div class="col-4"><a href={{ url($links->url) }} target="_blank">{{ $links->link_text }}</a><br>{{ $links->description }}</div>
Oct
22
3 weeks ago
Activity icon

Started a new Conversation Mailchimp Not Loading On All Pages

So, I have mailchimp working my laravel app, however its hit an miss when it shows. This is the header section from my layout blade file. Some pages that use this layout file will show the pop up but others don't:

<head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <script id="mcjs">!function(c,h,i,m,p){m=c.createElement(h),p=c.getElementsByTagName(h)[0],m.async=1,m.src=i,p.parentNode.insertBefore(m,p)}(document,"script","https://chimpstatic.com/mcjs-connected/js/users/a1d5b8ba711ecece58be5de11/1b204ce2d3c6f7dbe2d773358.js");</script>
    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
    <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.8.2/css/all.css">
    <link href="https://fonts.googleapis.com/css?family=Iceland|Nunito|Press+Start+2P&display=swap" rel="stylesheet">
    <link rel="icon" href="/images/pacmanfav.png" type="image/x-icon"/>
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <title>RetroWorld</title>
    <!-- Scripts -->
    <script src="{{ asset('js/app.js') }}" defer></script>
    <!-- Fonts -->
    <link rel="dns-prefetch" href="//fonts.gstatic.com">
    <link href="https://fonts.googleapis.com/css?family=Nunito" rel="stylesheet">
    <!-- Styles -->
    <link href="{{ asset('css/app.css') }}" rel="stylesheet">
    <script type="text/javascript" src="https://platform-api.sharethis.com/js/sharethis.js#property=5d495cf23387b20012d76b8a&product=sticky-share-buttons"></script>
  </head>

I suspect (though my be way off) that it's an issue with it not loading in time. Checked my console and got:

Uncaught TypeError: Cannot read property 'appendChild' of null
    at 1b204ce2d3c6f7dbe2d773358.js:43
    at 1b204ce2d3c6f7dbe2d773358.js:46

Is this the case, and if so how do I make it load on page load?

Oct
16
3 weeks ago
Activity icon

Replied to How To Update Images With Array

Ok that sorts out the initial error but when I try to upload now, all I get is a 404 page. Checked db and nothing was updated so I don't think it's a routing issue on redirect

Activity icon

Replied to How To Update Images With Array

Ok on further inspection of the error it's actually this line causing the problem:

$gameSearch->update($input);

Because this:

$input = $request->all();

Is also grabbing the image array:

array:14 [▼
  "_method" => "PATCH"
  "_token" => "MaP0WnARbUaRqlC4DNILgmW9TyUw9Aqt3fh11ioi"
  "title" => "Quackshot"
  "youtube" => null
  "price" => "15"
  "score" => "9"
  "description" => "Changed photos"
  "category_id" => "2"
  "sold" => "0"
  "manual" => "0"
  "box" => "0"
  "realphoto" => "0"
  "photo" => UploadedFile {#325 ▶}
  "image" => array:1 [▶]
]

Is there a way to remove this from the initial $request->all() and have it just for use by the foreach loop, or is that not possible:

"image" => array:1 [▶]
Activity icon

Replied to How To Update Images With Array

yeah, I don't really know how to go about updating with multiple files. dd shows:

array:14 [▼
  "_method" => "PATCH"
  "_token" => "MaP0WnARbUaRqlC4DNILgmW9TyUw9Aqt3fh11ioi"
  "title" => "Quackshot"
  "youtube" => null
  "price" => "15"
  "score" => "9"
  "description" => "Changed photos"
  "category_id" => "2"
  "sold" => "0"
  "manual" => "0"
  "box" => "0"
  "realphoto" => "0"
  "photo" => UploadedFile {#325 ▶}
  "image" => array:1 [▶]
]
Activity icon

Replied to How To Update Images With Array

I changed it to

$input = $request;

And also removed the line altogether but it didn't help

Activity icon

Started a new Conversation How To Update Images With Array

I have a form that allows for the upload of multiple images alongside other inputs and that works fine. However, I cannot update the entries with multiple images as I get the error:

Array to string conversion

Here is the part of the form which handles the upload:

<div class="form-group {{$errors->has('photo') ? 'has-error' : ''}}">
      {!! Form::label('photo', 'Image 1:') !!}
      {!! Form::file('photo', null, ['class'=>'form-control'])!!}
      @if($errors->has('photo'))
        {{$errors->first('photo')}}
      @endif
    </div>
    <div class="form-group {{$errors->has('image') ? 'has-error' : ''}}">
      {!! Form::label('image', 'Image 2:') !!}
      {!! Form::file('image[]', null, ['class'=>'form-control'])!!}
      @if($errors->has('image'))
        {{$errors->first('image')}}
      @endif
    </div>
    <div class="form-group {{$errors->has('image') ? 'has-error' : ''}}">
      {!! Form::label('image', 'Image 3:') !!}
      {!! Form::file('image[]', null, ['class'=>'form-control'])!!}
      @if($errors->has('image'))
        {{$errors->first('image')}}
      @endif
    </div>
    <div class="form-group {{$errors->has('image') ? 'has-error' : ''}}">
      {!! Form::label('image', 'Image 4:') !!}
      {!! Form::file('image[]', null, ['class'=>'form-control'])!!}
      @if($errors->has('image'))
        {{$errors->first('image')}}
      @endif
    </div>

and the method:

public function update(GamesRequest $request, $id)
    {
          $gameSearch = Game::findOrFail($id);
          $photoSearch = Photo::findOrFail($id);
          $input = $request->all();
          if($file = $request->file('photo')){
            $name = $file->getClientOriginalName();
            $file->move('images/games/', $name);
            $input['photo'] = '/images/games/' . $name;
          }
            $input['title'] = $request->title;
            $input['price'] = $request->price;
            $input['score'] = $request->score;
            $input['description'] = $request->description;
            $input['category_id'] = $request->category_id;
            $input['promote'] = 0;
            $input['sold'] = $request->sold;
            $input['manual'] = $request->manual;
            $input['box'] = $request->box;
            $input['realphoto'] = $request->realphoto;
            $input['youtube'] = $request->youtube;
          $gameSearch->update($input);

        // Handle multiple file upload
        if($images = $request->file('image'))
        {
            foreach($images as $key => $image) {
                $name = $image->getClientOriginalName();
                if ($image->move('images/games/', $name)) {
                    // store image to database.
                    $input = $request->all();
                    $input->game_id = $input->id;
                    $input->image = '/images/games/' . $name;
                    $photoSearch->update($input);
                }
            }
        }
        return redirect('admin/games');
            }

When I upload just one photo that doesn't use the image array, it works fine

Oct
15
4 weeks ago
Activity icon

Replied to Multi Image Upload Not Working

Ok that got it but now its saying the photo Id column is getting no value from this:

$image->photo_id = $request->id;

How would I get the Id that the request generates for the games table and put it in the photo_id field for each photo in the loop?

Activity icon

Started a new Conversation Multi Image Upload Not Working

I'm trying to get a form working with multi-image uploads too. When I try the upload, all I get is this error and I can't see where it's gone wrong:

Invalid argument supplied for foreach()

I don't know if I've done the form correctly for the upload part but here is the section for the image upload:

 {!! Form::open(['method' =>'POST', 'action'=> '[email protected]', 'files'=>true, 'enctype'=>'multipart/form-data']) !!}

<div class="form-group {{$errors->has('image') ? 'has-error' : ''}}">
  {!! Form::label('image', 'Image 1:') !!}
  {!! Form::file('image', null, ['class'=>'form-control'])!!}
  @if($errors->has('image'))
    {{$errors->first('image')}}
  @endif
</div>
<div class="form-group {{$errors->has('image') ? 'has-error' : ''}}">
    {!! Form::label('image', 'Image 2:') !!}
    {!! Form::file('image', null, ['class'=>'form-control'])!!}
    @if($errors->has('image'))
        {{$errors->first('image')}}
    @endif
</div>
<div class="form-group {{$errors->has('image') ? 'has-error' : ''}}">
    {!! Form::label('image', 'Image 3:') !!}
    {!! Form::file('image', null, ['class'=>'form-control'])!!}
    @if($errors->has('image'))
        {{$errors->first('image')}}
    @endif
</div>
<div class="form-group {{$errors->has('image') ? 'has-error' : ''}}">
    {!! Form::label('image', 'Image 4:') !!}
    {!! Form::file('image', null, ['class'=>'form-control'])!!}
    @if($errors->has('image'))
        {{$errors->first('image')}}
    @endif
</div>
<div class="form-group">
        {!! Form::submit('Add Game', ['class'=>'btn btn-primary']) !!}
      </div>
      {!! Form::close() !!}

And here is the method from the controller:

    public function store(GamesRequest $request)
    {
          $games = new Game();
          $games->image = 'blank';
          $games->title = $request->title;
          $games->score = $request->score;
          $games->description = $request->description;
          $games->price = $request->price;
          $games->category_id = $request->category_id;
          $games->promote = 0;
          $games->manual = $request->manual;
          $games->box = $request->box;
          $games->realphoto = $request->realphoto;
          $games->youtube = $request->youtube;
          $games->sold = 0;
          $games->save();

        // Handle multiple file upload
        $images = $request->file('image');
        foreach($images as $key => $image) {
            $name = $images->getClientOriginalName();
            if ($images->move('images/games/', $name)) {
                // store image to database.
                $image = new Photo();
                $image->photo_id = $request->id;
                $image->image = '/images/games/' . $name;
                $image->save();
            }
        }
          return redirect()->route('admin.games.index');
    }
Oct
14
4 weeks ago
Activity icon

Replied to Object Out Of Class In Dropdown Menu In Html Collective

Ah there it is, it's working now. Thank you ever so much!

Activity icon

Replied to Object Out Of Class In Dropdown Menu In Html Collective

Yep, just using the code as you suggested

Activity icon

Replied to Object Out Of Class In Dropdown Menu In Html Collective

I get

array:35 [▼
  "" => "Choose Category"
  1 => "Mastersystem"
  2 => "Megadrive"
  3 => "Saturn"
  4 => "32X"
  5 => "Dreamcast"
  6 => "Gamegear"
  7 => "MegaCD"
  8 => "NES"
  9 => "SNES"
  10 => "N64"
  12 => "Gamecube"
  13 => "Gameboy"
  14 => "DS"
  15 => "Switch"
  16 => "Handhelds"

ETC

with the dd

Activity icon

Replied to Object Out Of Class In Dropdown Menu In Html Collective

yes I get a list comprising of name 1 and name 2

Activity icon

Replied to Object Out Of Class In Dropdown Menu In Html Collective

Ah with this the error goes, which is good, but now the dropdown menu just has the array in it rather than the item names

Activity icon

Replied to Object Out Of Class In Dropdown Menu In Html Collective

Ah but even with the ->all() added back and the column the order you suggested, it still has the same error

Activity icon

Replied to Object Out Of Class In Dropdown Menu In Html Collective

yes with the below code:

<div class="form-group {{$errors->has('category_id') ? 'has-error' : ''}}">
  {!! Form::label('category_id', 'Category:') !!}
  {!! Form::select('category_id', [''=>'Choose Category'] + $categories, null, ['class'=>'form-control'])!!}
  @if($errors->has('category_id'))
    {{$errors->first('category_id')}}
  @endif
</div>

I commented out this line:

 {!! Form::select('category_id', [''=>'Choose Category'] + $categories, null, ['class'=>'form-control'])!!}

and the error goes away

Activity icon

Replied to Object Out Of Class In Dropdown Menu In Html Collective

Sadly, that did not help. Still get the same error

Activity icon

Started a new Conversation Object Out Of Class In Dropdown Menu In Html Collective

I'm using this to produce a drop down menu for a form:

<div class="form-group {{$errors->has('category_id') ? 'has-error' : ''}}">
  {!! Form::label('category_id', 'Category:') !!}
  {!! Form::select('category_id', [''=>'Choose Category'] + $categories, null, ['class'=>'form-control'])!!}
  @if($errors->has('category_id'))
    {{$errors->first('category_id')}}
  @endif
</div>

However when I pass it this query:

{
        $games = Game::all();
        $categories = Category::pluck('id', 'name')->all();
        return view('admin.games.index', compact('games', 'categories'));
    }

It throws this error and I have no idea why. Was wondering if you could see what went wrong?

Object of class Illuminate\Database\Eloquent\Collection could not be converted to int (View: C:\xampp\htdocs\retro\resources\views\includes\admin\gameForm.blade.php) (View: C:\xampp\htdocs\retro\resources\views\includes\admin\gameForm.blade.php)

Many thanks

Oct
12
1 month ago
Activity icon

Started a new Conversation Syntax Error On Group By

Trying to group by category but only on categories with at least one entry, using the below code:

 $categoryIds = array();
            foreach($gameCount as $game)
            {
                if($game->total > 0 )
                {
                    array_push($categoryIds, $game->category_id );
                }
            }
            $categories = Category::wherein('id', $categoryIds)
                ->groupBy('company_id')
                ->get();

When I run it, I get this error:

SQLSTATE[42000]: Syntax error or access violation: 1055 'sonic.categories.id' isn't in GROUP BY (SQL: select * from `categories` where `id` in (1, 2, 8, 17, 21, 26, 35) group by `company_id`)

Any ideas? I can turn 'strict' => true, to 'strict' => false which will fix it but I don't wish to do this as it breaks other parts of the database searches.

Oct
10
1 month ago
Activity icon

Replied to Order By Not Working

Why is this? Would this not cause confusion with grouping by multiple columns? How would this help the sort order?

Activity icon

Replied to Order By Not Working

Right so how should it be chained please?

Activity icon

Replied to Order By Not Working

The solution you gave produces this error:

SQLSTATE[42000]: Syntax error or access violation: 1055 'sonic.categories.id' isn't in GROUP BY (SQL: select * from `categories` group by `company` order by `company` asc)

The company column is a string column. Should there be another way of sorting strings?

Activity icon

Replied to Order By Not Working

But when I remove the asc part, it doesn't sort by at all. I'm now using

$companies = Category::all()->groupBy('company')->sortBy('company');
Activity icon

Replied to Order By Not Working

$companies = Category::all()->groupBy('company')->SortBy('company', 'asc');

Gives this error:

asort() expects parameter 2 to be integer, string given

Where have I gone wrong here?

Activity icon

Started a new Conversation Order By Not Working

What have I done wrong here? Is it how I've strung the query together? I have the below query:

 $companies = Category::all()->groupBy('company')->OrderBy('company', 'asc');

Which results in the following error:

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

Have I just done it in the wrong order or something?

Oct
07
1 month ago
Activity icon

Replied to Issue Submitting Form

The store method is:

public function store(Request $request)
    {
        $postageset = new PostageSet();
        $postageset->postageSet -> $request->postageSet;
        $postageset->save();
        return redirect()->route('admin.holiday.index');
    }

Tried your solution but got the same error message

Activity icon

Started a new Conversation Issue Submitting Form

I have the below form but when I try to submit it, it just errors. Any ideas on this one please? Form:

<form method="post" action="{{ action('[email protected]') }}" accept-charset="UTF-8">
                <input name="_token" type="hidden" value="{{ csrf_token() }}"/>
                <div class="form-check form-check-inline">
                    <label class="form-check-label">
                        <input type="radio" class="form-check-input" name="optradio">Yes
                    </label>
                </div>
                <div class="form-check form-check-inline">
                    <label class="form-check-label ">
                        <input type="radio" class="form-check-input" name="optradio">No
                    </label>
                </div>
                <button type="submit" class="btn btn-primary">Submit</button>
            </form>

Route:

Route::post('postage-set', ['as'=>'postageset.store','uses'=>'[email protected]']);

Error:

Trying to get property 'POST /postage-set HTTP/1.1 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3 Accept-Encoding: gzip, deflate Accept-Language: en-GB,en;q=0.9,en-US;q=0.8,la;q=0.7 Cache-Control: max-age=0 Connection: keep-alive Content-Length: 59 Content-Type: application/x-www-form-urlencoded Cookie: XSRF-TOKEN=eyJpdiI6ImxodUsycDMrSHhOSUpIdGxkV2tzcUE9PSIsInZhbHVlIjoidnR1T1dHZjYydUhCanRWTWwwRWFPaU9KNkRsNVlXcVpDeGxcL2xhUW8yWlk1OW0yTHlHSEwxOGdrZ1JSSUJCZlkiLCJtYWMiOiI0MTBiZDgzMDUxOTZiNGQ0YWJiZTAxYzM0NmU1NGM1ZTg3M2ZjOTUwNDc4YzdiYTg3ODQ2OTlhZDVhOTAyMTNlIn0%3D; eden_beauty_session=eyJpdiI6IndYWEFnK2dUdUlxSm9uajRnTGgrUkE9PSIsInZhbHVlIjoiRlpGMVRBSkhQcHVaNGhmRDhld00zQVRTZkt4M2dISjZhWFNKRjAzK0FSdXRFK2JBMVB1bjNmMFBIbVo4T0p2cyIsIm1hYyI6IjI1ZWIwNWU3NzE5YThjMWI3NDU2ZGU2Yjg0MDZlY2FlZDg4ZGE2YzM2MGU2ZWFmNDdhOGM4ZGQ5ODQ5YTI4NTYifQ%3D%3D Host: edenbeauty.test Origin: http://edenbeauty.test Referer: http://edenbeauty.test/admin/holiday?optradio=on Upgrade-Insecure-Requests: 1 User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36

Can't see where it's gone wrong

Oct
04
1 month ago
Activity icon

Replied to Confused About Query Not Working

This worked. Many thanks!

Activity icon

Replied to Confused About Query Not Working

I already have

 $categories = Categories::all();

Being passed in here

  'categories' => $categories,
Activity icon

Replied to Confused About Query Not Working

Now I get

Trying to get property 'category' of non-object
Activity icon

Started a new Conversation Confused About Query Not Working

I have 2 controllers doing somewhat similar things. I am trying to get the name out of a column based on the ID given to it. Here, I can get the company out of the database and return it in a variable ($title) just fine:

public function show(Company $id){
        $categoryMenu = Categories::all();
        $companies = Company::where('visible', 0)->get();
        $title = $id->company;
        $products = Products::where('company_id', $id->id)->get()->groupBy('category_id');
        $categories = Products::where('company_id', $id->id)->groupBy('category_id')->get();
        return view('allProducts')->with([
            'companies' => $companies,
            'categories' => $categories,
            'products' => $products,
            'title' => $title,
            'categoryMenu' => $categoryMenu,
        ]);
    }

But when I try what seems to be the same thing with this one, $title is just null for some reason:

public function show(Request $id)
    {
        $categoryMenu = Categories::all();
        $companies = Company::where('visible', 0)->get();
        $categories = Categories::all();
        $title = $id->category;
        dd($title);
        $products = Products::where('category_id', $id->id)->get()->groupBy('company_id');
        $mainId=$id->id;
        $allCompanies = Products::whereHas('company', function($q) use($mainId) {
            $q->where('visible',0)->where('category_id', $mainId);
            })->groupBy('company_id')->get();
        return view('allCategories')->with([
            'companies' => $companies,
            'allCompanies' => $allCompanies,
            'categories' => $categories,
            'products' => $products,
            'title' => $title,
            'categoryMenu' => $categoryMenu,
        ]);
    }

I swapped out $id for $category and $company but predicatively this didn't help. I am confused why one works and the other not

Oct
03
1 month ago
Activity icon

Replied to How To Head Up A For Loop

That could work yes but what if I only want to show company names if there's more than one console under that name. For example, "Amiga" only has one console but "Nintendo" will have a sub-list of 8

Activity icon

Started a new Conversation How To Head Up A For Loop

I know this is a very bulky and crap way to go about it but right now on a site I'm doing, I have a menu comprised of looping through the results of many MANY database queries (see below):

$segaCategories = Category::where('company', 'sega')->get();
            $nintCategories = Category::where('company', 'nintendo')->get();
            $psCategories = Category::where('company', 'ps')->get();
            $xboxCategories = Category::where('company', 'xbox')->get();
            $amigaCategories = Category::where('company', 'amiga')->get();
            $atariCategories = Category::where('company', 'atari')->get();
            $bitCategories = Category::where('company', '8-Bit')->get();
            $doCategories = Category::where('company', '3DO')->get();
            $cdiCategories = Category::where('company', 'CDi')->get();
            $neoCategories = Category::where('company', 'Neo-Geo')->get();
            $pcEngineCategories = Category::where('company', 'PCengine')->get();
            $pcCategories = Category::where('company', 'PC')->get();
            $gawCategories = Category::where('company', 'Game And Watch')->get();
            $importCategories = Category::where('company', 'Imports')->get();
            $merchCategories = Category::where('company', 'merch')->get();

The menu is comprised of having some menu items on their own and some under a banner header. For example, Nintendo will be a header and under it will be all the Nintendo consoles but there are other consoles that don't have a common header.

Right now, I have many Foreach loops which use the above queries to show the menu items. Here is a snippit of the code I'm using:

@foreach($neoCategories as $neo)
                <li><a href="{{route('games.show', $neo->id)}}">{{ucfirst($neo->name)}}</a></li>
                @endforeach
                <li>Nintendo</li>
                  <ul>
                    @foreach($nintCategories as $nint)
                    <li><a href="{{route('games.show', $nint->id)}}">{{ucfirst($nint->name)}}</a></li>
                    @endforeach
                  </ul>

My question is - Is there a way to clean this up? I'm thinking of one query to the db but use a groupBy on their respective categories, but then is there a way to use one large foreach loop in the menu but somehow interject headers in the appropriate place?

Oct
02
1 month ago
Activity icon

Replied to Update Session Data On Cart Update

Can this be done? Or have I done it totally the wrong way?

Activity icon

Started a new Conversation Update Session Data On Cart Update

I have a shopping cart with the ability to add in a discount voucher code. I have the code working and it will add the discount just fine, but it only calculates on the cart the first time. For example, if I have a cart with 2 items which totals £10, I can remove 10% and make it £9. However, if I update one of the items to be 2 of the same item, the number will update, but the discount still removes £1 and not 10% of the new total price of all items.

Here's the model for Coupon:

class Coupon extends Model
{
    public static function findByCode($code)
    {
        return self::where('code', $code)->get();
    }

    public function discount($total)
    {
        if($this->type == 'fixed'){
            return $this->value;
        } elseif($this->type == 'percent'){
            return($this->percent_off / 100.0) * $total;
        } else{
            return 0;
        }
    }
}

I suspect the issue is because the session I'm storing it in only gets built the once and not when the cart updates. Do you know how I update the session with the new subtotal value when the cart changes?

Store request:

public function store(Request $request)
    {
       $oldCart = Session::get('cart');
       $cart = new Cart($oldCart);
       $totalPrice = $cart->totalPrice;
       $coupon = Coupon::where('code', $request->coupon_code)->first();
       if(!$coupon){
           return redirect()->back()->with('fail_message', 'Coupon Code Not Found');
       }
       session()->put('coupon',[
           'name' => $coupon->code,
           'id' => $coupon->id,
           'discount' => $coupon->discount($totalPrice),
           ]);
        return redirect()->back()->with('success_message', 'Coupon Has Been Applied');
    }

Cart model:

class Cart
{
    public $items = null;
    public $totalQty = 0;
    public $totalPrice = 0;
    public $pp = 3.95;

    public function __construct($oldCart){
      if ($oldCart){
        $this->items = $oldCart->items;
        $this->totalQty = $oldCart->totalQty;
        $this->totalPrice = $oldCart->totalPrice;
      }
    }
    public function contains($id){
      return ($this->items) && array_key_exists($id, $this->items);
    }

    public function add($item, $id){
      $storedItem = ['qty' =>0, 'price' => $item->price, 'item' => $item, 'id' => $id];
      if ($this->items) {
        if (array_key_exists($id, $this->items)) {
          $storedItem = $this->items[$id];
        }
      }else{
        $this->items = array();
      }
      $storedItem['price'] = $item->price;

        $storedItem['qty']++;
        $this->totalQty++;
        $this->totalPrice+=$item->price;
        $this->items[$id] = $storedItem;
    }

    public function removeItem($id){
      $this->totalQty -= $this->items[$id]['qty'];
      $this->totalPrice -= $this->items[$id]['price'];
      unset($this->items[$id]);
    }

    public function update($item, $id, $qty){
        $storedItem = ['qty' =>0, 'price' => $item->price, 'item' => $item, 'id' => $id];
        if ($this->items) {
            if (array_key_exists($id, $this->items)) {
                $storedItem = $this->items[$id];
            }
        }else{
            $this->items = array();
        }
        if($qty <= 0){
            $this->removeItem($id);
            return;
        }
        $this->totalQty -= $storedItem['qty'];
        $this->totalPrice -= $item->price * $storedItem['qty'];

        $storedItem['qty']=$qty;
        $this->totalQty+= $storedItem['qty'];
        $this->totalPrice+=$item->price * $storedItem['qty'];
        $this->items[$id] = $storedItem;
    }
}
Sep
27
1 month ago
Activity icon

Replied to Question About Is_null

Ok yeah this fixed it but I had the wrong field type. Cheers @sti3bas

Activity icon

Replied to Question About Is_null

Just tried but still doesn't show even though the column is 0 for the view in questio

Activity icon

Started a new Conversation Question About Is_null

I don't know if this is bad form, but I have a table with a column that can be null, 0, or 1 (null being if that particular option is not applicable and 0/1 being if it is applicable for the view in question but it returns yes/no)

I wanted to run a nested if statement as below but only show "has manual" if showGames is NOT null (ie only if it is a 1 or a 0) but it is acting like NULL and 0 are the same thing. If I use !empty or !is_null, they seem to do the same, not desired, effect. I don't know if that is just how that works but if it is, what's the workaround, please?

@if(!is_null($showGames->manual))
          Has Instruction Manual:
         @if($showGames->manual == 0)
          <i class="fas fa-times text-danger"></i><br><br>
          @else
          <i class="fas fa-check text-success"></i><br><br>
         @endif
      @endif
Sep
25
1 month ago
Activity icon

Replied to Multiple Table Queries

I copied and pasted but got the same error message

Activity icon

Replied to Multiple Table Queries

That's been suggested already but it didn't work

@mstrauss do you have any other suggestions?

Activity icon

Replied to Multiple Table Queries

Any ideas please?

Activity icon

Replied to Multiple Table Queries

Yeah that still gives the same error

Activity icon

Replied to Multiple Table Queries

With dd($id) I get an object with no attributes etc but when I use dd($id->id); I get the Id passed into it

Activity icon

Replied to Multiple Table Queries

Sorry to sound dumb but I don't know how to do that. Looking at the error, it seems to highlight

})->where('category_id', $id->id)

As the error potentially?