BrownieCoffee

BrownieCoffee

Member Since 4 Months Ago

Experience Points
2,380
Total
Experience

2,620 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
2,380 XP
Nov
11
1 week ago
Activity icon

Replied to Is It A Good Thing To Have Many Textarea ?

@nakov , @jlrdw , @shez1983 I would to permit to my users to create an article with steps. If there are for example, a step 2, he clicks on the button 'add a step' which add a new block with heading and textarea.

I don't know if it is clear... :/ .

Activity icon

Started a new Conversation Is It A Good Thing To Have Many Textarea ?

Hi,

I have a textarea and I would add anothers on click on a button ( like this video : https://www.youtube.com/watch?v=rVmZXJj5lH0).

My question is: is it a good thing to do that ? Isn't it to heavy for a website ?

Thank by advance.

Good B.

Activity icon

Replied to Summernote : Upload Image Only From Server ( Remove Upload Image Via Link)

@jlrdw Hi :) . First of all, thank's for your answer.

Actually, Summernote has a button image which, on click, open a modal with input file and input link.

I want to choose a image from server without using this modal (like QuillJs doing ).

Nov
09
1 week ago
Activity icon

Started a new Conversation Summernote : Upload Image Only From Server ( Remove Upload Image Via Link)

Hi there,

I have a question about summernote. I didn't find out solution. I use summernote to white articles. I permit users to upload images but I don't want they use the image uploader via link. I want to permit that only from server.

Is it possible to do that ?

Thank by advance.

Good B.

Nov
06
1 week ago
Activity icon

Started a new Conversation Can We Have <head> Tag Inside 2 Blade.php Files ?

Hi there,

I have a question about files.

I extended the file projects/index.blade.php to 2 files questions/index.blade.php, events/index.blade.php. I want now create another file without extend the projects/index.blade.php.

can I do this knowing that my projects/index.blade.php contains already

<!DOCTYPE html>
<html lang="{{ app()->getLocale() }}">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <link href="{{ asset('css/app.css') }}" rel="stylesheet">
    <title>Des projets écolos et économes</title>
</head>

?

Thank by advance.

Nov
03
2 weeks ago
Activity icon

Started a new Conversation Change Classes According To Width And Url

Hi guys, how are you?

I need help with my condition below :


app = {

    init: function () {

    /*1: stockage des classes dans des variables */


    /*2: actions par défault sur les classes */

    /*3: actions réalisées sur ces classes */

        $(window).on('resize', app.switchClassAbove1120Px).resize();

    },

    /*4: functions */

    switchClassAbove1120Px: function () {
        console.log('ca change!')
        // e.preventDefault();
           var width = $(window).width();

        if (($(location).attr('href').indexOf('forum') && width >= 1120)) {
            console.log('grand!')
            $('.categories-choice__list-items').removeClass('categories-choice__list-items__displaying--flex categories-choice__list-items__positionning--center categories-choice__list-items__overflow--x-auto categories-choice__list-items__scrollbar--hide').addClass('categories-choice__list-items__displaying--block');
        } else if(($(location).attr('href').indexOf('forum') && width <= 1120)){
            console.log('petit');
            $('.categories-choice__list-items').removeClass('categories-choice__list-items__displaying--block').addClass('categories-choice__list-items__displaying--flex categories-choice__list-items__positionning--center categories-choice__list-items__overflow--x-auto categories-choice__list-items__scrollbar--hide');
        }
    }
}

app.init();

I want that the classes are removed and added only if url == /forum and width <= 1200px .

Actually, the condition also used with home url ...

Can you help me please?

Thank a lot by advance. See you +

Sep
04
2 months ago
Activity icon

Replied to Upload Image From Computer With Tiptap Vue JS

@mvd Thank I'll check that !

Sep
02
2 months ago
Activity icon

Started a new Conversation Upload Image From Computer With Tiptap Vue JS

Hi guys, how are you?

I have a question about TipTap VueJS. I discovered this rich text editor and I would like to know if it is possible to upload an image from computer.

Aug
15
3 months ago
Activity icon

Started a new Conversation Remove Code On Click On A Button.

Hi guys.

I need you help to fix my problem.

I realize comments system. On click on "response" text, textarea appears with cancel and submit buttons . It's working for that.

But if I'm trying to remove this texterea width both buttons on click on cancel button It's not working I don't know why.

Can you help me please ? i hope my explaination is clear to you.

I share you link right there https://codeshare.io/amkN0X

Aug
14
3 months ago
Activity icon

Replied to Use "{{asset('/image/...'}} In Jquery

@bobbybouwmann got it ! Thank you.

Actualy I make my integrations. After that, Some part of code will be dynamic.

Activity icon

Started a new Conversation Use "{{asset('/image/...'}} In Jquery

Hi there.

I'm trying to display an avatar image on jquery but it fails.

I use actually this code for blade.php

<div class="questions-section__body questions-section__body--padding uk-card-body">
        <div class="questions-section__write-comment-box questions-section__write-comment-box--margin">
          <img class="avatar" src="{{asset('/images/persons/marius.jpg')}}"
          alt="avatar de l'utilisateur">
          <form class="" action="index.html" method="post" name="comment_form">
            <textarea class="textarea textarea--border questions-section__textarea questions-section__textarea--border questions-section__textarea--width questions-section__textarea--margin questions-section__textarea--resize" rows="3"></textarea>
            <button class="questions-section__submit-button questions-section__submit-button--float questions-section__submit-button--margin questions-section__submit-button--border uk-button uk-button-default">poser ma question</button>
          </form>
        </div>

and this code for jquery

    $questionResponse = $('.questions-section__response-action');

