littleboby

littleboby

Member Since 5 Months Ago

Experience Points
550
Total
Experience

4,450 experience to go until the next level!

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

  • Complete a lesson — 100pts
  • Create a forum thread — 50pts
  • Reply to a thread — 10pts
  • Leave a reply that is liked — 50pts
  • Receive a "Best Reply" award — 500pts
Lessons Completed
0
Lessons
Completed
Best Reply Awards
0
Best Reply
Awards
  • start-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
550 XP
Aug
04
3 months ago
Activity icon

Replied to Vue Router Component Needs Reloading In Order To Function Properly

Thanks for the suggestion, do you think it is because regarding to styling I'm not using a single scss or css but inline component styling?! Also in regard to functionality there are no problems, my bad for saying that.

Edit: tried putting all styles into my scss but that doesn't make a difference

Activity icon

Started a new Conversation Vue Router Component Needs Reloading In Order To Function Properly

Hello everyone,

I'm having a bit of an issue with vue router.

Basically I have a parent component and children of children of this component(so a tree of components). So far the basic route functionality/navigation works as expected, but when I use a "back button" to go back to a specific parent component, there are (parent)component elements such as buttons and inputs that do not reload and function properly.

What I mean by that is, a simple input after going back looks like this when clicked inside of: https://imgur.com/a/JzxE1h8 : instead of looking like this: https://imgur.com/a/HSNcgTk.

This simple input field is one of more than 10 examples(inputs, textareas, buttons).

If I want the elements to look how I want(and how it should on click) I have to reload.

Here are two short snippets regarding a parent and its child component:


<div class="mdl-card__actions mdl-card--border"> // just the click
       <router-link v-bind:to="'/group/' + group.id">
             <a class="mdl-button"> View Group </a>
       </router-link>
</div>      

and the back button inside the child that takes us back to the parent:

<button @click="$router.push({path: '/discover'})" class="mdl-button mdl-js-button mdl-js-ripple-effect mdl-button--colored backbtn">
                Back to Groups
</button>

Now speaking strictly semantically I know I could just write router-link without an anchor tag within but bear with me:

  • Using simple anchor tags with a click event and pushing a path doesn't make a difference, neither does:
  • Using a router-link as a back button

Also I have initiated router-view in my App.vue component.

I hope this snippet is enough to tell me what I missed, otherwise I'd be happy to provide more, your help is appreciated.

Thanks

Aug
01
3 months ago
Activity icon

Replied to Cannot Create New RESTful API Instance

Thanks for the answer, now in my web.php file I replaced the earlier statement with the following:

Route::get('/{any?}', function (){
    return view('discover');
})->where('any', '^(?!api\/)[\/\w\.-]*');

and the store method like so:

public function store(Request $request) {
        $request->validate([
            'title' => 'required|max:30',
            'description' => 'required|max:455',
            'place' => 'required',
            'time_happening' => 'required|date',
        ]);

        $event = Event::createFromArray($request->toArray());

        return response()->json($event)->withHeaders([
            'Content-Type' => 'application/json;charset=UTF-8, Accept:application/json',
        ]);
    }

Telescope shows this:

content-type: "application/json",

and it still doesn't seem to work. Trying this syntax in Insomnia or Postman gives an error saying:

The GET method is not supported for this route. Supported methods: POST.

Could I make the route statement better? What should I make to fix this?

Jul
29
3 months ago
Activity icon

Replied to Cannot Create New RESTful API Instance

@punksolid & @snapey - So in my api.php file I have this route -

Route::post('event/', '[email protected]');

which calls the aforementioned method.

In my Insomnia Client I'm doing the request with the following json body and the following credentials - Body: https://imgur.com/ILgyz2e , Authentication: https://imgur.com/Rf93al3 , Telescope Feedback: https://imgur.com/8uPs1QU - , which I now see uses the SinglePageController and gets me redirected.

This controller looks like this:

class SinglePageController extends Controller {
    public function index() {
        return view('discover');
    }
}

which is the main class for the following route(s):

Route::get('/{any}', '[email protected]')->where('any', '.*');
Jul
28
3 months ago
Activity icon

Replied to Cannot Create New RESTful API Instance

Also: If I open my Telescope panel this request is shown as a GET request and I don't get it

Activity icon

Replied to Cannot Create New RESTful API Instance

Thanks for the answer @punksolid, I just switched from create to store. The Resource::controller('EventController') is in other methods of this controller, if that makes any difference to my situation?

