mostafalaravel

mostafalaravel

Member Since 2 Years Ago

Experience Points
18,330
Total
Experience

1,670 experience to go until the next level!

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

  • Complete a lesson — 100pts
  • Create a forum thread — 50pts
  • Reply to a thread — 10pts
  • Leave a reply that is liked — 50pts
  • Receive a "Best Reply" award — 500pts
Lessons Completed
1
Lessons
Completed
Best Reply Awards
0
Best Reply
Awards
  • start-engines Created with Sketch.

    Start Your Engines

    Earned once you have completed your first Laracasts lesson.

  • first-thousand Created with Sketch.

    First Thousand

    Earned once you have earned your first 1000 experience points.

  • 1-year Created with Sketch.

    One Year Member

    Earned when you have been with Laracasts for 1 year.

  • 2-years Created with Sketch.

    Two Year Member

    Earned when you have been with Laracasts for 2 years.

  • 3-years Created with Sketch.

    Three Year Member

    Earned when you have been with Laracasts for 3 years.

  • 4-years Created with Sketch.

    Four Year Member

    Earned when you have been with Laracasts for 4 years.

  • 5-years Created with Sketch.

    Five Year Member

    Earned when you have been with Laracasts for 5 years.

  • school-session Created with Sketch.

    School In Session

    Earned when at least one Laracasts series has been fully completed.

  • welcome-newcomer Created with Sketch.

    Welcome To The Community

    Earned after your first post on the Laracasts forum.

  • full-time-student Created with Sketch.

    Full Time Learner

    Earned once 100 Laracasts lessons have been completed.

  • pay-it-forward Created with Sketch.

    Pay It Forward

    Earned once you receive your first "Best Reply" award on the Laracasts forum.

  • subscriber-token Created with Sketch.

    Subscriber

    Earned if you are a paying Laracasts subscriber.

  • lifer-token Created with Sketch.

    Lifer

    Earned if you have a lifetime subscription to Laracasts.

  • lara-evanghelist Created with Sketch.

    Laracasts Evangelist

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

  • chatty-cathy Created with Sketch.

    Chatty Cathy

    Earned once you have achieved 500 forum replies.

  • lara-veteran Created with Sketch.

    Laracasts Veteran

    Earned once your experience points passes 100,000.

  • 10k-strong Created with Sketch.

    Ten Thousand Strong

    Earned once your experience points hits 10,000.

  • lara-master Created with Sketch.

    Laracasts Master

    Earned once 1000 Laracasts lessons have been completed.

  • laracasts-tutor Created with Sketch.

    Laracasts Tutor

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

  • laracasts-sensei Created with Sketch.

    Laracasts Sensei

    Earned once your experience points passes 1 million.

  • top-50 Created with Sketch.

    Top 50

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

Level 4
18,330 XP
Jan
17
4 days ago
Activity icon

Started a new Conversation How To Set Focus To The First Child Element Of A Specific Div?

Hello ;

I have one div Element with id="nav-group" which contains another child element input type='text'

 <div aria-labelledby="nav-group-tab" class="tab-pane fade show active" id="nav-group" role="tabpanel">

I'm wondering how to set focus to that child Input not by Id but by position (First) ?

Thanks

Jan
15
6 days ago
Activity icon

Replied to Why I Have Duplicate Key Error Even If My Table Does Not Have This Id ?

I found it !

the problem is in postgresql : the id values was not sync with the Pkeys.

the solution to synchronize this is to exec this request :

SELECT setval(pg_get_serial_sequence('tbl', 'tbl_id'), max(tbl_id)) FROM tbl;

tbl: table name
tbl_id : id name
Activity icon

Started a new Conversation Why I Have Duplicate Key Error Even If My Table Does Not Have This Id ?

This is the error message :

Unique violation: 7 ERROR: duplicate key value violates unique constraint "competences_pkey"↵DETAIL: Key (id)=(5) already exists. (SQL: insert into "competences" ("category_id", "user_id", "objective_level", "current_level", "target_date", "obtained_date", "comment", "updated_at", "created_at") values (13, 503, 1, 1, 2020-01-15, 2020-01-15, etst, 2020-01-15 11:20:34, 2020-01-15 11:20:34) returning "id")"

First : before I did some manual deletes from that table in DB directly through PhpPgAdmin (Psql)

Second: when I check this table competences I don't see any record with Id = 5 ! before there was one with id=5 which I deleted manually

Is it possible to "refresh" competences_pkey to be exact to what this table contains ?

note : the auto-increment works because with every request the duplicated key(id) increase

Activity icon

Started a new Conversation How To Filter An Array ?

Hello ,