$questionResponse.click(function (e){
    e.preventDefault();

    $('.questions-section__comment').append('<div class="questions-section__body questions-section__body--padding uk-card-body"><div class="questions-section__write-comment-box questions-section__write-comment-box--margin"><img class="avatar" src="{{asset('+'/images/persons/marius.jpg'+')}}" alt="avatar de l\'utilisateur"><form class="" action="index.html" method="post" name="comment_form"><textarea class="textarea textarea--border questions-section__textarea questions-section__textarea--border questions-section__textarea--width questions-section__textarea--margin questions-section__textarea--resize" rows="3"></textarea><button class="questions-section__submit-button questions-section__submit-button--float questions-section__submit-button--margin questions-section__submit-button--border uk-button uk-button-default">poser ma question</button></form></div>');
  });


Can you help me to fix that please? Thank you by advance.

Aug
12
3 months ago
Aug
07
3 months ago
Activity icon

Replied to Session Has Unexpected Errors:

@aurawindsurfing I just did that. I still the same error

Activity icon

Replied to Session Has Unexpected Errors:

@aurawindsurfing

I remove image|mimes:png,jpg,jpeg| and it's working. I don't know why. I check my form and There is enctype="multipart/form-data" ...

Activity icon

Replied to Session Has Unexpected Errors:

@aurawindsurfing HI . I tryed your solution but I have still error.

I just tryed with this piece of code too image|mimetypes:image/jpeg,image/png,image/jpg but in vain...

Activity icon

Replied to Session Has Unexpected Errors:

@aurawindsurfing Sorry I didn't understood your question.

<?php

/* @var $factory \Illuminate\Database\Eloquent\Factory */
use App\Project;
use App\User;
use Faker\Generator as Faker;

$factory->define(Project::class, function (Faker $faker) {


    return [
        // 'user_id' => function () {
        //     return factory(User::class)->create()->id;
        // },
        'user_id' => factory(User::class)->create()->id,
        'title' => $faker->sentence(),
        'thumbnail' =>$faker->image('public/images/',640,480, null, false),
        'content' => $faker->text()
    ];
});


Aug
06
3 months ago
Activity icon

Replied to Session Has Unexpected Errors:

@aurawindsurfing , @lenophie hi guys.

The solution given by @aurawindsurfing seems like good but I've still errors for thumbnail field.

//actual error


.........."86188d512f07f6c9773f1090ff1e6aeb.jpg"
F.............                                          24 / 24 (100%)

Time: 30.51 seconds, Memory: 26.00 MB

There was 1 failure:

1) Tests\Feature\ProjectCreationTest::the_fields_are_filled
Session has unexpected errors: 

[
    "The thumbnail must be an image.",
]
Failed asserting that true is false.

/var/www/html/goshr/vendor/laravel/framework/src/Illuminate/Foundation/Testing/TestResponse.php:991
/var/www/html/goshr/tests/Feature/ProjectCreationTest.php:67
/home/audrey/.composer/vendor/phpunit/phpunit/src/TextUI/Command.php:201
/home/audrey/.composer/vendor/phpunit/phpunit/src/TextUI/Command.php:160

FAILURES!
Tests: 24, Assertions: 71, Failures: 1.

// my request 

  public function rules()
    {
        return [
            
        'category' => 'required',
        'title' => 'required|unique:projects,title|min:10|max:80',
        'thumbnail' =>'nullable|image|max:5000',
        'material' => 'required|array|min:1', // je précise ici que "material" doit être un tableau,  qu'il doit être requis et  qu'il doit compté au moins 1 élément.
        'material.*' => 'nullable|alpha_num|between:3,200|distinct', // je dis que pour tous les valeurs dans ce tableau peuvent être nulles, de type string, faire au minimum 3 caractères et unique
        'material.0' =>'required', // je dis que le champ 0 doit être requis
        'content' => 'required|min:10'

        ];

    }
actual code test


 /**
     * Fields are filled.
     *
     * @return void
     * @test
     */
    public function the_fields_are_filled()
    {
         
        $project = factory(Project::class)->make([
            // 'title' => 'Ceci est un nouveau titre',
            'user_id' => factory(User::class)->create(),
            'category_id' => factory(Category::class)->create(),
            'material_id'  =>factory(Material::class)->create()
        ]);

        dump($project->thumbnail);



        $response =  $this->actingAs(factory('App\User')->make())->post(route('projets.store'),
              [
                    'category' =>$project->category_id,
                    'user_id' => $project->user_id, 
                    'title' => $project->title, //pb -> titre déjà pris
                    'thumbnail' =>$project->thumbnail, // pas de thumbnail
                  //  'material[]' => $project->material_id, // pas de materiels
  'material' => [  // <===== EDIT
                        $project->material_id
                    ] , // pas de materiels
                    'content' => $project->content
                
                    ]
               
                ); 
        

        $response->assertSessionHasNoErrors()->assertEquals(1,Project::all()->count());
    }   


Do you know why I have thoses errors... ?

Activity icon

Started a new Conversation Session Has Unexpected Errors:

Hello,

I have a problem with my test. There are duplication of datas and I don't know why.

I have these error below :

F............                                           23 / 23 (100%)

Time: 8.36 seconds, Memory: 24.00 MB

There was 1 failure:

1) Tests\Feature\ProjectCreationTest::the_fields_are_filled
Session has unexpected errors: 

[
    "The title has already been taken.",
    "The thumbnail must be an image.",
    "The material field is required.",
    "The material.0 field is required."
]
Failed asserting that true is false.

