MattB

MattB

Member Since 1 Year Ago

Experience Points
5,410
Total
Experience

4,590 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
2
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 2
5,410 XP
May
06
2 weeks ago
Activity icon

Started a new Conversation Checkbox Query For Pivot Tables

So...I have a confusing issue I can't get my head around... I have 3 tables; news, categories, and categories_news. The pivot table is working as intended, but I have an edit page for news articles which I have a series of check-boxes pulled from the categories table. How can I enable the check-boxes to be checked if the article has those categories? (I hope that made sense).

form from blade:

<div class="col-6">
            <label for="categories">
              <strong>Choose one or more categories:</strong>
            </label>
            <div class="form-group {{$errors->has('category_id') ? 'has-error' : ''}}" id="categories">   
              @foreach($categories as $category) 
              {!! Form::label('category_id[]', $category->name) !!}
              {!! Form::checkbox('category_id[]', $category->id) !!}  
              @endforeach                          
             
              @if($errors->has('category_id'))
                {{$errors->first('category_id')}}
              @endif
            </div>

edit controller:

$storySearch = News::findOrFail($id);
        $categories = categories::all();
        $newsFlashes = Newsflashes::pluck('date', 'id')->all();       
        return view('admin.stories.edit', compact('storySearch', 'categories', 'newsFlashes'));

category modal:

public function news() {
        return $this->belongsToMany(News::class);
    }

News modal:

public function categories() 
    {
        return $this->belongsToMany(categories::class);
    }

Would really appreciate your help on this one please

May
05
2 weeks ago
Activity icon

Replied to DateTime::__construct(): Failed To Parse Time String (02-2020) At Position 0 (0): Unexpected Character

Sadly no. I'm storing the date as a string in the db, not a date format. Is that the issue here? I'm converting it with

protected $dates = ['date'];

Have I done something wrong there?

Activity icon

Replied to DateTime::__construct(): Failed To Parse Time String (02-2020) At Position 0 (0): Unexpected Character

Sorry, no joy. Seems like the problem might be in the model with this possibly?:

protected $dates = ['date'];
Activity icon

Started a new Conversation DateTime::__construct(): Failed To Parse Time String (02-2020) At Position 0 (0): Unexpected Character

I'm storing just a month and year in my db which stores it as a string such as this for example:

02-2020

I'm trying to turn it into a month and date using carbon so hopefully it looks like this:

February 2020

I'm using this line of code to do it:

{{ $newsflash->date->createFromFormat('MM YYYY') }}

But get error

DateTime::__construct(): Failed to parse time string (02-2020) at position 0 (0): Unexpected character

I'm not sure what's happening, or what the character is I'm messing up with. Any help would be massively appreciated. I do have the following in my model which allows it to be manipulated:

protected $dates = ['date'];
May
04
3 weeks ago
Activity icon

Replied to Datepicker Not Accepting Config Options In Laravel

because ones the js file and the other is a css file. Should I just include one, or both?

Activity icon

Replied to Datepicker Not Accepting Config Options In Laravel

I have it in this order:

<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.7.1/css/bootstrap-datepicker.min.css" rel="stylesheet"/>
        <script src="http://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.3.0/js/bootstrap-datepicker.js"></script>
        <script src="{{ asset('js/app.js') }}" defer></script>
Activity icon

Replied to Datepicker Not Accepting Config Options In Laravel

all I get is this error:

Uncaught TypeError: $(...).datepicker is not a function
    at Object../resources/js/app.js (app.js:37331)
    at __webpack_require__ (app.js:20)
    at Object.0 (app.js:37414)
    at __webpack_require__ (app.js:20)
    at app.js:84
    at app.js:87
Activity icon

Replied to Datepicker Not Accepting Config Options In Laravel

Now the date picker doesn't appear at all

Activity icon

Replied to Datepicker Not Accepting Config Options In Laravel

No joy, still the same sadly

Activity icon

Started a new Conversation Datepicker Not Accepting Config Options In Laravel

So, I have the datepicker references by cdn in the header of my blade thusly:

<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.7.1/css/bootstrap-datepicker.min.css" rel="stylesheet"/>
    <script src="http://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.3.0/js/bootstrap-datepicker.js"></script>

and in my app.js file, I have

$('.datepicker').datepicker({
  format: "mm-yyyy",
  startView: "month", 
  minViewMode: "months",
  autoclose: true  
  });

but when I use the following, it doesn't autoclose and it doesn't show just the month and year as it should. What have I potentially done wrong?

<div class="input-group date" data-provide="datepicker" id="datepicker">
                <input type="text" class="form-control">
                <div class="input-group-addon">
                    <span class="glyphicon glyphicon-th"></span>
                </div>
              </div>