I have the array bellow :

  0 => array:10 [▼
    "id" => -1
    "category" => array:5 [▶]
    "user_id" => 1
    "competenceName" => "Accounting process"
    "category_id" => 89
    "objective_level" => 0
    "current_level" => 0
    "target_date" => "2020-01-14"
    "obtained_date" => "2020-01-14"
    "comment" => ""
  ]
  1 => array:10 [▼
    "id" => -2
    "category" => array:5 [▶]
    "user_id" => 1
    "competenceName" => "Company Management"
    "category_id" => 90
    "objective_level" => 0
    "current_level" => 0
    "target_date" => "2020-01-14"
    "obtained_date" => "2020-01-14"
    "comment" => ""
  ]
  2 => array:10 [▶]

Is it possible to filter this array by competenceName and comment using something similar to like and % (case insensitive)?

Jan
14
1 week ago
Activity icon

Replied to How To Filter A Collection ?

@bugsysha I cant do it through query , because I merged another collection to the origin one returned by query .

        foreach ($emptyCategoryModel as $category){

            if (!$competences->get()->contains('category_id',$category["category_id"])){
                $finalCompetences->push($category);
            };

        }

                return [
                    "data" => $finalCompetences,
                    "total" => $finalCompetences->count(),
                ];
Activity icon

Started a new Conversation How To Filter A Collection ?

Hello ,

I would like to filter my results by competenceName OR comment using LIKE statement

something like :

  $finalCompetences->where('competenceName','like','%BOM%')
                     ->orwhere('comment','like','%BOM%');
 