/var/www/html/goshr/vendor/laravel/framework/src/Illuminate/Foundation/Testing/TestResponse.php:991
/var/www/html/goshr/tests/Feature/ProjectCreationTest.php:107
/home/audrey/.composer/vendor/phpunit/phpunit/src/TextUI/Command.php:201
/home/audrey/.composer/vendor/phpunit/phpunit/src/TextUI/Command.php:160

FAILURES!
Tests: 23, Assertions: 71, Failures: 1.

Can you help me please with that ?

there are all code at this link : https://codeshare.io/aJY79q

Thank you by advance.

Activity icon

Replied to Unexpected Errors For My Test

@punksolid @rajkotmachine hi , sorry ! I edited my post :) There is the test code now

Aug
05
3 months ago
Activity icon

Started a new Conversation Unexpected Errors For My Test

Hello,

I on my tests yet and I have unexpected errors.

............                                           23 / 23 (100%)

Time: 30.1 seconds, Memory: 30.00 MB

There was 1 failure:

1) Tests\Feature\ProjectCreationTest::the_fields_are_filled
Session has unexpected errors: 

[
    "Il semblerait que ce titre soit déjà pris",
    "The thumbnail must be an image.",
    "The material field is required.",
    "Vous devez inscrire au moins un matériel pour ce projet"
]
Failed asserting that true is false.

/var/www/html/goshr/vendor/laravel/framework/src/Illuminate/Foundation/Testing/TestResponse.php:991
/var/www/html/goshr/tests/Feature/ProjectCreationTest.php:111
/home/audrey/.composer/vendor/phpunit/phpunit/src/TextUI/Command.php:201
/home/audrey/.composer/vendor/phpunit/phpunit/src/TextUI/Command.php:160

FAILURES!
Tests: 23, Assertions: 71, Failures: 1.

But all my fields are filled

result `dump($response)`

#data: array:6 [
          "category" => 1
          "user_id" => 1
          "title" => "Ab iste esse qui fugit quas exercitationem vitae molestias."
          "thumbnail" => "891833a5f5421160f20fb75c62d07989.jpg"
          "material_id" => array:2 [
            0 => 1
            1 => 2
          ]
          "content" => "Aliquid quaerat dolorem dolorem nihil architecto eligendi. Optio autem est molestias incidunt quas illum."
        ]


#initialRules: array:7 [
          "category" => "required"
          "title" => "required|unique:projects|min:10|max:80"
          "thumbnail" => "nullable|image|max:5000"
          "material" => "required|array|min:1"
          "material.*" => "nullable|alpha_num|between:3,200|distinct"
          "material.0" => "required"
          "content" => "required|min:10"
        ]
        #rules: array:6 [
          "category" => array:1 [
            0 => "required"
          ]
          "title" => array:4 [
            0 => "required"
            1 => "unique:projects"
            2 => "min:10"
            3 => "max:80"
          ]
          "thumbnail" => array:3 [
            0 => "nullable"
            1 => "image"
            2 => "max:5000"
          ]
          "material" => array:3 [
            0 => "required"
            1 => "array"
            2 => "min:1"
          ]
          "material.0" => array:1 [
            0 => "required"
          ]
          "content" => array:2 [
            0 => "required"
            1 => "min:10"
          ]
        ]




.blade.php


<form id="project-create-form" action="{{route('projets.store')}}" method="POST" enctype="multipart/form-data">
            @csrf
            <div class="categories-box">
                <div class="presentation">
                    Choisir une catégorie
                </div>
                <div>
                    @if($errors->has('category'))
                    <div class="error-box">
                        <small><i class="fa fa-times" aria-hidden="true"></i> {{$errors->first('category')}}</small>
                    </div>
                    @endif
                    <div class="categories">         
                        @foreach ($categories as $enName => $frName)
                        <div>
                            <label for="{{$enName}}">
                                <input type="radio" id="{{$enName}}" name="category" class="category">
                                
                                <span>{{$frName}}</span>
                            </label>
                        </div>
                        @endforeach
                    </div>
                </div>
            </div>


            <div class="uk-margin">
                @if($errors->has('title'))
                <div class="error-box">
                    <small><i class="fa fa-times" aria-hidden="true"></i> {{$errors->first('title')}}</small>
                </div>
                @endif
                <div class="input-and-characters-num">
                    <input class="uk-input post-title" name="title" type="text" maxlength="{{$maxChars}}"
                        placeholder="Titre du projet">
                    <div class="characters-num" id="charNum">{{$maxChars}}</div>
                </div>
            </div>

            <div class="uk-margin">
                @if($errors->has('thumbnail'))
                <div class="error-box">
                    <small><i class="fa fa-times" aria-hidden="true"></i> {{$errors->first('thumbnail')}}</small>
                </div>
                @endif <div class="thumbnail-box">

                    <label for="thumbnail" class="thumbnail-label">
                        <i class="fa fa-cloud-upload" aria-hidden="true"></i>
                        ajouter une image thumnail pour votre projet !
                        <input type="file" id="thumbnail" name="thumbnail" class="thumbnail">
                        <div id="image_preview">
                        </div>
                    </label>
                </div>
            </div>

            <div class="uk-margin inputs-box">
                <div class="presentation">
                    <h4>Liste des besoins</h4>
                    <small>Ajoutez ce dont vous avez besoin pour ce projet</small>
                </div>
                <div class="boxes">

                    @if($errors->has('material.*'))
                    <div class="error-box">
                        <small><i class="fa fa-times" aria-hidden="true"></i> {{$errors->first('material.*')}}</small>
                    </div>

                    @endif

                    @for($i = 1; $i <=3 ; $i++) @php if($i==1){ 
                        
                        $button='material-add-button' ; $icon='fa-plus' ;
                        $placeholder='ex: 5 boîtes en carton' ; 

                    } else { 
                        
                        $button='material-remove-button' ;
                        $icon='fa-times' ; $placeholder='' ; 
                        
                    }
                    
                    @endphp 
                    
                    <div class="input-box" id="input-box-{{$i}}">
                        <input class="uk-input material-input" name="material[]" id="{{$i}}" type="text"
                            placeholder="{{$placeholder}}">

                        <button class="uk-button {{$button}}" type="button" id="btn-{{$i}}"><i class="fa {{$icon}}"
                                aria-hidden="true"></i>
                        </button>
                    </div>

                    @endfor
                </div>

        </div>