Apr
30
3 weeks ago
Activity icon

Replied to Cannot Send To Store Method From Controller

OH you're right. Thank you, I was blind to that :/

Activity icon

Replied to Cannot Send To Store Method From Controller

As plain html it looks like this:

<form method="POST" action="http://URL.test/admin/newsflashes" accept-charset="UTF-8"><input name="_token" type="hidden" value="key goes here"> 
              <div class="form-group ">
                <label for="date">News Flash Date:</label>
                <input class="form-control" name="date" type="text" id="date">
                              </div>
              <br>
              <div class="form-group">
                <input class="btn btn-primary" type="submit" value="Add News Flash">
              </div>
              </form>

But I find it odd it works outside the modal

Activity icon

Started a new Conversation Cannot Send To Store Method From Controller

I have a form inside a modal which isn't talking to the store method of the controller it's sent to. When I move the form outside of the modal to the page that calls the modal, it works fine and I can post to the store method. Can't see what the issue is here. It doesn't matter if I use a custom request or the basic one for validation:

Form Modal:

<div class="modal-body">
        <form>
          <div class="row">
            <div class="col-12">
              {!! Form::open(['method' =>'POST', 'action'=> '[email protected]']) !!} 
              <div class="form-group {{$errors->has('date') ? 'has-error' : ''}}">
                {!! Form::label('date', 'News Flash Date:') !!}
                {!! Form::text('date', null, ['class'=>'form-control'])!!}
                @if($errors->has('date'))
                  {{$errors->first('date')}}
                @endif
              </div>
              <br>
              <div class="form-group">
                {!! Form::submit('Add News Flash', ['class'=>'btn btn-primary']) !!}
              </div>
              {!! Form::close() !!}
            </div>            
          </div>         
        </form>
      </div>

Store Method:

public function store(NewsFlashRequest $request)
    {
        dd($request);
        $newsFlash = new Newsflashes();          
          $newsFlash->date = $request->date;
          $newsFlash->published = 0;          
          $newsFlash->number_of_stories = 0;          
          $newsFlash->save();
          return redirect()->route('admin.newsflash.index');
    }

Route:

Route::resource('/admin/newsflashes', 'AdminNewsFlashController', [
  'names'=>[
  'index'=>'admin.newsflashes.index',
  'create'=>'admin.newsflashes.create',
  'store'=>'admin.newsflashes.store',
  'edit'=>'admin.newsflashes.edit',
  'show'=>'admin.newsflashes.show',
  'destroy'=>'admin.newsflashes.destroy',
  ]]);

From the route list:

 POST      | admin/newsflashes                  | admin.newsflashes.store       | App\Http\Controllers\[email protected]                    | web
Apr
14
1 month ago
Activity icon

Replied to How Do I Pass 2 Arguments To A Getter In Vuex?

Anyone please know what I'm doing wrong?

Activity icon

Replied to How Do I Pass 2 Arguments To A Getter In Vuex?

With this I get the error:

ReferenceError: color1 is not defined
Apr
09
1 month ago
Activity icon

Started a new Conversation How Do I Pass 2 Arguments To A Getter In Vuex?

So, not sure if this is the correct way of going about this but I am trying to create a getter which returns a gradient based off of 2 colors passed to it via a function. So far I have:

Function being called

  <v-card-text
                          style="height: 120px"
                          :style="{
                              'background-image': backgroundImage(
                                  card.color1,
                                  card.color2,
                              ),
                          }"
                          flat
                                ></v-card-text>

computed:

backgroundImage() {
            return this.backgroundImage(color1, color2)
        },

getter:

getters: {
        backgroundImage: () => (color1, color2) =>{
            let bgImage =
                'linear-gradient(to top right, ' + color1 + ',' + color2 + ')';
            return bgImage;
        }
        
    }

But when I run it now, I get this error

Error in render: "RangeError: Maximum call stack size exceeded"

Not sure what I did wrong or if this is the correct way to handle this sort of function in Vuex?

Apr
08
1 month ago
Activity icon

Replied to How Vuex Works With Axios

So..sorry how would that look in the code I have so far?

Activity icon

Started a new Conversation How Vuex Works With Axios

Trying to get my head around VueX but struggling to get Axios to work with it. I have the following in my store.js file:

state: {
        cards: [],
        currentPage: 1,
        lastPage: 2,
    },
    actions: {
        loadGradients(pageNumber) {
            if (axios == null) {
                return;
            }
            axios
                .get('/api/gradients?page=' + pageNumber +'&sort=' + 'created_at')
                .then(res => {
                    if (res.status === 200) {
                        state.cards = res.data.gradients.data;
                        state.lastPage = res.data.gradients.last_page;
                        state.currentPage = res.data.gradients.current_page;
                    }
                })
                .catch(err => {
                    console.log(err);
                });
        },
    }