but it returns empty result (the key "BOM" exists in competenceName values

My actual code:

 return [
                    "data" => $finalCompetences,
                    "total" => $finalCompetences->count(),
                ];

the results:


  "data": [
    {
      "id": 6,
      "category_id": 17,
      "user_id": 1,
      "objective_level": 4,
      "current_level": 4,
      "target_date": "2021-11-28",
      "obtained_date": "2022-10-14",
      "comment": "",
      "created_at": "2020-01-08 10:06:28",
      "updated_at": "2020-01-08 10:06:28",
      "name": null,
      "competenceName": "Hierarchy Building & BOM (Bill of Material)",
      "category": {
        "id": 17,
        "competence": "Hierarchy Building & BOM (Bill of Material)",
        "created_at": "2020-01-08 09:53:55",
        "updated_at": "2020-01-08 09:53:55",
        "wheel_id": 10
      }
    },
    {
      "id": 15,
      "category_id": 25,
      "user_id": 1,
      "objective_level": 3,
      "current_level": 1,
      "target_date": "2020-06-01",
      "obtained_date": "2022-10-08",
      "comment": null,
      "created_at": "2020-01-08 10:06:28",
      "updated_at": "2020-01-10 16:20:55",
      "name": null,
      "competenceName": "Walkdown (WSD)",
      "category": {
        "id": 25,
        "competence": "Walkdown (WSD)",
        "created_at": "2020-01-08 09:53:55",
        "updated_at": "2020-01-08 09:53:55",
        "wheel_id": 10
      }
    },
Activity icon

Started a new Conversation How To Merge Two Collections With A Specific Condition?

I have Two collections competences and coCompetences those collections look like :

competence :

 ...
    {
      "id": 6,
      "category_id": 17,
      "user_id": 1,
      "objective_level": 4,
      "current_level": 4,
      "target_date": "2021-11-28",
      "obtained_date": "2022-10-14",
      "comment": "",
      "created_at": "2020-01-08 10:06:28",
      "updated_at": "2020-01-08 10:06:28",
      "name": null,
      "competenceName": "Hierarchy Building & BOM (Bill of Material)",
      "category": {
        "id": 17,
        "competence": "Hierarchy Building & BOM (Bill of Material)",
        "created_at": "2020-01-08 09:53:55",
        "updated_at": "2020-01-08 09:53:55",
        "wheel_id": 10
      }
    },
    {
...

coCompetences :

{
    "category": {
      "id": 12,
      "competence": "Criticality Analysis",
      "created_at": "2020-01-08 09:53:55",
      "updated_at": "2020-01-08 09:53:55",
      "wheel_id": 10
    },
    "user_id": 1,
    "competenceName": "Criticality Analysis",
    "category_id": 12,
    "objective_level": 0,
    "current_level": 0,
    "target_date": "2020-01-14",
    "obtained_date": "2020-01-14",
    "comment": ""
  },

I would like to push only coCompetences elements into competences where coCompetences.category_id are not exist in competences.category_id

in another way : add all coCompetences elements to competences except those where coCompetences.category_id already exists in coCompetences.

Activity icon

Replied to How To Add More Attributes To The Collection Results ?

@tykus Thanks

I have another collection competence:

  "data": [
    {
      "id": 6,
      "category_id": 17,
      "user_id": 1,
      "objective_level": 4,
      "current_level": 4,
      "target_date": "2021-11-28",
      "obtained_date": "2022-10-14",
      "comment": "",
      "created_at": "2020-01-08 10:06:28",
      "updated_at": "2020-01-08 10:06:28",
      "name": null,
      "competenceName": "Hierarchy Building & BOM (Bill of Material)",
      "category": {
        "id": 17,
        "competence": "Hierarchy Building & BOM (Bill of Material)",
        "created_at": "2020-01-08 09:53:55",
        "updated_at": "2020-01-08 09:53:55",
        "wheel_id": 10
      }
    },
    {
      "id": 15,
      "category_id": 25,
      "user_id": 1,
      "objective_level": 3,
      "current_level": 1,
      "target_date": "2020-06-01",
      "obtained_date": "2022-10-08",
      "comment": null,
      "created_at": "2020-01-08 10:06:28",
      "updated_at": "2020-01-10 16:20:55",
      "name": null,
      "competenceName": "Walkdown (WSD)",
      "category": {
        "id": 25,
        "competence": "Walkdown (WSD)",
        "created_at": "2020-01-08 09:53:55",
        "updated_at": "2020-01-08 09:53:55",
        "wheel_id": 10
      }
    },

I would like to merge the collection categories(from your solution) to the collection competence(above),

with one condition : merge only elements where category_id does not exists in competence collection

Activity icon

Started a new Conversation How To Add More Attributes To The Collection Results ?

Hello ,

return (category::where('wheel_id','=',$request->input('wheelId'))->get());

the request above returns :


[
  {
    "id": 12,
    "competence": "Criticality Analysis",
    "created_at": "2020-01-08 09:53:55",
    "updated_at": "2020-01-08 09:53:55",
    "wheel_id": 10
  },
  {
    "id": 13,
    "competence": "Equipment Maintenance Plan Building",
    "created_at": "2020-01-08 09:53:55",
    "updated_at": "2020-01-08 09:53:55",
    "wheel_id": 10
  },
  {
    "id": 14,
    "competence": "Equipment Maintenance Plan Optimisation",
    "created_at": "2020-01-08 09:53:55",
    "updated_at": "2020-01-08 09:53:55",
    "wheel_id": 10
  },
.....

I would like to add extra attributes to have something like :

[
  {
    "objective_level": 2,
    "current_level": 2,
    "target_date": "2021-08-07",
    "obtained_date": "2022-10-06",

    "category": {
       "id": 12,
       "competence": "Criticality Analysis",
       "created_at": "2020-01-08 09:53:55",
       "updated_at": "2020-01-08 09:53:55",
       "wheel_id": 10
    }
  },
  {

    "objective_level": 2,
    "current_level": 2,
    "target_date": "2021-08-07",
    "obtained_date": "2022-10-06",

  "category": {
      "id": 13,
      "competence": "Equipment Maintenance Plan Building",
      "created_at": "2020-01-08 09:53:55",
      "updated_at": "2020-01-08 09:53:55",
      "wheel_id": 10
    }
  },
  {
    "objective_level": 2,
    "current_level": 2,
    "target_date": "2021-08-07",
    "obtained_date": "2022-10-06",

    "category": {
       "id": 14,
       "competence": "Equipment Maintenance Plan Optimisation",
       "created_at": "2020-01-08 09:53:55",
       "updated_at": "2020-01-08 09:53:55",
        "wheel_id": 10
     }
  },
.....

As you can see : I embedded the old result in category attribute and added other attributes : "objective_level": 2, "current_level": 2, "target_date": "2021-08-07", "obtained_date": "2022-10-06",

Thanks

Activity icon

Started a new Conversation How To Left_join In Eloquent ?

First here the competence controller :

$competences = Competence::with('category')->orderBy($sorting, $sortOrder);
$competences = $competences->where('user_id', '=', $request->input('memberId'));
...
if ($request->has('wheelId')) {
            $wheelId = $request->input('wheelId');
            $competences = $competences->whereHas('category', function ($query) use ($wheelId) {
                $query->where('wheel_id', '=', $wheelId);
            });
        }

return $competences->paginate($limit);

The code above returns only competences of the 'user_id', '=', $request->input('memberId') where the wheel_id = $request->input('wheelId');

Result example :

  "data": [
    {
      "id": 28,
      "category_id": 9,
      "user_id": 1,
      "objective_level": 4,
      "current_level": 3,
      "target_date": "2021-12-20",
      "obtained_date": "2022-10-14",
      "comment": "abc",
      "created_at": "2020-01-08 10:06:28",
      "updated_at": "2020-01-13 16:54:58",
      "name": null,
      "competenceName": "OEE (Operational Equipment Effectiveness)",
      "category": {
        "id": 9,
        "competence": "OEE (Operational Equipment Effectiveness)",
        "created_at": "2020-01-08 09:53:55",
        "updated_at": "2020-01-08 09:53:55",
        "wheel_id": 9
      }
    }
  ],

Is it possible to show all competences of each wheel even if the user hasn't ?

competence model:

class Competence extends Model
{

    protected $appends = ["competenceName"];

    public function getCompetenceNameAttribute()
    {
        if ($this->category_id == null) return null;
        return category::find($this->category_id)->competence;
    }


    public function category()
    {
        return $this->belongsTo('App\category');
    }


    public function user()
    {
        return $this->belongsTo('App\User');
    }


}

wheel model :

namespace App;

use Illuminate\Database\Eloquent\Model;

class wheel extends Model
{
    public function phone()
    {
        return $this->hasOne('App\Category');
    }
}

category model :

class category extends Model
{
    public function trainings()
    {
        return $this->belongsToMany(training::class);
    }

    public function wheel()
    {
        return $this->belongsTo('App\Wheel');
    }
}

training model :

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

    public function level()
    {
        return $this->belongsTo('App\level');
    }

    public function participants()
    {
        return $this->belongsToMany(User::class, 'participants_training')
            ->select([DB::raw("CONCAT(last_name,' ', first_name) AS name"),
                'last_name', 'first_name'
            ]);
    }

    public function trainers()
    {
        return $this->belongsToMany(User::class, 'trainers_training')
            ->select([
                DB::raw("CONCAT(last_name,' ', first_name) AS name"),
                'last_name', 'first_name'
            ]);

    }
Jan
13
1 week ago
Activity icon

Replied to How To Listen To Parent Component Parameter Changes ?

@bugsysha thanks it works , but how to call a function inside testId() ?

computed: {
    testId() {

    getCompetenceLogs();
        return this.memberId;

    }
}

this gives me Error :

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

Started a new Conversation How To Listen To Parent Component Parameter Changes ?

Hello

I have two components : competences and competence-logs

I call competence-logs from competences.

In competences :

<competence-logs :login-user-id="loginUserId"
                             :member-id="memberId"
                             ref="competenceLogs"
                             v-if="authrzCompetencesEdit"></competence-logs>

In competence-logs :

<p>{{testId}}</p>
<p>{{memberId}}</p>
 

...

        created: function(){
            this.testId = this.memberId;
        },

Problem :

when I change In competences the value of memberId it changes also in <p>{{memberId}}</p> which is normal but <p>{{testId}}</p>``keeps the same value (original value) it seems not updated to thememberId` of the parent component !

Jan
09
1 week ago
Activity icon

Started a new Conversation Custom Command : Ask Password

Hello ,

I'm wondering if it's possible to ask user to type something like password when he run a custom method ?

<?php

namespace App\Console\Commands;

use App\User;
use Illuminate\Console\Command;

class CreateAdminUser extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'create:admin';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Create a new user with admin roles. Be sure you create it following your roles implementation';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $user = User::create([
            'name' => 'Jhon Doe',
            'email' => '[email protected]',
            'password' => bcrypt('password'),
            'admin' => true
        ]);
        if($user){
            $this->info('Admin user successfully created the email is [email protected] and the password is "password" ');
        }
    }
}

Thanks

Activity icon

Replied to How To Login Then Go To Specific Link To Test ?

@sergiu17 I created another DB (original DB dump) just for test

Activity icon

Replied to How To Login Then Go To Specific Link To Test ?

@sergiu17 thanks it works

Is it possible act like a user without create method ? I mean by existing user ?

Activity icon

Replied to How To Login Then Go To Specific Link To Test ?

@sergiu17 Is it possible to specify more attributes in user model when ->create() ?

For example I want to specify that is _admin is true and other attributes too ?

Activity icon

Started a new Conversation How To Login Then Go To Specific Link To Test ?

Hello ,

In my test I would like to login as user then get specific url status !

    public function test_links()
    {

        $this->post('/login', [
            'email'     => '[email protected]',
            'password'  => 'password',
        ])
            ->get('/myprofile')
            ->assertStatus(200);


    }
Jan
08
1 week ago
Activity icon

Started a new Conversation Is It Possible To Test If All Routes Are Redirected To Login Page When User Is Not Logged-id ?

Hello ,

Here bellow I made a test to know if a non-loged user when he request / is redirected to the login page .

the question is : this test is only for / route , is there any way to test the rest of routes without typing theme all ? someting like $this->get('/*') ?

    public function test_if_user_is_not_logged_must_redirect_to_login_page(){
        $this->get('/')
            ->assertStatus(302);
    }

Activity icon

Replied to Eloquent : How To Insert With Non-existing Id In Table.

@nakov

Yes :

    public function up()
    {
        Schema::create('wheels', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name')->nullable();
            $table->timestamps();
        });
    }

then I added another field :

        Schema::table('categories', function (Blueprint $table) {
            $table->integer('wheel_id')->unsigned();
            $table->foreign('wheel_id')->references('id')->on('wheels')
                ->onDelete('cascade');
        });
Activity icon

Started a new Conversation Eloquent : How To Insert With Non-existing Id In Table.

I try to insert data to two tables (wheels, categories) by looping one array ($output).

The two tables have already some rows :

        foreach ($output as $key => $val) {

            $wheel = new wheel();
            $wheel->name = $key;
            $wheel->save();
            $wheelId = $wheel->id;

          

            foreach ($val as $valData) {
                echo $valData . "<br>";
                $category = new category();
                $category->competence = $valData;
                $category->wheel_id = $wheelId;
                $category->save();
            }
            
        }

But I receive the error bellow because of an Id duplication ,

SQLSTATE[23505]: Unique violation: 7 ERROR: duplicate key value violates unique constraint "wheels_pkey" DETAIL: Key (id)=(1) already exists. (SQL: insert into "wheels" ("name", "updated_at", "created_at") values (I-coach , 2020-01-08 09:11:40, 2020-01-08 09:11:40) returning "id")

Question : How to user a non existing ID when I save() ?

Jan
07
2 weeks ago
Activity icon

Started a new Conversation Error : Failed To Open Stream: No Such File Or Directory In ../vendor/composer/autoload_real.php On Line 66

Hello I removed one package using :

composer remove revolution/laravel-google-sheets

and now my application is down , here the error message :

( ! ) Warning: require(/home/vagrant/code/crm/vendor/composer/../phpseclib/phpseclib/phpseclib/bootstrap.php): failed to open stream: No such file or directory in /home/vagrant/code/crm/vendor/composer/autoload_real.php on line 66
Call Stack
#   Time    Memory  Function    Location
1   0.0003  403672  {main}( )   .../index.php:0
2   0.0010  403936  require( '/home/vagrant/code/crm/vendor/autoload.php' ) .../index.php:24
3   0.0017  404616  ComposerAutoloaderInitf897318154619604ea94f9d748dba01a::getLoader( )    .../autoload.php:7
4   0.0214  413024  composerRequiref897318154619604ea94f9d748dba01a( )  .../autoload_real.php:56

I also tried to update : ``composer update` but the problem stills !

Activity icon

Started a new Conversation What's The Best Laravel Package To Read Google Sheet ?

Hello ,

I have a specific google sheet (in url)

I would like to use these file data and I'm wondering which is the best package to do this ?

thanks

Activity icon

Started a new Conversation Vuejs-datepicke Z-index Not Working!

I have a vuejs-datepicke component in v-server-table component which is in collapse element

div.collapse > v-server-table.test-table > span > div.form-group > datepicker

<div :class="{ 'show' : (wheel.id == defaultOpenedWheel || searchKey !== null)}" class="collapse"
   data-parent="#accordion"
   role="tabpanel"
   v-bind:aria-labelledby="'heading-'+index" v-bind:id="'collapse-'+index">
<v-server-table :columns="columnCompetences"
   class="test-table"
   :options="options"
   :show-pagination="false"
   @loaded="onLoaded"
   v-bind:ref="'wheel_'+wheel.id"
   v-bind:url="'/api/competences?wheelId='+wheel.id+'&querySearch='+searchKey+'&memberId='+memberId">
<span slot="target_date" slot-scope="{row}">
   <span v-if="rowToShow !== 'row'+row.id">{{formDate(row.target_date)}}</span>
   <div class="form-group" v-if="rowToShow === 'row'+row.id">
      <datepicker :format="customDateFormat" :input-class="'form-control'"
         v-model="updateRow.target_date"></datepicker>
      <small class="form-text  text-danger"
         v-if="formErrors !== null && formErrors.target_date!==undefined"> {{formErrors.target_date[0]}} </small>
   </div>
</span>

the problem : the datepicker is not completely shown (z-index problem I thinks) and I must to scroll-down !

see the picture : https://i.stack.imgur.com/5oJM2.png

The related class is :

element.style {
}
.vdp-datepicker__calendar {
    position: absolute;
    z-index: 9999 !important;
    background: #fff;
    width: 300px;
    border: 1px solid #ccc;
}

I added the z-index: 9999 !important; but it's not working !

Jan
06
2 weeks ago
Activity icon

Replied to Some Questions About The Laravel Testing

@tray2 yes I have it :


class CreateTeamleaderApisTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('teamleader_apis', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->timestamps();
            $table->string('access_token',1024);
            $table->string('refresh_token',1024);
        });
    }

and other migration to add some fields:

2019_09_08_190030_add_fields_deal_sync_date_to_teamleader_apis.php
2019_09_09_160203_add_fields_task_sync_date_to_teamleader_apis.php
2019_09_11_085549_add_fields_company_sync_date_to_teamleader_apis.php

Activity icon

Replied to Some Questions About The Laravel Testing

@sinnbeck super it works , the only thing I have now is :

1) Tests\Feature\ExampleTest::testBasicTest
Illuminate\Database\QueryException: SQLSTATE[HY000]: General error: 1 no such table: teamleader_apis (SQL: select * from "teamleader_apis" limit 1)

here is my test :

<?php

namespace Tests\Feature;

use App\User;
use Tests\TestCase;
use Illuminate\Foundation\Testing\RefreshDatabase;

class ExampleTest extends TestCase
{
    use RefreshDatabase;
    /**
     * A basic test example.
     *
     * @return void
     */
    public function testBasicTest()
    {
        $this->actingAs(factory(User::class)->create());
        $this->get('/api/trainings')
        ->assertOk();
    }
}

Activity icon

Replied to Some Questions About The Laravel Testing

@sinnbeck no I think the user model has nothing special !

namespace App;

use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Str;
use Spatie\Activitylog\Traits\LogsActivity;

class User extends Authenticatable implements MustVerifyEmail
{
    use SoftDeletes;
    use Notifiable;
    use LogsActivity;
    const VERIFIED_USER = '1';
    const UNVERIFIED_USER = '0';

    const ADMIN_USER = '1';
    const REGULAR_USER = '0';


should I clear any cache ?

Activity icon

Replied to Some Questions About The Laravel Testing

@tray2

I did a simple test unit :

    public function testBasicTest()
    {
        $this->actingAs(factory(User::class)->create());
        $this->get('/api/trainings')
        ->assertOk();
    }

as you can see this will create a user and login ,

but the problem is that user is created in the project database instead of memory sqlite !

PHPunit.xml

<?xml version="1.0" encoding="UTF-8"?>
<phpunit backupGlobals="false"
         backupStaticAttributes="false"
         bootstrap="vendor/autoload.php"
         colors="true"
         convertErrorsToExceptions="true"
         convertNoticesToExceptions="true"
         convertWarningsToExceptions="true"
         processIsolation="false"
         stopOnFailure="false">
    <testsuites>
        <testsuite name="Unit">
            <directory suffix="Test.php">./tests/Unit</directory>
        </testsuite>

        <testsuite name="Feature">
            <directory suffix="Test.php">./tests/Feature</directory>
        </testsuite>
    </testsuites>
    <filter>
        <whitelist processUncoveredFilesFromWhitelist="true">
            <directory suffix=".php">./app</directory>
        </whitelist>
    </filter>
    <php>
        <server name="APP_ENV" value="testing"/>
        <server name="BCRYPT_ROUNDS" value="4"/>
        <server name="CACHE_DRIVER" value="array"/>
        <server name="MAIL_DRIVER" value="array"/>
        <server name="QUEUE_CONNECTION" value="sync"/>
        <server name="SESSION_DRIVER" value="array"/>
        <server name="DB_CONNECTION" value="sqlite"/>
        <server name="DB_DATABASE" value=":memory:"/>
    </php>
</phpunit>

Activity icon

Replied to Some Questions About The Laravel Testing

@tray2 , Should I install it in vagrant ? I use VMbox (homestead)

Activity icon

Started a new Conversation I Found Strange Files Are In The Main Directory !

Hello , I'm wondering why I have these files in the main directory and is it possible to delete them ?

-rwxrwxrwx 1 vagrant vagrant      0 Dec 23 14:36 0220*
-rwxrwxrwx 1 vagrant vagrant      0 Dec 23 14:36 0.system*
-rwxrwxrwx 1 vagrant vagrant      0 Dec 23 14:36 -1*
-rwxrwxrwx 1 vagrant vagrant      0 Dec 23 14:36 1000*
-rwxrwxrwx 1 vagrant vagrant      0 Dec 23 14:36 1024*
-rwxrwxrwx 1 vagrant vagrant      0 Dec 23 14:36 120*
-rwxrwxrwx 1 vagrant vagrant      0 Dec 23 14:36 1.2.11*
-rwxrwxrwx 1 vagrant vagrant      0 Dec 23 14:36 14*
-rwxrwxrwx 1 vagrant vagrant      0 Dec 23 14:36 2*
-rwxrwxrwx 1 vagrant vagrant      0 Dec 23 14:36 20*
-rwxrwxrwx 1 vagrant vagrant      0 Dec 23 14:36 20031129*
-rwxrwxrwx 1 vagrant vagrant      0 Dec 23 14:36 2018.01RC3*
-rwxrwxrwx 1 vagrant vagrant      0 Dec 23 14:36 20180731*
-rwxrwxrwx 1 vagrant vagrant      0 Dec 23 14:36 25*
-rwxrwxrwx 1 vagrant vagrant      0 Dec 23 14:36 2.9.4*
-rwxrwxrwx 1 vagrant vagrant      0 Dec 23 14:36 2M*
-rwxrwxrwx 1 vagrant vagrant      0 Dec 23 14:36 300*
-rwxrwxrwx 1 vagrant vagrant      0 Dec 23 14:36 31.7667*
-rwxrwxrwx 1 vagrant vagrant      0 Dec 23 14:36 320180731*
-rwxrwxrwx 1 vagrant vagrant      0 Dec 23 14:36 32767*
-rwxrwxrwx 1 vagrant vagrant      0 Dec 23 14:36 35.2333*
-rwxrwxrwx 1 vagrant vagrant      0 Dec 23 14:36 4*
-rwxrwxrwx 1 vagrant vagrant      0 Dec 23 14:36 4096K*
-rwxrwxrwx 1 vagrant vagrant      0 Dec 23 14:36 512M*
-rwxrwxrwx 1 vagrant vagrant      0 Dec 23 14:36 533*
-rwxrwxrwx 1 vagrant vagrant      0 Dec 23 14:36 64*
-rwxrwxrwx 1 vagrant vagrant      0 Dec 23 14:36 7.3.6-1+ubuntu18.04.1+deb.sury.
Activity icon

Replied to Some Questions About The Laravel Testing

@alanholmes one more question :

Where do you put the .sqlite file ?

Activity icon

Started a new Conversation Some Questions About The Laravel Testing

Hello ,

question 1 : The testing should be only in local ? no need to make it in production env ?

question 2 : I use psql , so I created a new database my_db_testing which is a copy of my original db and I created a new file .env.testing with same content as .env file except the database name ! is it a correct way to do that ?

Jan
03
2 weeks ago
Activity icon

Started a new Conversation SQLSTATE[HY000] [1045] Access Denied For User 'forge'@'localhost' (using Password: NO)

Hello,

I decided to create .env.testing file to override the .env file for testing .

then , I :php artisan config:cache --env=testing

[email protected]:~/code/crm$ php artisan config:cache --env=testing
Configuration cache cleared!
Configuration cached successfully!

But after that the project is down 'error 500' and every artisan command returns this error message :

SQLSTATE[HY000] [1045] Access denied for user 'forge'@'localhost' (using password: NO) 

It's like the .env does not exists !

I also try to clear cache , but also all clear cache command s returns the same error :

[email protected]:~/code/crm$ php artisan config:clear

   Illuminate\Database\QueryException  : SQLSTATE[HY000] [1045] Access denied for user 'forge'@'localhost' (using password: NO) (SQL: select * from `teamleader_apis` limit 1)

  at /home/vagrant/code/crm/vendor/laravel/framework/src/Illuminate/Database/Connection.php:664
    660|         // If an exception occurs when attempting to run a query, we'll format the error
    661|         // message to include the bindings with SQL, which will make this exception a
    662|         // lot more helpful to the developer instead of just the database's errors.
    663|         catch (Exception $e) {
  > 664|             throw new QueryException(
    665|                 $query, $this->prepareBindings($bindings), $e
    666|             );
    667|         }
    668|

  Exception trace:

  1   App\Console\Commands\DemoCron::__construct()
      [internal]:0

  2   Doctrine\DBAL\Driver\PDOException::("SQLSTATE[HY000] [1045] Access denied for user 'forge'@'localhost' (using password: NO)")
      /home/vagrant/code/crm/vendor/doctrine/dbal/lib/Doctrine/DBAL/Driver/PDOConnection.php:31

  Please use the argument -v to see more details.
Activity icon

Started a new Conversation How To Connect To Psql ? Psql: FATAL: Peer Authentication Failed For User "postgres"

Hello

I try to connect to pgsql via ssh :

[email protected]:~$ psql
psql: FATAL:  role "vagrant" does not exist

And as you can see I got this error message :'psql: FATAL: role "vagrant" does not exist'

I use vm-box in windows OS

Thanks

Activity icon

Replied to Memory Database For Unit Testing

@tray2 no I have only pgrsql

Activity icon

Replied to Memory Database For Unit Testing

@nakov yes it's a local DB not a production ,

I don't have the .env.testing, should I create new one ? with another DB name ?

Activity icon

Replied to Memory Database For Unit Testing

@nakov I did a big mistake !

all my tables are empty !

use App\User;
use Tests\TestCase;
use Illuminate\Foundation\Testing\RefreshDatabase;

class ExampleTest extends TestCase
{
    use RefreshDatabase;
    /**
     * A basic test example.
     *
     * @return void
     */
    public function testBasicTest()
    {
        $this->actingAs(factory(User::class)->create());
        $response = $this->get('/api/trainings')
        ->assertOk();
    }
}

Is there a way to recover the content of tables ?

please help

thanks

Activity icon

Started a new Conversation Memory Database For Unit Testing

Well , bellow is the DB connection param :

DB_CONNECTION=pgsql
DB_HOST=127.0.0.1
DB_PORT=5432
DB_DATABASE=crm
DB_USERNAME=homestead
DB_PASSWORD=secret

I would like to make this test using "memory database" as you can see (phpunit.xml) :

    <php>
        <server name="APP_ENV" value="testing"/>
        <server name="BCRYPT_ROUNDS" value="4"/>
        <server name="CACHE_DRIVER" value="array"/>
        <server name="MAIL_DRIVER" value="array"/>
        <server name="QUEUE_CONNECTION" value="sync"/>
        <server name="SESSION_DRIVER" value="array"/>


        <server name="DB_CONNECTION" value="sqlite"/>
        <server name="DB_DATABASE" value=":memory:"/>


    </php>

But when I run the test bellow :

    public function testBasicTest()
    {
        $this->actingAs(factory(User::class)->create());
        $response = $this->get('/api/trainings')
        ->assertOk();
    }

a new user is created on my database not on the "memory database"

note: the test result is OK,

Activity icon

Replied to Why I Have This Failure ?

@nakov Thanks ,

I would like to know if methods in test class should be camel case or snake case ?

   public function test_user_can_view_a_login_form()
    {
        //
    }

or

   public function testUserCanViewALoginForm()
    {
        //
    }
Activity icon

Replied to Why I Have This Failure ?

ahh okey that's true , I have an auth in /,

is it possible to simulate user name and password in test unit ?

Activity icon

Started a new Conversation Why I Have This Failure ?

 vendor/bin/phpunit
PHPUnit 7.5.17 by Sebastian Bergmann and contributors.

.F                                                                  2 / 2 (100%)

Time: 301 ms, Memory: 18.00 MB

There was 1 failure:

1) Tests\Feature\ExampleTest::testBasicTest
Expected status code 200 but received 302.
Failed asserting that false is true.

/home/vagrant/code/crm/vendor/laravel/framework/src/Illuminate/Foundation/Testing/TestResponse.php:151
/home/vagrant/code/crm/tests/Feature/ExampleTest.php:19

Here the code :

<?php

namespace Tests\Feature;

use Tests\TestCase;
use Illuminate\Foundation\Testing\RefreshDatabase;

class ExampleTest extends TestCase
{
    /**
     * A basic test example.
     *
     * @return void
     */
    public function testBasicTest()
    {
        $response = $this->get('/');

        $response->assertStatus(200);
    }
}
Activity icon

Started a new Conversation Unit Testing Directory

Hello ,

What's the difference between Feature directory and Unit directory ?

// Create a test in the Feature directory...
php artisan make:test UserTest

// Create a test in the Unit directory...
php artisan make:test UserTest --unit

+Thanks

Jan
02
2 weeks ago
Activity icon

Started a new Conversation Why GetChanges() Array Is Always Empty ?

Hello ,

I'm wondering why $competence->getOriginal(); is empty in the code bellow ?

    public function update(Request $request, Competence $competence)
    {

        $originalValues = $competence->getOriginal();

        $competence->obtained_date = $request->get('obtained_date');
        $competence->target_date = $request->get('target_date');
        $competence->comment = $request->get('comment');
        $competence->objective_level = $request->get('objective_level');
        $competence->current_level = $request->get('current_level');

        dd($originalValues,$request->all(),$competence->getChanges());
...
}

the result is :

array:11 [ // $originalValues
  "id" => 204
  "category_id" => 1
  "user_id" => 532
  "objective_level" => 3
  "current_level" => 3
  "target_date" => "2018-11-28"
  "obtained_date" => "2022-08-11"
  "comment" => "Correct descriptio"
  "created_at" => "2019-11-10 22:49:21"
  "updated_at" => "2020-01-02 11:26:56"
  "name" => "Google chrome"
]


array:12 [ //  $request->all()
  "id" => 204
  "category_id" => 1
  "user_id" => 532
  "objective_level" => 4 <---- changed
  "current_level" => 4 <---- changed
  "target_date" => "2018-11-28"
  "obtained_date" => "2022-08-11"
  "comment" => "Correct descriptio"
  "created_at" => "2019-11-10 22:49:21"
  "updated_at" => "2020-01-02 11:26:56"
  "name" => "Google chrome"
  "_method" => "patch"
]


[] //$competence->getChanges()

remark :

        if ($competence->isDirty(["objective_level", "current_level"])) {
            dd("changed");
        }

works without issues !

Dec
31
3 weeks ago
Activity icon

Started a new Conversation How To Redirect To 403 Error Page From JS ?

Hello ,

I would like to redirect the browser to 403 error page if the API result status code is 403

                  })
                    .catch(error => {
                        console.log('error', error.response.status)
                    });

Should I create a get route called 403 , then redirect the browser to it ? or there is another simple way ?

Route::get('403', function () {
    return abort(403);
});

Route::get('404', function () {
    return abort(404);
});
Activity icon

Replied to Is It Possible To Search In An Array Using Collection ?

@grahh

is it the same as :

collect($this->fullTeamDescendants)->contains('user_id',216);