//my test 


/*
* @test
*/

    public function the_fields_are_filled()
    {
         
            $user = factory(User::class)->create();
            $project = factory(Project::class)->create();
            $cat = factory(Category::class)->create();
            $material = factory(Material::class, 2)->create();

            $mat1 = Material::find(1);
            $mat2 = Material::find(2);


            // dd($mat1, $mat2);

            //relation between user and projects 
            $user->projects()->save($project);


            // relation between project and user
            $project->user()->associate($user)->save();


            //relation between project and material
            // $project->materials()->save($material);


            //si plusieurs materiaux
            $project->materials()->saveMany([$mat1, $mat2]);


            //relation between material and project
            $mat1->project()->associate($project)->save();
            $mat2->project()->associate($project)->save();
     
            // dd($project->materials->all());

            //relation between project and category
            $project->category()->save($cat);

            //relation between category and project
            $cat->categorizable()->associate($project)->save();



       
// dd($matId = $project->materials->pluck('id'));



// dd($user->projects);





// dd($user->projects);

        $response =  $this->actingAs($user)->post(route('projets.store'),
              [
                    'category' => $project->category->id,
                    'user_id' => $project->user->id, 
                    'title' => $project->title, //pb -> titre déjà pris
                    'thumbnail' =>$project->thumbnail, // pas de thumbnail
                    'material[0]' => $project->materials->pluck('name'), // pas de materiels
                    'content' => $project->content
                
                    ]
               
                ); 


// dump($response);

        $response->assertStatus(302)->assertSessionHasNoErrors();
    }  

I don't know why. Can you help me please?

Activity icon

Replied to Column Not Found: 1054 Unknown Column 'project_id' In 'field List'

@snapey thank's a lot !

Do you have a tip to place foreign key to the good place ?

@aurawindsurfing thank you too for your help !

Activity icon

Replied to Column Not Found: 1054 Unknown Column 'project_id' In 'field List'

@aurawindsurfing still nothing... I don't see the solution...

Activity icon

Replied to Column Not Found: 1054 Unknown Column 'project_id' In 'field List'

@snapey hi!

Here, the Project has many Material.

Activity icon

Replied to Column Not Found: 1054 Unknown Column 'project_id' In 'field List'

@aurawindsurfing Hi !

Sorry, I don't understand that you're tring to say.

Activity icon

Started a new Conversation Column Not Found: 1054 Unknown Column 'project_id' In 'field List'

Hi.

I have this error after running phpunit:

..........E............                                           23 / 23 (100%)

Time: 24.62 seconds, Memory: 28.00 MB

There was 1 error:

1) Tests\Feature\ProjectCreationTest::the_fields_are_filled
Illuminate\Database\QueryException: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'project_id' in 'field list' (SQL: update `materials` set `project_id` = 1, `materials`.`updated_at` = 2019-08-05 22:31:43 where `id` = 2)


But i don't have project_id anywhere. I don't know that is the problem... Can you help me to fix that please ?

Project model

    protected $fillable = [ 'category_id', 'title', 'thumbnail', 'material_id', 'content' ];



    public function materials(){
        return $this->hasMany(Material::class);
    }

Material model


       protected $fillable = [ 'name' ];


    public function project(){
        return $this->belongsTo(Project::class);
    }
Projects migration



        Schema::create('projects', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->unsignedBigInteger('user_id');
            $table->string('title');
            $table->string('thumbnail');
            $table->unsignedBigInteger('material_id');
            $table->longText('content');
            $table->dateTime('created_at');
            $table->dateTime('updated_at')->nullable();


            $table->foreign('user_id')
                  ->references('id')->on('users')
                  ->onDelete('cascade');

            $table->foreign('material_id')
                  ->references('id')->on('materials')
                  ->onDelete('cascade');
        });

Materials migration


Schema::create('materials', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name');
            $table->dateTime('created_at');
            $table->dateTime('updated_at')->nullable();
        });
my actual test:


    public function the_fields_are_filled()
    {
         
            $user = factory(User::class)->create();
            $project = factory(Project::class)->create();
            $cat = factory(Category::class)->create();
            $material = factory(Material::class)->create();


            //relation between user and projects 
            $user->projects()->save($project);

            // relation between project and user
            $project->user()->associate($user)->save();


            //relation between project and material
            $project->materials()->save($material);

            //relation between material and project
            $material->project()->associate($project)->save();
     

            // //relation between project and category
            // $project->category()->save($cat);

            // //relation between category and project
            // $cat->categorizable()->associate($project)->save();


            dd($material->project);


// dd($user->projects);

}

project factory


<?php

/* @var $factory \Illuminate\Database\Eloquent\Factory */
use App\Project;
use Faker\Generator as Faker;

$factory->define(Project::class, function (Faker $faker) {


    return [
        'user_id' => function () {
            return factory(App\User::class)->create()->id;
        },
        'title' => $faker->sentence,
        'thumbnail' =>$faker->image('public/images/',640,480, null, false),
        'material_id'=> function () {
            return factory(App\Material::class)->create()->id;
        },
        'content' => $faker->text()
    ];
});