I'm calling it through the following function in my main app.js file:

created() {
        this.loadGradients(1);
    },
methods: {
loadGradients:function(pageNumber) {
            this.$store.dispatch('loadGradients') ;
        }
}

But when I run the page, the array in the store.js file isn't being updated it seems, even though the data is being returned correctly from the database. Not sure what I did wrong? If I have to use a combination of actions and mutation, how would I go about that please?

Apr
02
1 month ago
Activity icon

Started a new Conversation Cols Not Working As Expected In Vue

So I'm running Vuejs with Vuetify and with the below code, when there's more than 2 rows worth of data returned to the view it will show them sized as they should be. However when there's an incomplete row's worth of data, each col is shrunk down to be smaller than expected. I can't see why this is happening:

<v-row align="center" justify="center">
            <v-col cols md="11" class="pt-5">
                <v-card class="cardColor d-inline-block mx-auto">
                    <v-card-title class="text-right py-0">
                        <v-row>
                            <v-col cols="5" class="pb-0">
                                <v-select
                                    v-model="sortSelection"
                                    :items="sortBy"
                                    label="Sort By"
                                    class="py-0"
                                    @change="changeOrder"
                                ></v-select>
                            </v-col>
                        </v-row>
                    </v-card-title>
                    <v-card-text>
                        <v-row>
                            <v-card
                                v-for="card in orderedCards"
                                :key="card.id"
                                class="col-3 col-md-3 col-lg-3 pa-0 card"
                                flat
                            >
                                <v-card-text
                                    style="height: 120px"
                                    :style="{
                                        'background-image': backgroundImage(
                                            card.color1,
                                            card.color2,
                                        ),
                                    }"
                                    flat
                                ></v-card-text>
                                <v-row>
                                    <v-col cols="8">
                                        <div class="px-2">
                                            <span>
                                                {{ card.name }}
                                            </span>
                                            <br />
                                            <span>
                                                {{ card.color1 }} &#8594;
                                                {{ card.color2 }}
                                            </span>
                                        </div>
                                    </v-col>
                                    <!-- edit and delete cards -->
                                    <v-col cols="4">
                                        <div>
                                            <v-icon
                                                small
                                                class="mr-2"
                                                @click="showEditDialogue(card)"
                                            >
                                                mdi-square-edit-outline
                                            </v-icon>
                                            <v-icon
                                                small
                                                @click="deleteItem(card)"
                                            >
                                                mdi-delete
                                            </v-icon>
                                        </div>
                                    </v-col>
                                    <!-- *** -->
                                </v-row>
                            </v-card>
                        </v-row>
                        <v-row align="center" justify="center">
                            <v-btn text @click="loadGradients(prevPage)"
                                >Prev</v-btn
                            >
                            Page {{ currentPage }} of {{ lastPage }}
                            <v-btn text @click="loadGradients(nextPage)"
                                >Next</v-btn
                            >
                        </v-row>
                    </v-card-text>
                </v-card>
                <!-- add new entry button -->
                <div class="text-center py-3">
                    <v-btn large color="primary" @click.stop="showNewDialogue()"
                        >Add New Gradient</v-btn
                    >
                </div>
                <!-- new entry modal -->
                <v-dialog v-model="dialog" max-width="700">
                    <v-card>
                        <v-form>
                            <v-container>
                                <v-row>
                                    <v-col cols="12" md="4">
                                        <v-text-field
                                            v-model="card.name"
                                            label="Name of Gradient"
                                        ></v-text-field>
                                    </v-col>

                                    <v-col cols="12" md="4">
                                        <v-select
                                            v-model="card.color1"
                                            :items="colors"
                                            label="First Color"
                                        ></v-select>
                                    </v-col>

                                    <v-col cols="12" md="4">
                                        <v-select
                                            v-model="card.color2"
                                            :items="colors"
                                            label="Second Color"
                                        ></v-select>
                                    </v-col>
                                </v-row>
                            </v-container>
                            <v-card-actions>
                                <v-spacer></v-spacer>
                                <v-btn color="blue darken-1" text @click="close"
                                    >Cancel</v-btn
                                >
                                <v-btn
                                    color="blue darken-1"
                                    text
                                    @click="saveToServer"
                                    >Save</v-btn
                                >
                            </v-card-actions>
                        </v-form>
                    </v-card>
                </v-dialog>
            </v-col>
        </v-row>
Mar
31
1 month ago
Activity icon

Started a new Conversation How To Include A Color Picker In Vue

I am trying to make a form with 2 inputs for colours. Hoping to use a built in vuetify color picker but when I use the below code, the dialogue just opens a blank grey screen. Not sure what I have done wrong:

<v-dialog v-model="dialog" max-width="700">
            <template v-slot:append>
                <v-menu
                    v-model="menu"
                    top
                    nudge-bottom="105"
                    nudge-left="16"
                    :close-on-content-click="false"
                >
                    <template v-slot:activator="{on}">
                        <div :style="swatchStyle" v-on="on" />
                    </template>
                    <v-card>
                        <v-form v-model="valid">
                            <v-container>
                                <v-row>
                                    <v-col cols="12" md="4">
                                        <v-text-field
                                            v-model="gradname"
                                            label="Name of Gradient"
                                        ></v-text-field>
                                    </v-col>
                                    <v-col cols="12" md="4">
                                        <v-text-field
                                            v-model="color1"
                                            label="First Color"
                                        ></v-text-field>
                                        <v-color-picker v-model="color" flat />
                                    </v-col>
                                    <v-col cols="12" md="4">
                                        <v-text-field
                                            v-model="color2"
                                            label="Second Color"
                                        ></v-text-field>
                                    </v-col>
                                </v-row>
                            </v-container>
                        </v-form>
                    </v-card>
                </v-menu>
            </template>
        </v-dialog>

And here's the script with some dummy data:

<script>
export default {
    data() {
        return {
            dialog: false,
            color: '#1976D2FF',
            mask: '!#XXXXXXXX',
            menu: false,
            cards: [
                {name: 'Name of thing', color1: '#ff0000', color2: '#ffff00'},
                {name: 'Name of thing', color1: '#b3b3ff', color2: '#0000e6'},
                {name: 'Name of thing', color1: '#ff0000', color2: '#ffff00'},
                {name: 'Name of thing', color1: '#ff0000', color2: '#ffff00'},
                {name: 'Name of thing', color1: '#0d0d0d', color2: '#999999'},
                {name: 'Name of thing', color1: '#ff0000', color2: '#ffff00'},
                {name: 'Name of thing', color1: '#ff0000', color2: '#ffff00'},
                {name: 'Name of thing', color1: 'green', color2: 'red'},
            ],
        };
    },
    computed: {
        swatchStyle() {
            const {color, menu} = this;
            return {
                backgroundColor: color,
                cursor: 'pointer',
                height: '30px',
                width: '30px',
                borderRadius: menu ? '50%' : '4px',
                transition: 'border-radius 200ms ease-in-out',
            };
        },
        backgroundImage: () => (color1, color2) => {
            let bgImage =
                'linear-gradient(to top right, ' + color1 + ',' + color2 + ')';
            return bgImage;
        },
    },
};
</script>
Mar
25
2 months ago
Activity icon

Replied to Protecting API Routes With Middleware

Isn't that for when data needs to be accessed by a 3rd party app that isn't Laravel? Is there not a simpler way to protect the API when it's just kept in the laravel app?

Activity icon

Started a new Conversation Protecting API Routes With Middleware

Hi guys, so I'm trying to learn API routing on Laravel and so far it all works, but I would like to know how to protect the API from view. So far if anyone was to put in the API link into the address bar, you could see the entire JSON object. Is there a way to protect this using middleware like you can normal links? I have this as my links so far:

Route::apiResources([
    'user' => 'API\UsersController',
    'faq' => 'API\QuestionController',
    'dump' => 'API\DumpController',
    'gallery' => 'API\GalleryController',
    'artpack' => 'API\ArtPackController',
    'boughtArtPack' => 'API\BoughtArtPackController'
]);

Tried protecting it with an established auth middleware I have working for the admin back end routes but now it blocks the API whether you're logged in or not. I have it set up like this:

Route::group(['middleware' => 'IsAdmin'], function () {
  Route::apiResources([
    'user' => 'API\UsersController',
    'faq' => 'API\QuestionController',
    'dump' => 'API\DumpController',
    'gallery' => 'API\GalleryController',
    'artpack' => 'API\ArtPackController',
    'boughtArtPack' => 'API\BoughtArtPackController'
  ]);
});
Mar
18
2 months ago
Activity icon

Replied to Syntax Error With New Laravel Projects

I'm using Xampp with MariaDB instead of mySQL. Are there any better recommendations?

Activity icon

Replied to Syntax Error With New Laravel Projects

Ah! so currently I have this:

$table->string('email')->unique();

What do you recommend changing it to?

Activity icon

Started a new Conversation Syntax Error With New Laravel Projects