My route for this method looks like this:

Route::post('event/', '[email protected]');

Jul
27
3 months ago
Activity icon

Started a new Conversation Cannot Create New RESTful API Instance

Doing a small CRUD-App and I'm having problems creating an instance, on Api endpoint: 'event/' the Controller named: EventController and Method: create is called.

This is what the method looks like:

public function create(Request $request) {
    $request->validate([
        'title' => 'required|max:30',
        'description' => 'required|max:455',
        'place' => 'required',
        'time_happening' => 'required|date',
    ]);

    $event = Event::createFromArray($request->toArray());

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

While the model looks like this:

public static function createFromArray($data) {
    // Create a new event with the given data.
    $event = self::create([
        'title' => $data['title'],
        'description' => $data['description'],
        'place' => $data['place'],
        'time_happening' => $data['time_happening'],
        'created_by' => auth()->user()->id,
        'group_id' => $data['group_id']
    ]);


    // Return the newly created event.
    return $event
}

The JSON I'm writing in the API Client:

{
  "title": "Laravel Tech Meetup.Laravel Tech Meetup.Laravel Tech 
    Meetup.Laravel Tech Meetup.",

   "description": "Qui molestiae consectetur ipsam vel 
    dicta. Nesciunt architecto laborum accusantium
    eos facere temporibus iure fugiat. 
    Et dicta incidunt ut deleniti eum alias earum.",

   "place": "83224 Blabla",
   "time_happening": "2019-09-25 03:29:46"
}

With this code I expect for the new instance to:

  • Get created by the user I'm logged in as,
  • And to get returned to me in the API Client I'm using(Insomnia)

Result:

I get redirected to Homepage and when I check if it's created in the database it's not.

What am I doing wrong?!

Jul
01
4 months ago
Activity icon

Replied to Nested Routes Throwing Error In Vue Router

Did you found a solution eventually?! I'm having this exact same one

Jun
30
4 months ago
Activity icon

Replied to Getting All Json Instances From An Axios Response Dynamically

@DIEGOAURINO - I commented attributes out and now I have only

 'name' => $this->name,
 'description' => $this->description,

and it works perfectly, but I don't understand the mistake, if I want to define attributes in my Resource how would I do it?!

Thanks for pointing it out.

Activity icon

Replied to Getting All Json Instances From An Axios Response Dynamically

@DIEGOAURINO - Hey @diegoaurino, thanks for your reply,

  • What I'm trying to do as mentioned above is getting different attributes of a json response, this seems needlessly complicated to implement, how do people generally achieve something like this?! E.g; getting json attributes from an api and put them into different HTML-Elements

  • Concerning the weird structure of the API, that comes from the Resource which I have formatted that way

  • I don't have the singular 'group' anymore in my data function

  • Console logging the this.groups outputs json data in this form: Object->data->0 through 9 observers->attributes->description & name

  • In my GroupCard component in Vue.js devtools I get the groups array with 0 through 9 objects, clicking one of them reveals attributes object

  • Wouldn't the data already be iterable since iterating through it in my container generates us 10 Cards?!

Activity icon

Replied to Getting All Json Instances From An Axios Response Dynamically

@MSTRAUSS - Exactly, I have ten(from pagination in the GroupsController) cards, but empty. Adding this to my getGroups method directly after the line

this.groups = response.data.data;

produces no effect.

Activity icon

Replied to Getting All Json Instances From An Axios Response Dynamically

@DIEGOAURINO - I understand but this is not what we should be focusing right now as I'm using the lexical this and it does work generating 10 cards. The problem right now is I can't get all the relevant attributes after I get all empty cards.

Activity icon

Replied to Getting All Json Instances From An Axios Response Dynamically

@MSTRAUSS - I am using @diegoaurino 's answer for this, writing an arrow function and then the functionality exactly as I wrote at the reply above and it doesn't work. So now I have 10 card elements from this line:

this.groups = response.data.data;

Now if I use

 this.groups.name = response.data.data[0].attributes.name; 

while

data: function() {
        return {
            groups: [{
                name : '',
                description : ''
            }],
        }
    },

it means I would only get the attributes of the instance in the index 0, but that doesn't work either, also after running npm run dev and deleting my cache

Activity icon

Replied to Getting All Json Instances From An Axios Response Dynamically

@MSTRAUSS - Yes, now it works, thank you. this.groups = response.data.data; gives that many groups I'm passing (in this case 10 with pagination), but getting the name and description in my HTML elements like so

data: function() {
        return {
            groups: [{
                name : '',
                description : ''
            }],
        }
    },

// and then in axios function
this.groups.name = response.data.data.attributes.name; 

does not work, any ideas?!

Jun
29
4 months ago
Activity icon

Started a new Conversation Getting All Json Instances From An Axios Response Dynamically

I am giving my API-Resource to my vue component, but I cannot access all the single id's.

Route:

// Get all Groups
Route::get('groups', '[email protected]');

Index method:

public function index() {
        // Get Groups
        $groups = Groups::paginate(10);

        // Return collection of Groups as a resource
        return GroupsResource::collection($groups);
    }

and the Resource itself:

class Groups extends JsonResource {
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function toArray($request) {
        return [
            'type' =>'group',
            'id' => $this->id,
            'attributes' => [
                'name' => $this->name,
                'description' => $this->description,
            ],
        ];
    }

    public function with($request) {
        return [
            'version' => '1.0.0',
            'author_url' => url('http://www.blabla.com')
        ];
    }
}

My Component looks like this:

<template>
    <div class="group-card">
        <div v-for="group in groups" class="demo-card-wide mdl-card mdl-shadow--2dp" :group="group">
            <div class="mdl-card__title">
                <h2 class="mdl-card__title-text"> {{ group.name }}</h2>
            </div>
            <div class="mdl-card__supporting-text">
                {{ group.description }}
            </div>
            <div class="mdl-card__actions mdl-card--border">
                <a class="mdl-button mdl-button--colored mdl-js-button mdl-js-ripple-effect"> Get Started </a>
            </div>
            <div class="mdl-card__menu">
                <button class="mdl-button mdl-button--icon mdl-js-button mdl-js-ripple-effect">
                <i class="material-icons">share</i>
                </button>
            </div>
        </div>
    </div>
</template>


<script>
export default {
    data: function() {
        return {
            groups: [],
            group: [{ // commenting this out has absolutely no effect
                    name: "",
                    description : ""
                }]
        }
    },

    methods: {
        getGroups() {
            axios.get('/api/groups')
            .then(function (response) {
                console.log(response.data.data[0].attributes.name); // this line is where we are getting our Name value from
                this.groups = response.data.data[0].attributes; // this line doesn't work
            })
        }
    },

    mounted() {
    console.log('Group Card mounted.');
    this.getGroups();
    }

}
</script>

While as a response in my console log I get:

Aliquam autem voluptas ipsa non. // the name
app.js:1914 Uncaught (in promise) TypeError: Cannot set property 'groups' of undefined
    at app.js:1914

Also I should mention, what I get as response.data is the following:

{data: Array(10), links: {…}, meta: {…}}
data: Array(10)
0:
attributes:
description: "Esse doloremque iste aperiam atque minus ab illum dolores dignissimos amet illum voluptatem voluptas."
name: "Aliquam autem voluptas ipsa non."
__proto__: Object
id: 1
type: "group"
__proto__: Object
1: {type: "group", id: 2, attributes: {…}}
2: {type: "group", id: 3, attributes: {…}}
3: {type: "group", id: 4, attributes: {…}}
4: {type: "group", id: 5, attributes: {…}}
5: {type: "group", id: 6, attributes: {…}}
6: {type: "group", id: 7, attributes: {…}}
7: {type: "group", id: 8, attributes: {…}}
8: {type: "group", id: 9, attributes: {…}}
9: {type: "group", id: 10, attributes: {…}}
length: 10
__proto__: Array(0)
links: {first: "http://www.styx-occursum.io/api/groups?page=1", last: "http://www.styx-occursum.io/api/groups?page=2", prev: null, next: "http://www.styx-occursum.io/api/groups?page=2"}
meta: {current_page: 1, from: 1, last_page: 2, path: "http://www.styx-occursum.io/api/groups", per_page: 10, …}
__proto__: Object

The group component, (in itself a material design card element) is not being shown at this point. As you can see I can access the attributes.name of a single un-dynamical instance and I cannot "fill" the groups array declared at the top.

  • How do I access all the instances of this Json object and give it back at the HTML above?

Thanks in advance and sorry for the long post, I'm trying to give as much info as possible.

Jun
28
4 months ago
Activity icon

Replied to Vue.js Activated In Tab: Npm Run Watch Build Successful, No Visual Feedback

@DIEGOAURINO - Okay now I added id=app to the div element at Discover.html and removed the div container from template element at Discover.vue; I get two times "Component mounted." in the console as expected and the material header is injected as HTML; but I can't see it.

Activity icon

Replied to Vue.js Activated In Tab: Npm Run Watch Build Successful, No Visual Feedback

@DIEGOAURINO - Hey, thanks for the reply. I just tried it and now I'm getting this other error in the console app.js:38006 [Vue warn]: Cannot find element: #app...

Activity icon

Started a new Conversation Vue.js Activated In Tab: Npm Run Watch Build Successful, No Visual Feedback

I have this route:

Route::get('/discover', function() {
    return view('discover');
});

which returns an HTML file.

Discover.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
    <link rel="stylesheet" href="https://code.getmdl.io/1.3.0/material.deep_purple-indigo.min.css" />
    <script defer src="https://code.getmdl.io/1.3.0/material.min.js"></script>
    <script src="js/app.js" defer></script>
    <title>Discover</title>
</head>
<body>
    <div class="app">
        <discover></discover>
    </div>
</body>
</html>

while Discover.vue looks like this:

<template>
<div id="chat-app">
    <HeaderComponent></HeaderComponent>
</div>
</template>


<script>

import HeaderComponent from './HeaderComponent';

export default {
    mounted() {
        console.log('Component mounted.')
    }
}


components: {
    HeaderComponent
}

</script>

and HeaderComponent.vue

<template>
    <header class="mdl-layout__header mdl-layout__header--transparent">
    <div class="mdl-layout__header-row">
      <!-- Title -->
      <span class="mdl-layout-title">Title</span>
      <!-- Add spacer, to align navigation to the right -->
      <div class="mdl-layout-spacer"></div>
      <!-- Navigation -->
      <nav class="mdl-navigation">
        <a class="mdl-navigation__link" href="">Link</a>
        <a class="mdl-navigation__link" href="">Link</a>
        <a class="mdl-navigation__link" href="">Link</a>
        <a class="mdl-navigation__link" href="">Link</a>
      </nav>
    </div>
  </header>
</template>

<script>
export default {
    mounted() {
       console.log('Component mounted.')
    }
}
</script>


App.js configuration is pretty standard:

Vue.component('discover', require('./components/Discover.vue').default);

/**
 * Next, we will create a fresh Vue application instance and attach it to
 * the page. Then, you may begin adding components to this application
 * or customize the JavaScript scaffolding to fit your unique needs.
 */

const app = new Vue({
    el: '#app',
});

The error has two parts:

  • I have a blank page &
  • On the console I get [Vue warn]: Unknown custom element: <HeaderComponent> - did you register the component correctly? For recursive components, make sure to provide the "name" option.

Have I done a syntax error or am I not thinking about this logically?!

Activity icon

Replied to Validating Input Fields With Required

@SNAPEY - So now I deleted it and wrote it like so:

$request->validate([
            'title' => 'required|max:30',
            'description' => 'required|max:255',
            'place' => 'required',
            'time_happening' => 'date'
        ]);
    

Is this safe to a certain degree?!

Activity icon

Started a new Conversation Validating Input Fields With Required

I have an API and inside a table named Meetup, I'm validating the rows like so:

$meetup = $request->isMethod('put') ? Meetup::findOrFail($request->meetup_id) : new Meetup;

        $meetup->id = $request->input('meetup_id');
        $meetup->title = $request->input('title');
        $meetup->description = $request->input('description');
        $meetup->place = $request->input('place');
        $meetup->time_happening = $request->input('time_happening');
        $meetup->created_at = $request->input('created_at');
        $meetup->created_by = $request->input('created_by');
        $meetup->group_id = $request->input('group_id');
    
        if ($meetup->save()) {
            return new MeetupResource($meetup);
        }

However, I want to make certain fields required, so how would I implement something like that without getting rid of input()(if I shouldn't get rid of it)?

Activity icon

Replied to Seeding While Telescope Is Active Generates Fatal Throwable Error

@JOHNBRAUN - Thanks for the reply, I was mistakenly generating so many fake data that my memory limit was met. So I got rid of my seeders, and instead I'm just generating data with Faker and rand() in the right numbers scope(e.g 50 Users, Meetups row named created_by generates rand(1, 50) and so on.)

However thanks for the suggestion and I'm marking you as the right answer.

Jun
27
4 months ago
Activity icon

Started a new Conversation Seeding While Telescope Is Active Generates Fatal Throwable Error

Hey everyone, I'm doing a web application where people can create events and join them, comment etc.

Today I added comments and comment_likes table(Migrations, Seeders & Factories). Telescope is active and when I migrate:fresh the telescope tables get migrated too, and when I try to seed my fake data I get the following error:

Seeding: MeetupsTableSeeder

   Symfony\Component\Debug\Exception\FatalThrowableError  : Maximum function nesting level of '256' reached, aborting!

  at C:\xampp\htdocs\meetup\vendor\laravel\framework\src\Illuminate\Container\Container.php:1102
    1098|      *
    1099|      * @param  string  $abstract
    1100|      * @return string
    1101|      */
  > 1102|     public function getAlias($abstract)
    1103|     {
    1104|         if (! isset($this->aliases[$abstract])) {
    1105|             return $abstract;
    1106|         }

  Exception trace:

  1   Illuminate\Container\Container::getAlias("env")
      C:\xampp\htdocs\meetup\vendor\laravel\framework\src\Illuminate\Foundation\Application.php:761

  2   Illuminate\Foundation\Application::make("env")
      C:\xampp\htdocs\meetup\vendor\laravel\framework\src\Illuminate\Container\Container.php:1225

  Please use the argument -v to see more details.

If I go to config/telescope.php and set 'enabled' => env('TELESCOPE_ENABLED', true), to false, I get the following error:

 php artisan db:seed
Seeding: MeetupsTableSeeder

   Symfony\Component\Debug\Exception\FatalThrowableError  : Maximum function nesting level of '256' reached, aborting!

  at C:\xampp\htdocs\meetup\vendor\fzaninotto\faker\src\Faker\Provider\Base.php:183
    179|      * @throws \LengthException When requesting more elements than provided
    180|      *
    181|      * @return array New array with $count elements from $array
    182|      */
  > 183|     public static function randomElements($array = array('a', 'b', 'c'), $count = 1, $allowDuplicates = false)
    184|     {
    185|         $traversables = array();
    186| 
    187|         if ($array instanceof \Traversable) {

  Exception trace:

  1   Faker\Provider\Base::randomElements()
      C:\xampp\htdocs\meetup\vendor\fzaninotto\faker\src\Faker\Provider\Base.php:234

  2   Faker\Provider\Base::randomElement()
      C:\xampp\htdocs\meetup\vendor\fzaninotto\faker\src\Faker\Provider\Person.php:92

  Please use the argument -v to see more details.

Am I missing something?! If I search for exactly this error online telescope is not included at all so people are trying to do other things completely.

Jun
20
5 months ago
Activity icon

Replied to Illuminate\Database\QueryException : SQLSTATE[23000]: Integrity Constraint Violation: 1452 Cannot Add Or Update A Child Row: A Foreign Key Constraint Fails

@NAKOV - I oversaw you adding the classes at the top, my bad. The factory seems to be working now, however there is this Illuminate\Database\QueryException : SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`styx-occursum`.`meetups`, CONSTRAINT `meetups_group_id_foreign` FOREIGN KEY (`group_id`) REFERENCES `groups` (`id`) ON DELETE CASCADE) (SQL: insert into `meetups` (`title`, `description`, `place`, `created_by`, `group_id`, `time_happening`, `updated_at`, `created_at`) values (Et quos ut velit aut., Odit voluptas est veniam eum et asperiores et. Iste quia et voluptas est. Eligendi maxime saepe provident neque. Neque quia voluptatibus eum quisquam. Sapiente culpa neque earum molestiae aut in., 26588 Glover Route Apt. 552, 104, 4, 2015-11-13 04:56:36, 2019-06-20 21:41:27, 2019-06-20 21:41:27)) error not letting it work now

Activity icon

Replied to Illuminate\Database\QueryException : SQLSTATE[23000]: Integrity Constraint Violation: 1452 Cannot Add Or Update A Child Row: A Foreign Key Constraint Fails

@NAKOV - Okay now my factory looks like this:

$factory->define(App\Meetup::class, function (Faker $faker) {

    $user = factory(User::class)->create();

    return [
        'title' => $faker->text(30),
        'description' => $faker->text(200),
        'place' => $faker->streetAddress(),
        'created_by' => factory(Meetup::class, 100)->create(['created_by' => $user->id]),
        'group_id' => factory(Group::class),
        'time_happening' =>$faker->dateTime($max = 'now', $timezone = null)
    ];
});

and I'm getting Symfony\Component\Debug\Exception\FatalThrowableError : Class 'User' not found in the console, did I do something wrong?!

Activity icon

Replied to Illuminate\Database\QueryException : SQLSTATE[23000]: Integrity Constraint Violation: 1452 Cannot Add Or Update A Child Row: A Foreign Key Constraint Fails

@NAKOV - Thanks for the reply, does this generate a random Existing user_id for each meetup?! Trying this now

Activity icon

Started a new Conversation Illuminate\Database\QueryException : SQLSTATE[23000]: Integrity Constraint Violation: 1452 Cannot Add Or Update A Child Row: A Foreign Key Constraint Fails

Creating an application where people create events or 'meetups'. I created my factories: 2019_06_20162119_create_groups_table, (different meetup categories) 201906_20_170900create_meetups_table, (the events themselves) 201906_20182232_create_attending_table, (people that are attending) & 201906_20_182319_create_group_members_table (members of the different categories)

After I created the seeders and factories and doing php artisan db:seed the error comes up, here's what my scripts look like(sorry for the long post):

Meetups table:

class CreateMeetupsTable extends Migration
{
   /**
    * Run the migrations.
    *
    * @return void
    */
   public function up()
   {
       Schema::create('meetups', function (Blueprint $table) {
           $table->bigIncrements('id');
           $table->string('title');
           $table->longText('description');
           $table->string('place');
           $table->dateTimeTz('time_happening');
           $table->timestamps();
           $table->bigInteger('created_by')->unsigned();
           $table->foreign('created_by')->references('id')->on('users')->onDelete('cascade');
           $table->bigInteger('group_id')->unsigned();
           $table->foreign('group_id')->references('id')->on('groups')->onDelete('cascade');
       });
   }

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

Groups table:

class CreateGroupsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('groups', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name');
            $table->string('description');
        });
    }

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

Attending table:

class CreateAttendingTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('attending', function (Blueprint $table) {
            $table->bigInteger('meetup_id')->unsigned();
            $table->foreign('meetup_id')->references('id')->on('meetups')->onDelete('cascade');
            $table->bigInteger('user_id')->unsigned();
            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
            $table->timestamps();
        });
    }

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

Group members table:

class CreateGroupMembersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('group_members', function (Blueprint $table) {
            $table->bigInteger('group_id')->unsigned();
            $table->foreign('group_id')->references('id')->on('groups')->onDelete('cascade');
            $table->bigInteger('user_id')->unsigned();
            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
        });
    }

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

MeetupsTableSeeder:

class MeetupsTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        factory(App\Meetup::class, 100)->create();
    }
}