material factory


<?php

/* @var $factory \Illuminate\Database\Eloquent\Factory */

use App\Material;
use Faker\Generator as Faker;

$factory->define(Material::class, function (Faker $faker) {

    return [
        'name' =>'4 cuillère de miel'
    ];
});

Activity icon

Started a new Conversation Problem To Display Array With Polymorphic Relation

Hello everyone.

I have a problem to display the post and the relations with its relations.

I wrote this code :

//my test:


      $project = factory(Project::class);

        // $users = factory(App\User::class, )
        //    ->create()
        //    ->each(function ($user) {
        //         $user->posts()->save(factory(App\Post::class)->make());
        //     });

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

           $userp =  $user->projects()->save(factory(Project::class)->make());

            // dd($userp);

            $pro = $userp->category()->save(factory(Category::class)->make());

dd($pro);            


$response =  $this->actingAs($user)->post(route('projets.store'),
              [
                    'category' => $pro->categorizable_id,
                    'user_id' => $pro->user_id,
                    'title' => $pro->title,
                    'thumbnail' =>$pro->thumbnail,
                    'material_id' => $pro->material_id,
                    'content' => $pro->content
                
                    ]
               
                ); 



result of dd($pro) after running phpunit

// result of phpunit

#fillable: []
  #connection: "mysql"
  #table: null
  #primaryKey: "id"
  #keyType: "int"
  +incrementing: true
  #with: []
  #withCount: []
  #perPage: 15
  +exists: true
  +wasRecentlyCreated: true
  #attributes: array:7 [
    "fr_name" => "quidem"
    "en_name" => "cum"
    "categorizable_id" => 1
    "categorizable_type" => "App\Project"
    "updated_at" => "2019-08-05 19:17:26"
    "created_at" => "2019-08-05 19:17:26"
    "id" => 1
  ]
  #original: array:7 [
    "fr_name" => "quidem"
    "en_name" => "cum"
    "categorizable_id" => 1
    "categorizable_type" => "App\Project"
    "updated_at" => "2019-08-05 19:17:26"
    "created_at" => "2019-08-05 19:17:26"
    "id" => 1
  ]
  #changes: []
  #casts: []
  #dates: []
  #dateFormat: null
  #appends: []
  #dispatchesEvents: []
  #observables: []
  #relations: []
  #touches: []
  +timestamps: true
  #hidden: []
  #visible: []
  #guarded: array:1 [
    0 => "*"
  ]



I don't have all my relations between project, category and user...

Can you help me please ?

Thank you a lot.

Activity icon

Replied to Session Has Unexpected Errors:

@aurawindsurfing Thank ! I understand my error ! Thank you a lot ;D

Activity icon

Replied to Session Has Unexpected Errors:

@aurawindsurfing thank you I'll check that !

Aug
04
3 months ago
Activity icon

Replied to Session Has Unexpected Errors:

@aurawindsurfing hi. I have this error.

1) Tests\Feature\ProjectCreationTest::the_fields_are_filled
Illuminate\Validation\ValidationException: The given data was invalid.

I read your last sentence: "You are only testing the last project with this piece of code:"

I not sure to understand... how I can do ?

Activity icon

Started a new Conversation Session Has Unexpected Errors:

Hello again.

I have a problem for my second test. I trying to test, for this time, that all my fields are filled.

I have this error in my console:

PHPUnit 7.5.13 by Sebastian Bergmann and contributors.

..........F.............                                          24 / 24 (100%)

Time: 4.55 minutes, Memory: 28.00 MB

There was 1 failure:

1) Tests\Feature\ProjectCreationTest::the_fields_are_filled
Session has unexpected errors: 

[
    "Il semblerait que ce titre soit déjà pris",
    "Le titre doit est composé d'au moins 10 caractères",
    "The thumbnail must be an image.",
    "The material field is required.",
    "Vous devez inscrire au moins un matériel pour ce projet"
]
Failed asserting that true is false.

/var/www/html/goshr/vendor/laravel/framework/src/Illuminate/Foundation/Testing/TestResponse.php:991
/var/www/html/goshr/tests/Feature/ProjectCreationTest.php:68
/home/audrey/.composer/vendor/phpunit/phpunit/src/TextUI/Command.php:201
/home/audrey/.composer/vendor/phpunit/phpunit/src/TextUI/Command.php:160


My factory seems to be O.K.

<?php

/* @var $factory \Illuminate\Database\Eloquent\Factory */
use App\Project;
use Faker\Generator as Faker;

$factory->define(Project::class, function (Faker $faker) {


    return [
        'user_id' => function () {
            return factory(App\User::class)->create()->id;
        },
        'title' => $faker->word(4),
        'thumbnail' =>$faker->image('public/images/',640,480, null, false),
        'material_id'=> function () {
            return factory(App\Material::class)->create()->id;
        },
        'content' => $faker->text()
    ];
});

and my test too


    /**
     * Fields are filled.
     *
     * @return void
     * @test
     */
    public function the_fields_are_filled()

    {


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


    $projects = factory(Project::class, 3)
           ->create()
           ->each(function ($project) {
                $project->category()->save(factory(Category::class)->make());
            });


        foreach($projects as $project){
            
            $response =  $this->actingAs($user)->post(route('projets.store'),[
            'category' => $project->category->id ,
            'user_id' => $project->user_id,
            'title' => $project->title,
            'thumbnail' =>$project->thumbnail,
            'material_id' => $project->material_id,
            'content' => $project->content
             
        ]);
        }

        

        $response->assertStatus(302)->assertSessionHasNoErrors();

    }