I don't know if this is something I'm doing wrong or everyone who creates a new Laravel (version 5 or 6, doesn't seem to matter) project has to fix each time.

Whenever I create a new project and try to run an initial migration, I get this error:

Syntax error or access violation: 1071 Specified key was too long; max key length is 767 bytes")

I can fix it just fine, but seems I have to do it every time. Is there something I should be doing when I create the project? Tried to reinstall Laravel on my PC but it didn't help. Tried creating a project using these commands, but no difference:

laravel new blog

composer create-project --prefer-dist laravel/laravel blog "6.*" (or "5.*")

I have to fix it by adding the following to appServiceProvider:

use Illuminate\Support\Facades\Schema; //NEW: Import Schema

function boot()
{
    Schema::defaultStringLength(191); //NEW: Increase StringLength
}
Mar
16
2 months ago
Activity icon

Replied to One To Many Relation Not Working

The first answer there just has the result which stops after company and doesn't have the rest of the data, and the 2nd answer just tacks on the company data onto the result of the find query

Activity icon

Started a new Conversation One To Many Relation Not Working

I have a table of games, games companies and consoles. I am trying to output games to JSON using the API in Laravel and connecting the tables in a way that given the company ID and console ID in the games table, I can cross-reference the company/console name from the other table to fill in the name.

Game Model:

class Game extends Model
{
    public function company()
    {
        return $this->belongsTo('App\Company', 'company_id');
    }

    public function console()
    {
        return $this->hasOne('App\Console', 'console_id');
    }
}

company Model (console is similar):

class Company extends Model
{
    public function game()
    {
        return $this->hasMany('App\Game');
    }
}

I have this in my controller so far:

 public function show($id)
    {
        $showGame= Game::where('id', $id)->first();        
        return response()->json([
            'showGame' => $showGame
        ]);
    }

This will output this as JSON but I wanted company and console to have the names rather than numbers:

{
    "showGame": {
        "id": 2,
        "company_id": 2,
        "console_id": 1,
        "title": "Sonic",
        "price": £10,
	"inStock": "yes"          
    }
}

I tried the following which gives the company name just fine but then won't display the rest of the data (It just stops at company_id):

 public function show($id)
    {
        $showGame= Game::find($id)->company->where('id', $id)->first();        
        return response()->json([
            'showGame' => $showGame
        ]);
    }
Feb
12
3 months ago
Activity icon

Replied to V-hover Not Working As Expected On Image

Do you mean like this?

 <v-col cols="6" md="3" :class="c.class">     
          <v-expand-transition>
<!-- ... -->
</v-expand-transition>
</v-col>
Activity icon

Replied to V-hover Not Working As Expected On Image

Ok I have the screenshot here: https://www.dropbox.com/s/9nnbwwkyi31dnq9/Capture.JPG?dl=0

So what should happen is a hover event which triggers an overlay to come up from the bottom of each green surrounded column to cover it totally but what's happening is that only each logo is being covered instead and doesn't cover the total col/div

Activity icon

Replied to V-hover Not Working As Expected On Image

Any other ideas please?

Activity icon

Replied to V-hover Not Working As Expected On Image

Hmm that's still doing the same hover effect I'm afraid

Activity icon

Started a new Conversation V-hover Not Working As Expected On Image

So, I have set up an array of divs with images in them, however when I apply the v-hover tag to them, the hover effect only triggers when you hover over the image, and not the surrounding v-col. Also, it only has the overlay to cover just the image and not the v-col. I tried moving the v-hover tag to encompass the v-col but it complained about too many child elements:

<template>
  <v-row class="mx-0" align="center" justify="center">
    <v-col cols="6" md="3" v-for="c in catImages" :key="c.id" :class="c.class" >
      <v-hover v-slot:default="{ hover }">
        <v-img :src="c.img" max-height="100%">
          {{ catImages.company }}
          <v-expand-transition>
            <div
              v-if="hover"
              class="transition-fast-in-fast-out black darken-2 v-card--reveal white--text text-center"
              style="height: 100%;"
            >
              <v-list dense flat color="black">
                <v-list-item-group class="py-0">
                  <v-list-item
                    v-for="(link, index) in c.links"
                    :key="index"
                    :href="link.url + '/' + index"
                    target="_blank"
                    
                  >
                    <v-list-item-content>
                      <v-list-item-title class="white--text">{{ link.links }}</v-list-item-title>
                    </v-list-item-content>
                  </v-list-item>
                </v-list-item-group>
              </v-list>
            </div>
          </v-expand-transition>
        </v-img>
      </v-hover>
    </v-col>
  </v-row>
</template>
Feb
05
3 months ago
Activity icon

Started a new Conversation Vuejs Array Not Populating From Axios Request

I have an Axios request pulling a JSON object from my DB as it should, and it shows ok in the console.log window as an array as expected but when I go to query the array to loop through it to show the data, it just shows blank data. Not sure what I did wrong, maybe it's a lifecycle hook problem with the data not loading quickly enough? If so, how do I get around that?

<template>
    <v-col cols="8">
        <h1 class="display-2 my-4">
            Page Heading
            <ul>
                <li v-for="p in posts" :key="p.id">
                    {{ p.title }}
                </li>
            </ul>
            <p class="headline">Secondary Text</p>
        </h1>
        <div v-for="p in posts" :key="p.id">
            <v-card class="mx-auto mb-4" max-width="750">
                <v-img
                    class="white--text align-end"
                    height="200px"
                    src="https://cdn.vuetifyjs.com/images/cards/docks.jpg"
                >
                    <v-card-title>{{ p.title }}</v-card-title>
                </v-img>

                <v-card-text class="text--primary">
                    <div>Written By: {{ p.posted_by }}</div>

                    <div>{{ p.post }}</div>
                </v-card-text>
                <v-card-actions>
                    <v-btn color="orange" text>
                        Share
                    </v-btn>
                    <v-btn color="orange" text>
                        Explore
                    </v-btn>
                </v-card-actions>
            </v-card>
        </div>
    </v-col>
</template>

<script>
export default {
    data: () => ({
        posts: [],
    }),
    created() {
        this.posts = [];
        axios.get('/api/posts').then(res => {
                this.posts = res.data;
                console.log(this.posts)
            })
            .catch(err => {
                console.log(err);
            });
    },
};
</script>
<style lang="scss" scoped></style>

For reference, this is the data I'm passing into it: https://jsoneditoronline.org/?id=2ab8a589187f4b50918e51e7ad4c02eb

Dec
06
5 months ago
Activity icon

Replied to How To Return Update Result As Json Object

Ok yeah it seems it's not being updated. I can see the form data is passing over all the relevant info from the front end, so is something wrong in the code? Is it failing because maybe it's not picking up there being an image do you think?

Activity icon

Started a new Conversation How To Return Update Result As Json Object

I have the following which is just an update to a db that takes in a Json object from vue. I cannot figure out how to return the result as a json object back to vue. What have I done wrong? As it stands, I get no response showing when I check in the developer tools of Chrome:

public function update(Request $request, $id)
    {
        $imageSearch = Gallery::findOrFail($id);
        $file_image = $request->file('imageFile');
        $file_thumbnail = $request->file('thumbnailFile');
        $input = $request->all();
        if($file_image && $file_thumbnail){
            $fileName = $file_image->getClientOriginalName();
            $thumbName = $file_thumbnail->getClientOriginalName();
            $path_images = 'images';
            $path_thumbnail = 'thumbnails';
            if($file_image->move($path_images, $fileName) && $file_thumbnail->move($path_thumbnail, $thumbName)){
                $input['image'] = '/' . $fileName;
                $input['thumbnail'] = '/' . $thumbName;
                $input['name'] = $request->name;
                $input['species_id'] = $request->species;
                $input['tag'] = $request->tag;
                $input['patreon'] = $request->patreon;
                $update = $imageSearch->update($input);
                return response()->json([
                    'update' => $update,
                    'message' => 'Image has been Updated'
                ]);
            };
        };

    }
Dec
04
5 months ago
Activity icon

Replied to 404 Error When Uploading File With Axios. Please Help

I know it works because I can see it displaying images I already had in the database. Can I not append it as an object then? I ask as I need to grab the image to move it to a folder and the name too. Unless I'm going about it the wrong way? How is it done with Vue?

Activity icon

Replied to 404 Error When Uploading File With Axios. Please Help

Yeah, the writing to the db would come after once I can write to the controller. I have this right now which is displaying the images using props and it seems to work but is this what's throwing off the code?

<template #item.image="{item}">
            <img width="100" :src="('../../../thumbnails'+item.image)">
 </template>
Activity icon

Replied to 404 Error When Uploading File With Axios. Please Help

So the form is there to upload an image alongside information about the image, such as title etc. It has some text inputs and an image input all with the intent to pass it across to the database via the api

Activity icon

Replied to 404 Error When Uploading File With Axios. Please Help

Sorry to be dumb here, just getting into Vuejs properly, but if I want to pass the whole form over including the image, how would I do that?

Activity icon

Replied to 404 Error When Uploading File With Axios. Please Help

No doesn't that grab just the image? I need all the form submitting. I get this error when I try adding the .image part app.js:43380 [Vue warn]: Invalid prop: type check failed for prop "item". Expected Object, got File

Activity icon

Started a new Conversation 404 Error When Uploading File With Axios. Please Help

I have a form with input for 2 images, one which goes to an images folder and one which goes to thumbnails. When I hit upload, I get GET http://danza.test/thumbnails[object%20File] 404 (Not Found). If I output the request object, all looks ok. I'm stuck.

Upload method:

let $updatedGallery = this;
                    let $index = this.images.push(this.editedItem)-1;
                    axios.post('/api/gallery', this.editedItem).then((response) => {
                        $updatedGallery.editedItem.id = response.data.id;
                        Object.assign($updatedGallery.images[$index], $updatedGallery.editedItem);
                    })
                        .catch(function (error) {
                            console.log(error);
                        });

Object:

editedItem: {
                name: '',
                image: null,
                thumbnail: null,
                species: '',
                tag: '',
                patreon: '',
                action: '',
            },
            defaultItem: {
                name: '',
                image: null,
                thumbnail: null,
                species: '',
                tag: '',
                patreon: '',
                action: '',
            },

Form:

<v-row>
                                    <v-col cols="12" sm="6" md="6">
                                        <v-file-input v-model="editedItem.image" label="Picture"></v-file-input>
                                    </v-col>
                                    <v-col cols="12" sm="6" md="6">
                                        <v-file-input v-model="editedItem.thumbnail" label="Thumbnail"></v-file-input>
                                    </v-col>
Dec
03
5 months ago
Activity icon

Started a new Conversation Vue Image Upload Issue

I'm using vuetifiy's file upload input to handle file uploads. My form is this:

<v-card-text>
                            <v-container>
                                <v-row>
                                    <v-col cols="12" sm="6" md="6">
                                        <v-text-field label="Image Title" v-model="editedItem.name" single-line></v-text-field>
                                    </v-col>
                                    <v-col cols="12" sm="6" md="6">
                                        <v-select :items="species" v-model="editedItem.species" label="Species"></v-select>
                                    </v-col>
                                </v-row>
                                <v-row>
                                    <v-col cols="12" sm="6" md="6">
                                        <v-file-input v-model="editedItem.image" label="Picture"></v-file-input>
                                    </v-col>
                                    <v-col cols="12" sm="6" md="6">
                                        <v-file-input v-model="editedItem.thumbnail" label="Thumbnail"></v-file-input>
                                    </v-col>
                                </v-row>                              
                            </v-container>
                        </v-card-text>

Every field except the 2 file upload links works fine. In the console, I get errors such as this:

TypeError: Cannot read property 'files' of undefined

and others saying the file is undefined. Have I done something wrong with the v-model part? The edited item is as such:

 editedItem: {
                name: '',
                image: '',
                thumbnail: '',
                species: '',                
                action: '',
            },
Dec
02
5 months ago
Activity icon

Replied to Issue Editing Items In Vue Table

Also forgot to add, when I use the above code to enter a new item, in the error console I get this error just after it outputs 'Before' (put there by the above code in the component):

TypeError: Cannot set property 'id' of undefined
    at VM8713 app.js:2159
Activity icon

Started a new Conversation Issue Editing Items In Vue Table

I have a table with the ability to add new items and edit existing ones (with the edit button being next to each entry). I have an issue with it whereby if you were to add a new item, NOT refresh the page, but then go to edit the item, it will edit it on Vue but not pass the edit back to the database. When you go to edit an item, the PUT URL returns a 404 error. If however, you refresh the page after adding an item, you can edit it perfectly fine. Any ideas what I've done wrong, or maybe forgotten to add?

Component:

<template>
    <v-data-table
        :headers="headers"
        :items="questions"
        sort-by="question"
        class="elevation-1"
    >
        <template v-slot:top>
            <v-toolbar flat color="white">
                <v-toolbar-title>FAQs</v-toolbar-title>
                <v-spacer></v-spacer>
                <v-dialog v-model="dialog" max-width="700px">
                    <template v-slot:activator="{ on }">
                        <v-btn color="primary" dark class="mb-2" v-on="on">New Item</v-btn>
                    </template>
                    <v-card>
                        <v-card-title>
                            <span class="headline">{{ formTitle }}</span>
                        </v-card-title>

                        <v-card-text>
                            <v-container>
                                <v-row>
                                    <v-col cols="12" sm="6" md="6">
                                        <v-textarea v-model="editedItem.question" label="Question"></v-textarea>
                                    </v-col>
                                    <v-col cols="12" sm="6" md="6">
                                        <v-textarea v-model="editedItem.answer" label="Answer"></v-textarea>
                                    </v-col>
                                </v-row>
                            </v-container>
                        </v-card-text>

                        <v-card-actions>
                            <v-spacer></v-spacer>
                            <v-btn color="blue darken-1" text @click="close">Cancel</v-btn>
                            <v-btn color="blue darken-1" text @click="saveToServer">Save</v-btn>
                        </v-card-actions>
                    </v-card>
                </v-dialog>
            </v-toolbar>
        </template>
        <template v-slot:item.action="{ item }">
            <v-icon
                small
                class="mr-2"
                @click="editItem(item)"
            >
                mdi-square-edit-outline
            </v-icon>
            <v-icon
                small
                @click="deleteItem(item)"
            >
                mdi-delete
            </v-icon>
        </template>
        <template v-slot:no-data>
            <v-btn color="primary" @click="initialize">Reset</v-btn>
        </template>
    </v-data-table>
</template>

<script>
    export default {
        data: () => ({
            dialog: false,
            headers: [
                {
                    text: 'Question',
                    align: 'left',
                    sortable: true,
                    value: 'question',
                    width: '25%'
                },
                { text: 'Answer', value: 'answer', width: '55%' },
                { text: 'Actions', value: 'action', sortable: false, width: '20%' },
            ],
            questions: [],
            editedIndex: -1,
            editedItem: {
                question: '',
                answer: ''
            },
            defaultItem: {
                question: '',
                answer: ''
            },
        }),

        computed: {
            formTitle () {
                return this.editedIndex === -1 ? 'New Item' : 'Edit Item'
            },
        },

        watch: {
            dialog (val) {
                val || this.close()
            },
        },

        created () {
            this.initialize();
            this.loadUsers();
        },

        methods: {
            initialize () {
                this.questions = []
            },
            loadUsers(){
                if (axios == null) {
                    return;
                }
                axios.get('/api/faq').then(res=>{
                    if(res.status === 200){
                        this.questions=res.data;
                    }
                }).catch(err=>{
                    console.log(err);
                });
            },

            editItem (item) {
                this.editedIndex = this.questions.indexOf(item);
                this.editedItem = Object.assign({}, item);
                this.dialog = true
            },

            deleteItem (item) {
                const index = this.questions.indexOf(item);
                confirm('Are you sure you want to delete this item?') && this.questions.splice(index, 1)
            },

            close () {
                this.dialog = false;
                setTimeout(() => {
                    this.editedItem = Object.assign({}, this.defaultItem);
                    this.editedIndex = -1
                }, 300)
            },

            saveToServer () {
                if (this.editedIndex > -1) {
                    // Edit item
                    Object.assign(this.questions[this.editedIndex], this.editedItem);
                    axios.put('/api/faq/' + this.questions[this.editedIndex].id, this.editedItem).then(function (response) {
                        console.log(response);
                    })
                        .catch(function (error) {
                            console.log(error);
                        });
                } else {
                    //New item
                    this.questions.push(this.editedItem);
                    axios.post('/api/faq', this.editedItem).then(function (response) {
                        console.log('Before');
                        this.id = response.id;
                        console.log('After');
                        Object.assign(this.questions[this.editedIndex], this);
                        console.log(response);
                    })
                        .catch(function (error) {
                            console.log(error);
                        });
                }

                this.close()
            },
        },
    }
</script>

Store controller:

public function store(Request $request)
    {
        $bodyContent = $request->getContent();
        Storage::disk('local')->put('APIdump.txt', $bodyContent);
        $id = faq::insertGetId($request->all());
        return Response:: json([
            'status' => 'ok',
            'id' => $id,
        ], 200);
    }

Update controller:

public function update(Request $request, $id)
    {
        faq::findOrFail($id)->update($request->all());
        return response(['message' => 'Success']);

    }
Nov
29
5 months ago
Activity icon

Replied to How To Cross Reference Tables

How would I reference that in my VueJS model please?

Activity icon

Started a new Conversation How To Cross Reference Tables

I know that in Laravel I can reference the "name " column of one table using the key from another, but how does one do that in Vue? I'm using the below table layout from Vuetify but can't see how to get the role name from the Roles table using the Role_id from the users table:

<template>
    <div>
        <v-toolbar flat color="white">
            <v-toolbar-title>Users</v-toolbar-title>
        </v-toolbar>
        <v-data-table
            :headers="headers"
            :items="users"
            :items-per-page="5"
            class="elevation-1"
            flat
        >
        </v-data-table>
    </div>
</template>

<script defer>
    export default {
        data () {
            return {
                headers: [
                    {
                        text: 'Username',
                        align: 'left',
                        value: 'username',
                    },
                    { text: 'Email', value: 'email' },
                    { text: 'Role', value: 'role_id' },

                ],
                users: [],
            }
        },
        created() {
            this.loadUsers();
        },
        methods: {
            loadUsers(){
                if (axios == null) {
                    return;
                }
                axios.get('/api/user').then(res=>{
                    if(res.status === 200){
                        this.users=res.data.users;
                    }
                }).catch(err=>{
                    console.log(err);
                });
            }
        }
    }
</script>

Controller:

public function index()
    {
        $allUsers = User::all();
        $allRoles = Role::all();
        return Response::json([
            'users' => $allUsers,
            'roles' => $allRoles
        ], 200);
    }

Many thanks