AttendingTableSeeder:

class AttendingTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        factory(App\Attending::class, 100)->create();
    }
}

GroupMembersSeeder

class GroupMembersSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        factory(App\GroupMembers::class, 500)->create();
    }
}

UserTableSeeder:

public function run()
    {
        factory(App\User::class, 50)->create();
    }

& DatabaseSeeder

public function run()
    {
        $this->call(MeetupsTableSeeder::class);
        $this->call(UserTableSeeder::class);
        $this->call(AttendingTableSeeder::class);
        $this->call(GroupMembersSeederTableSeeder::class);
    }

The meetups factory looks like this:

$factory->define(App\Meetup::class, function (Faker $faker) {
    return [
        'title' => $faker->text(30),
        'description' => $faker->text(200),
        'place' => $faker->streetAddress(),
        'created_by' => rand(1, 50),
        'group_id' => rand(1, 15),
        'time_happening' =>$faker->dateTime($max = 'now', $timezone = null)
    ];
});

Group members factory:

$factory->define(App\GroupMembers::class, function (Faker $faker) {
    return [
        'group_id' => rand(1, 15),
        'user_id' => rand(1, 50)
    ];
});

Attending factory:

$factory->define(App\Attending::class, function (Faker $faker) {
    return [
        'meetup_id' => rand(1, 100),
        'user_id' => rand(1, 50)
    ];
});

& the Users factory:

$factory->define(User::class, function (Faker $faker) {
    return [
        'name' => $faker->name,
        'email' => $faker->unique()->safeEmail,
        'email_verified_at' => now(),
        'password' => bcrypt('secret'), // secret
        'remember_token' => Str::random(10),
    ];
});

I also created the models for every table/class but have written nothing in them as yet, I am aware that there are a lot of questions like this on other platforms but none of the answers seem to help with my case, so in advance thank you kind stranger/s!