I'm not sure but I'm think my loop is the problem, but it seems to be neccesary.

Do you know why my test isn't true ?

Thank by advance.

Activity icon

Replied to Unit/Feature Test : Test If Radio Button Is Checked Or Not .

@mikenewbuild I find I found solution for this test (below )

        /**
     * The field category is missing
     *
     * @return void
     * @test
     */
    public function the_field_category_is_missing()

    {


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


    $projects = factory(Project::class, 3)
           ->create()
           ->each(function ($project) {
                $project->category()->save(factory(Category::class)->make());
            });


        foreach($projects as $project){
            $response =  $this->actingAs($user)->post(route('projets.store'),[
            'category' => NULL ,
            'user_id' => $project->user_id,
            'title' => $project->title,
            'thumbnail' =>$project->thumbnail,
            'material_id' => $project->material_id,
            'content' => $project->content
             
        ]);
        }

        

        $response->assertStatus(302)->assertSessionHasErrors(['category' => 'Votre projet doit être classé dans une catégorie']);

    }

Than you a lot for your help, hoping my solution is the good one.

Activity icon

Replied to ErrorException: Array_keys() Expects Parameter 1 To Be Array, Object Given

@devk oh yes, Thank you ! I corrected my errors :)

Activity icon

Started a new Conversation ErrorException: Array_keys() Expects Parameter 1 To Be Array, Object Given

Hi there.

I'm trying to do some tests for post creation. I have an error:

PHPUnit 7.5.13 by Sebastian Bergmann and contributors.

..........E............                                           23 / 23 (100%)

Time: 26.65 seconds, Memory: 28.00 MB

There was 1 error:

1) Tests\Feature\ProjectCreationTest::the_fields_are_filled
ErrorException: array_keys() expects parameter 1 to be array, object given

/var/www/html/goshr/vendor/fzaninotto/faker/src/Faker/Provider/Base.php:195
/var/www/html/goshr/vendor/fzaninotto/faker/src/Faker/Provider/Base.php:234
/var/www/html/goshr/vendor/fzaninotto/faker/src/Faker/Generator.php:222
/var/www/html/goshr/vendor/fzaninotto/faker/src/Faker/Generator.php:279
/var/www/html/goshr/database/factories/CategoryFactory.php:32
/var/www/html/goshr/vendor/laravel/framework/src/Illuminate/Database/Eloquent/FactoryBuilder.php:273
/var/www/html/goshr/vendor/laravel/framework/src/Illuminate/Database/Eloquent/FactoryBuilder.php:292
/var/www/html/goshr/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Concerns/GuardsAttributes.php:122
/var/www/html/goshr/vendor/laravel/framework/src/Illuminate/Database/Eloquent/FactoryBuilder.php:300
/var/www/html/goshr/vendor/laravel/framework/src/Illuminate/Database/Eloquent/FactoryBuilder.php:219
/var/www/html/goshr/tests/Feature/ProjectCreationTest.php:62
/var/www/html/goshr/vendor/laravel/framework/src/Illuminate/Support/Collection.php:475
/var/www/html/goshr/tests/Feature/ProjectCreationTest.php:63
/home/audrey/.composer/vendor/phpunit/phpunit/src/TextUI/Command.php:201
/home/audrey/.composer/vendor/phpunit/phpunit/src/TextUI/Command.php:160

ERRORS!
Tests: 23, Assertions: 69, Errors: 1.

I don't see my error... can you help me please?

Thank you by advance.


//my CategorFactory


<?php

/* @var $factory \Illuminate\Database\Eloquent\Factory */

use App\Category;
use App\Project;
use App\Tip;
use Faker\Generator as Faker;

$factory->define(Category::class, function (Faker $faker) {


    $categorizable = [
        App\Project::class,
        App\Tip::class,
    ];

    $categorizableType = $faker->randomElement($categorizable);
    $categorizable = factory($categorizableType)->create();


    return [
            'fr_name' => $faker->word(),
            'en_name' => $faker->word(),
            'categorizable' => $categorizable->id,
            // 'categorizable_id' => function () {
            //     return factory(Project::class)->create()->id;
            // },
            // 'categorizable_type' =>  function (array $post) {
            //     return Project::find($post['projects.id'])->type;
            // },
            'categorizable_type' => $faker->randomElement($categorizable)
    ];

});

//my Tip Factory

<?php

/* @var $factory \Illuminate\Database\Eloquent\Factory */

use App\Tip;
use App\User;
use Faker\Generator as Faker;

$factory->define(Tip::class, function (Faker $faker) {
    return [
        'user_id' => function () {
            return factory(App\User::class)->create()->id;
        },
        'content' => $faker->text()
    ];
});

///my Project Factory


<?php

/* @var $factory \Illuminate\Database\Eloquent\Factory */
use App\Project;
use Faker\Generator as Faker;

$factory->define(Project::class, function (Faker $faker) {


    return [
        'user_id' => function () {
            return factory(App\User::class)->create()->id;
        },
        'title' => $faker->word(4),
        'thumbnail' =>$faker->image('public/images/',640,480, null, false),
        'material_id'=> function () {
            return factory(App\Material::class)->create()->id;
        },
        'content' => $faker->text()
    ];
});

finally, my test


    /**
     * Fields are filled.
     *
     * @return void
     * @test
     */
    public function the_fields_are_filled()

    {


    //      $users = factory(User::class, 3)
    //     ->create()
    //     ->each(function ($user) {
    //          $user->projects()->save(factory(Project::class)
    //     ->create()
    //     ->each(function ($project) {
    //         $project->category()->save(factory(Category::class)
    //    ->create());
    //     })
    
    // );
    //      });

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


    $projects = factory(Project::class, 3)
           ->create()
           ->each(function ($project) {
                $project->category()->save(factory(Category::class)->make());
            });


        $response =  $this->actingAs($user)->post(route('projets.store'),[
            'category' => 1 ,
            'user_id' => $project->user_id,
            'title' => $project->title,
            'thumbnail' =>$project->thumbnail,
            'material_id' => $project->material_id,
            'content' => $project->content
             
        ]);

        $response->assertStatus(302);

    }
Activity icon

Replied to Unit/Feature Test : Test If Radio Button Is Checked Or Not .

@mikenewbuild hi. I test your solution but in vain.

It's certainly my fault. I didn't precise my problem.

It edited above.

Aug
03
3 months ago
Activity icon

Started a new Conversation What Test Choose Between Unit , Feature And Dusk Test ?

Hi there,

I have doubts about different tests that Laravel offers. How to know what type of test to use, especially between Feature Test and Dusk test ?

My last question is : Is it necessary to create unit test ? I don't know how to apply that because I use actually my Feature Test...

Thank you by advance !

Activity icon

Replied to Unit/Feature Test : Test If Radio Button Is Checked Or Not .

@mikenewbuild hi. I edited my problem.

The route is called route('projets.store').

If I execute $this->withoutExceptionHandling, I have this error:

1) Tests\Feature\ProjectCreationTest::all_fields_are_empty
Illuminate\Validation\ValidationException: The given data was invalid.


I don't know why..

Activity icon

Started a new Conversation Unit/Feature Test : Test If Radio Button Is Checked Or Not .

Hi there.

I'm trying to do test on a form. I want to test if, there a radio button is not checked, the errors displayed.

Actually. My test fails.

//my database structure:



categories
____________

-id
-name
-categorizable_id
-categorizable_type



projects
_________

-id
-user_id
-title
-thumbnail
-material_id
-content



materials
__________

-id
-name


users
______

-id
-name
-firstname
-email


In my categories table, there are already 6 pre-defined/written categories.

// html code


<div>
                    @if($errors->has('category'))
                    <div class="error-box">
                        <small><i class="fa fa-times" aria-hidden="true"></i> {{$errors->first('category')}}</small>
                    </div>
                    @endif
                    <div class="categories">         
                        @foreach ($categories as $enName => $frName)
                        <div>
                            <label for="{{$enName}}">
                                <input type="radio" id="{{$enName}}" name="category[]" class="category">
                                
                                <span>{{$frName}}</span>
                            </label>
                        </div>
                        @endforeach
                    </div>
                </div>
//my category factory:

<?php

/* @var $factory \Illuminate\Database\Eloquent\Factory */

use App\Category;
use Faker\Generator as Faker;

$factory->define(Category::class, function (Faker $faker) {


    return [
            'fr_name' => $faker->word(),
            'en_name' => $faker->word(),
            'categorizable_id' => function () {
                return factory(App\Project::class)->make()->id;
            },
            'categorizable_type' => function (array $cat) {
                return App\Project::find($cat['project_id'])->type;
            }
    ];

});

//my project factory

<?php

/* @var $factory \Illuminate\Database\Eloquent\Factory */
use App\Project;
use Faker\Generator as Faker;

$factory->define(Project::class, function (Faker $faker) {


    return [
        'user_id' => function () {
            return factory(App\User::class)->create()->id;
        },
        'title' => $faker->word(4),
        'thumbnail' =>$faker->image('public/images/',640,480, null, false),
        'material_id'=> function () {
            return factory(App\Material::class)->create()->id;
        },
        'content' => $faker->text()
    ];
});

my test

    public function all_fields_are_empty()
    {
        $user = factory('App\User')->make();

 

        $project = factory('App\Project')->create();

            $response =  $this->actingAs($user)->post(route('projets.store'),[

                'category' => [],
                'title' => NULL,
                'thumbnail' => NULL,
                'material[]' =>NULL,
                'content' => NULL
                 
            ]);

        $response->assertSessionHasErrors('category', 'title', 'material[]', 'content');
    }
//errors
...........F............                                          24 / 24 (100%)

Time: 19.76 seconds, Memory: 28.00 MB

There was 1 failure:

1) Tests\Feature\ProjectCreationTest::all_fields_are_empty
Session missing error: category
Failed asserting that false is true.

/var/www/html/goshr/vendor/laravel/framework/src/Illuminate/Foundation/Testing/TestResponse.php:933
/var/www/html/goshr/tests/Feature/ProjectCreationTest.php:85
/home/audrey/.composer/vendor/phpunit/phpunit/src/TextUI/Command.php:201
/home/audrey/.composer/vendor/phpunit/phpunit/src/TextUI/Command.php:160

FAILURES!
Tests: 24, Assertions: 72, Failures: 1.


Can you enlighthen me please?

Thank by advance.

Aug
02
3 months ago
Activity icon

Replied to Refresh Only A Table Of Database During Testing

I found. I finnaly use duplicate my database for the test only.

Activity icon

Started a new Conversation Refresh Only A Table Of Database During Testing

Hi there.

Is it possible to do a use Refresh Database only on one table?

Thank by advance.

Activity icon

Replied to How To Count The Number Of Input There Are Name='*' ?

@bobbybouwmann hi I apologize for not having given news recently.

So my actual blade code is bellow

<div class="boxes">

                    @if($errors->has('material.*'))
                    <div class="error-box">
                        <small><i class="fa fa-times" aria-hidden="true"></i> {{$errors->first('material.*')}}</small>
                    </div>

                    @endif

                    @for($i = 1; $i <=3 ; $i++) @php if($i==1){ 
                        
                        $button='material-add-button' ; $icon='fa-plus' ;
                        $placeholder='ex: 5 boîtes en carton' ; 

                    } else { 
                        
                        $button='material-remove-button' ;
                        $icon='fa-times' ; $placeholder='' ; 
                        
                    }
                    
                    @endphp 
                    
                    <div class="input-box" id="input-box-{{$i}}">
                        <input class="uk-input material-input" name="material[]" id="{{$i}}" type="text"
                            placeholder="{{$placeholder}}">

                        <button class="uk-button {{$button}}" type="button" id="btn-{{$i}}"><i class="fa {{$icon}}"
                                aria-hidden="true"></i>
                        </button>
                    </div>

                    @endfor
                </div>

in my requests/projectcreation.php

 public function rules()
    {
        return [
            
        'category' => 'required',
        'title' => 'required|unique:posts|min:10|max:80',
        'thumbnail' =>'nullable|image|max:5000',
        'material' => 'required|array|min:1', // je précise ici que "material" doit être un tableau,  qu'il doit être requis et  qu'il doit compté au moins 1 élément.
        'material.*' => 'nullable|alpha_num|between:3,200|distinct', // je dis que pour tous les valeurs dans ce tableau peuvent être nulles, de type string, faire au minimum 3 caractères et unique
        'material.0' =>'required', // je dis que le champ 0 doit être requis
        'detail' => 'required|min:10'

        ];

    }

and finally in my controller.php

  public function store(ProjectCreation $request){

        $validatedData = $request->validated();


}

I have 3 fields. I want that at least of one is required, but It can be the 1st field, the 2nd field or the 3rd field.

But now, the problem is with the piece of code your given, and if I filled a field 0, I will have error that the field.1 must by present. If I filled the field.1 , I will have error that the field.2 must by present etc...

For resume, I could like to fill any field and not neccesarely the first field.

Sorry for my bad english, I trying to do understand myself...

Jul
31
3 months ago
Activity icon

Replied to How To Count The Number Of Input There Are Name='*' ?

@bobbybouwmann hi, thank for your help. But the errors still here.

it is required to fill all the fields accorting to the error

Activity icon

Started a new Conversation How To Count The Number Of Input There Are Name='*' ?

It's me again.

Someone can you tell me how to count the number of input in a form wich are name="*"?

for example

<input type="text" name="toto" />


How to have total ?

I trying to do that for my validation.

I want for aming all inputs with the name="material[]" , at least one of them is required.

I tryed that with basic Laravel's validations rules

'material' => 'required|array|min:1',
'material.*' => 'required_without_all:material.*|string|between:3,200|distinct'


but the error is still here

 The material.0 field is required when none of material.0 are present.

Thank you by advance.

Activity icon

Replied to Problem With Required Field

@hakhsin Hi ! Thank a lot I find the solution :D

Activity icon

Started a new Conversation Problem With Required Field

Hi everyone. I need your help with my validation.

I have dynamical fields named material[]. By default, there are 3 fieds but the users can add or remove.

I'm trying to do my validation but in vain.

I want that least of one field make required. The others can be optional.

But after complete field, I still have the error The material[] field is required when none of material[] are present.

Can you help me please ? Thank you a lot by advance !

//my blade.php


<div class="boxes">

                    @if($errors->has('material[]'))
                    <div class="error-box">
                        <small><i class="fa fa-times" aria-hidden="true"></i> {{$errors->first('material[]')}}</small>
                    </div>

                    @endif

                    @for($i = 1; $i <=3 ; $i++) @php if($i==1){ 
                        
                        $button='material-add-button' ; $icon='fa-plus' ;
                        $placeholder='ex: 5 boîtes en carton' ; 

                    } else { 
                        
                        $button='material-remove-button' ;
                        $icon='fa-times' ; $placeholder='' ; 
                        
                    }
                    
                    @endphp 
                    
                    <div class="input-box" id="input-box-{{$i}}">
                        <input class="uk-input material-input" name="material[]" id="{{$i}}" type="text"
                            placeholder="{{$placeholder}}">

                        <button class="uk-button {{$button}}" type="button" id="btn-{{$i}}"><i class="fa {{$icon}}"
                                aria-hidden="true"></i>
                        </button>
                    </div>

                    @endfor
                </div>

//my validation request : Requests/ProjectCreation.php


<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class ProjectCreation extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    public function messages(){

     return [
                'category.required' => 'Votre projet doit être classé dans une catégorie',
                'title.required' => 'Oups! Il manque un titre à votre projet',
                'title.unique' => 'Il semblerait que ce titre soit déjà pris',
                'title.min' => 'Le titre doit est composé d\'au moins :min caractères',
                'title.max' => 'Le titre est trop long',
                // 'material[].required_without_all' => 'Saisissez au moins un matériel',
                'material[].between' => 'Ce champ doit contenir entre :min et :max caractères',
                'detail.required' => 'Il manque du contenu pour ce projet'
        ];
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            
            'category' => 'required',
            'title' => 'required|unique:posts|min:10|max:80',
            'thumbnail' =>'nullable|image|max:5000',
            'material[]' =>'between:3,200|required_without_all:material[]',
            'detail' => 'required|min:10'
        ];

    }
}

my ProjectController.php


/**
 * Store the incoming blog post.
 *
 * @param  ProjectCreation  $request
 * @return Response
 */
    public function store(ProjectCreation $request){

        $validatedData = $request->validated();


    }