gianmarx

Member Since 6 Months Ago

Pisa

Experience Points
26,570
Total
Experience

3,430 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
163
Lessons
Completed
Best Reply Awards
0
Best Reply
Awards
  • start your engines Created with Sketch.

    Start Your Engines

    Earned once you have completed your first Laracasts lesson.

  • first-thousand Created with Sketch.

    First Thousand

    Earned once you have earned your first 1000 experience points.

  • 1-year Created with Sketch.

    One Year Member

    Earned when you have been with Laracasts for 1 year.

  • 2-years Created with Sketch.

    Two Year Member

    Earned when you have been with Laracasts for 2 years.

  • 3-years Created with Sketch.

    Three Year Member

    Earned when you have been with Laracasts for 3 years.

  • 4-years Created with Sketch.

    Four Year Member

    Earned when you have been with Laracasts for 4 years.

  • 5-years Created with Sketch.

    Five Year Member

    Earned when you have been with Laracasts for 5 years.

  • school-in-session Created with Sketch.

    School In Session

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

  • welcome-newcomer Created with Sketch.

    Welcome To The Community

    Earned after your first post on the Laracasts forum.

  • full-time-student Created with Sketch.

    Full Time Learner

    Earned once 100 Laracasts lessons have been completed.

  • pay-it-forward Created with Sketch.

    Pay It Forward

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

  • subscriber Created with Sketch.

    Subscriber

    Earned if you are a paying Laracasts subscriber.

  • lifer Created with Sketch.

    Lifer

    Earned if you have a lifetime subscription to Laracasts.

  • evangelist Created with Sketch.

    Laracasts Evangelist

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

  • chatty-cathy Created with Sketch.

    Chatty Cathy

    Earned once you have achieved 500 forum replies.

  • lara-veteran Created with Sketch.

    Laracasts Veteran

    Earned once your experience points passes 100,000.

  • 10k-strong Created with Sketch.

    Ten Thousand Strong

    Earned once your experience points hits 10,000.

  • lara-master Created with Sketch.

    Laracasts Master

    Earned once 1000 Laracasts lessons have been completed.

  • laracasts-tutor Created with Sketch.

    Laracasts Tutor

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

  • laracasts-sensei Created with Sketch.

    Laracasts Sensei

    Earned once your experience points passes 1 million.

  • top-50 Created with Sketch.

    Top 50

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

  • Community Pillar

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

Level 6
26,570 XP
Jan
25
17 hours ago
Activity icon

Started a new Conversation MOCK API Test:Error: Call To Undefined Method App\Services\TrelloCardService::_downloadCardsFromBoard()

I wrote the following service:

namespace App\Services;

use App\Services\Api\TrelloCardAPIService;

class TrelloCardService
{
    protected $trelloCardApiService;

    public function __construct(TrelloCardAPIService $trelloCardApiService)
    {
        $this->trelloCardApiService = $trelloCardApiService;
    }
    
}

then a service that calls the API:

<?php


namespace App\Services\Api;

use App\Traits\CardTrait;
use Unirest\Request;

class TrelloCardAPIService
{
    public function call(string $url) {
        $headers = array('Accept' => 'application/json');
        $query = array('key' => env('TRELLO_KEY'), 'token' => env('TRELLO_TOKEN'));
        $r = Request::get($url, $headers, $query);
        return $r->body;
    }

    public function _downloadCardsFromBoard() {
        echo "API downloadCards!\n";
        $url = TRELLO_API_BASE_URL . "/boards/".TRELLO_BOARDS_SPRINT."/cards";
        $res = $this->call($url);
        return $res;
    }

}

then I wrote the test feature:

namespace Tests\Feature;

use App\Services\Api\TrelloCardAPIService;
use App\Services\TrelloCardService;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Foundation\Testing\WithFaker;
use Illuminate\Support\Facades\File;

use Tests\TestCase;

class trelloCardTest extends TestCase
{
    public function test_mock_card()
    {
        $cards = json_decode(File::get("tests/test_data/cards.json"),FALSE);

        $mock = $this->mock(TrelloCardAPIService::class, function ($mock) use ($cards) {
            $mock->shouldReceive('_downloadCardsFromBoard')
                ->once()
                ->andReturn($cards);
        });
        
        //here I print the var mock if I do the DD
        $mockedTrelloCardService = new TrelloCardService($mock);

        $data = $mockedTrelloCardService->_downloadCardsFromBoard();//fail this
        dd($data);//I would like to print $cards
    }
}

give me following error:

Error: Call to undefined method App\Services\TrelloCardService::_downloadCardsFromBoard()
Jan
21
4 days ago
Activity icon

Started a new Conversation Mock Test: Mockery\Exception\BadMethodCallException: Received Mockery_0_App_ClassU_downloadCard::

I wrote this with DI:

 public function test_mock_get_data()
    {
        $this->mock(downloadCard::class, function ($mock) {
            $mock->shouldReceive('_downloadCardsFromBoard()')
                ->once()
                ->andReturn(new Request(
                    File::get('tests/test_data/cards.json'),
                    $status =200,
                    $headers=[],
                ))
                ->andReturnValues(json_decode(File::get('tests/test_data/cards.json'),TRUE));
        });


        $response = $this->artisan('trello-monitor:sync');

    }

give me follwing error:

Mockery\Exception\BadMethodCallException: Received Mockery_0_App_ClassU_downloadCard::_downloadCardsFromBoard(), but no expectations were specified

the artisan command is so done:

 $cards = $this->unirest->_downloadCardsFromBoard($boardId);

        foreach($cards as $index=>$card) {
            echo $index.' of '.count($cards)."\r\n";
            $this->unirest->createCard($card);
        }

essentially if I comment out the line:

// $this->unirest->createCard($card); 

the test passes but the command must be done like this, I don't know how to solve

Activity icon

Replied to Mock \Unirest\Request Laravel

namespace Tests\Unit;

//use PHPUnit\Framework\TestCase;
use Unirest\Request;
use Illuminate\Support\Facades\File;
use Tests\TestCase;
use App\ClassU\Unirest;
use Unirest\Response;


class unirestTest extends TestCase
{
    public function test_mock_get_data()
    {
        $this->withoutExceptionHandling();
        $cards = json_decode(File::get('tests/test_data/cards.json'),TRUE);

        $this->mock(Unirest::class, function ($mock) {
            $mock->shouldReceive('get')
                ->once()
                ->andReturn(new Response(
                    $status =200,
                    $headers=[],
                    json_decode(File::get('tests/test_data/cards.json'),TRUE)
                ));
        });
    }
}

give folowing error :

1) Tests\Unit\unirestTest::test_mock_get_data

ErrorException: explode() expects parameter 2 to be string, array given

@bugsysha

Activity icon

Replied to Mock \Unirest\Request Laravel

namespace Tests\Unit;

//use PHPUnit\Framework\TestCase;
use Unirest\Request;
use Illuminate\Support\Facades\File;
use Tests\TestCase;
use App\ClassU\Unirest;

class unirestTest extends TestCase
{
    public function test_mock_get_data()
    {
        $value = 'get_data';
        $this->mock(Unirest::class, function ($mock) {
            $mock->shouldReceive('get')
                ->once()
                ->andReturn(new Response(
                    $status =200,
                    $headers=[],
                    File::get(base_path('tests/test_data/cards.json'))
                ));
        });
    }
}

give me following error:

There was 1 error:

  1. Tests\Unit\unirestTest::test_mock_get_data Error: Class 'Tests\Unit\Response' not found

/Users/gianmarx/trello/trello-monitor/tests/Unit/unirestTest.php:28 /Users/gianmarx/trello/trello-monitor/vendor/mockery/mockery/library/Mockery/Container.php:229 /Users/gianmarx/trello/trello-monitor/vendor/mockery/mockery/library/Mockery.php:117 /Users/gianmarx/trello/trello-monitor/vendor/laravel/framework/src/Illuminate/Foundation/Testing/Concerns/InteractsWithContainer.php:53 /Users/gianmarx/trello/trello-monitor/tests/Unit/unirestTest.php:33

@bugsysha

Activity icon

Replied to Mock \Unirest\Request Laravel

what i was wondering if i could make a unirest request with laravel's guzzle or http. having said that I would do a class like this:

    namespace App\ClassU;

use Unirest\Request;


class Unirest
{
    public function get_data(string $url) {
        $headers = array('Accept' => 'application/json');
        $query = array('key' => env('TRELLO_KEY'), 'token' => env('TRELLO_TOKEN'));
        $r = Request::get($url, $headers, $query);
        return $r->body;
    }

}

Now how could I mock this class? @bugsysha

Jan
20
5 days ago
Activity icon

Started a new Conversation Mock \Unirest\Request Laravel

I created this method that gives me the get to download the cards on trello:

public function get_data(string $url) {
   
        $headers = array('Accept' => 'application/json');
        $query = array('key' => env('TRELLO_KEY'), 'token' => env('TRELLO_TOKEN'));
        $r = \Unirest\Request::get($url, $headers, $query);
        return $r->body;

    }

I was wondering how I could mock this method in particular of:

\Unirest\Request::get($url, $headers, $query);

I was wondering if it was possible to mocking it with HTTP::fake()

Activity icon

Replied to Validator Error 302 Api With Put

the validator was misspelled and corrected. it's works

Activity icon

Started a new Conversation Validator Error 302 Api With Put

sent the following request to my api

$requestSvr1 = [
        "id_server" => 999,
        "task_available" => ["task11","mptupdatepoi", "mptupdatetrack", "mptupdateroute", "mptdeleteroute","mptdeletepoi"],
        "exclude_instances" => ["romage.org"],
        "accept_instances" => ["mde.org"]
    ];

when I take my request and let the validator work it I get 302.

I don't even get to print the dd

$requestSvr->only(['id_server', 'task_available','accept_instances','exclude_instances']);

        $validator = $requestSvr->validate([
            'id_server' => 'required|string',
            'task_available' => 'required|array',
            'accept_instances'=> 'array',
            'exclude_instances' =>'array'
        ]);
        dd($validator);

        if($validator->fails()){
            return response(['error' => $validator->errors(), 'Validation Error'],400);
        }

dd ($ requestSvr); and I get this:

  #json: null

#convertedFiles: [] #userResolver: Closure($guard = null) {#2894 class: "Illuminate\Auth\AuthServiceProvider" this: Illuminate\Auth\AuthServiceProvider {#83 …} use: { $app: Illuminate\Foundation\Application {#729 …} } file: "./vendor/laravel/framework/src/Illuminate/Auth/AuthServiceProvider.php" line: "105 to 107" } #routeResolver: Closure() {#3972 class: "Illuminate\Routing\Router" this: Illuminate\Routing\Router {#217 …} use: { $route: Illuminate\Routing\Route {#406 …} } file: "./vendor/laravel/framework/src/Illuminate/Routing/Router.php" line: "662 to 664" } +attributes: Symfony\Component\HttpFoundation\ParameterBag {#2896 #parameters: [] } +request: Symfony\Component\HttpFoundation\ParameterBag {#4115 #parameters: array:4 [ "id_server" => 999 "task_available" => array:6 [ 0 => "task11" 1 => "mptupdatepoi" 2 => "mptupdatetrack" 3 => "mptupdateroute" 4 => "mptdeleteroute" 5 => "mptdeletepoi" ] "exclude_instances" => array:1 [ 0 => "romage.org" ] "accept_instances" => array:1 [ 0 => "mde.org" ] ] } +query: Symfony\Component\HttpFoundation\InputBag {#3944 #parameters: [] } +server: Symfony\Component\HttpFoundation\ServerBag {#4126 #parameters: array:17 [ "SERVER_NAME" => "hoqu-laravel.test" "SERVER_PORT" => 80 "HTTP_HOST" => "hoqu-laravel.test" "HTTP_USER_AGENT" => "Symfony" "HTTP_ACCEPT" => "text/html,application/xhtml+xml,application/xml;q=0.9,/;q=0.8" "HTTP_ACCEPT_LANGUAGE" => "en-us,en;q=0.5" "HTTP_ACCEPT_CHARSET" => "ISO-8859-1,utf-8;q=0.7,;q=0.7" "REMOTE_ADDR" => "127.0.0.1" "SCRIPT_NAME" => "" "SCRIPT_FILENAME" => "" "SERVER_PROTOCOL" => "HTTP/1.1" "REQUEST_TIME" => 1611144633 "PATH_INFO" => "" "REQUEST_METHOD" => "PUT" "CONTENT_TYPE" => "application/x-www-form-urlencoded" "REQUEST_URI" => "/api/pull" "QUERY_STRING" => "" ] } +files: Symfony\Component\HttpFoundation\FileBag {#4121 #parameters: [] } +cookies: Symfony\Component\HttpFoundation\InputBag {#3956 #parameters: [] } +headers: Symfony\Component\HttpFoundation\HeaderBag {#4110 #headers: array:6 [ "host" => array:1 [ 0 => "hoqu-laravel.test" ] "user-agent" => array:1 [ 0 => "Symfony" ] "accept" => array:1 [ 0 => "text/html,application/xhtml+xml,application/xml;q=0.9,/;q=0.8" ] "accept-language" => array:1 [ 0 => "en-us,en;q=0.5" ] "accept-charset" => array:1 [ 0 => "ISO-8859-1,utf-8;q=0.7,;q=0.7" ] "content-type" => array:1 [ 0 => "application/x-www-form-urlencoded" ] ] #cacheControl: [] } #content: null #languages: null #charsets: null #encodings: null #acceptableContentTypes: null #pathInfo: "/api/pull" #requestUri: "/api/pull" #baseUrl: "" #basePath: null #method: "PUT" #format: null #session: null #locale: null #defaultLocale: "en" -preferredFormat: null -isHostValid: true -isForwardedValid: true -isSafeContentPreferred: null basePath: "" format: "html" }

Jan
18
1 week ago
Activity icon

Replied to Call Command From Web Interface / Menu

all right. How can I link this action to a click on a button? @bugsysha

Activity icon

Replied to Call Command From Web Interface / Menu

ok so are you telling me that i can create a resource put the command you told me? @bugsysha

Activity icon

Started a new Conversation Call Command From Web Interface / Menu

there is a plug-in that manages to call a command from the web interface.

I created a command with php make: command and I wanted to call it from the web interface only I was wondering if it was possible with laravel nova ?

Activity icon

Started a new Conversation Nl2br Don't Respectbreaks Lines \n

I should print such a formatted line:

"kings \n garden"

in pure PHP I would do this:

echo  nl2br ("kings \n garden");

in blade of laravel. 8x I do so:

{!! nl2br($task->text) !!}

but it doesn't print me correctly, how could I do?

Jan
15
1 week ago
Activity icon

Started a new Conversation TDD: Lesson 21

when i launch this test:

function test_completing_a_new_task_records_projects_activity()
{
    $project = ProjectFactory::withTask(1)->create();

    $project->addTask('Some task');

    $this->patch($project->task[0]->path(),[
        'body'=>'foobar',
        'completed'=>true
    ]);

    $this->assertCount(3,$project->activity);

// $this->assertEquals('created_task',$project->activity->last()->description); }

i get the following error:

There was 1 error:
  1. Tests\Feature\ActivityFeedTest::test_completing_a_new_task_records_projects_activity Error: Call to undefined method Tests\Setup\ProjectFactory::withTask()

but in ProjectFactory

use App\Models\Project; use App\Models\Task; use App\Models\User;

class ProjectFactory { protected $taskCount = 0;

protected $user;

public function withTasks($count)
{
    $this->taskCount = $count;

    return $this;

}
Activity icon

Commented on Project Activity Feeds: Part 2

at minute 03:36 Jeffrey changes to ../Providers/Task.php only that I in my project do not find Task.php in Providers but other files like AppServiceProviders I am using laravel 8x @jeffrey

Jan
14
1 week ago
Activity icon

Started a new Conversation $request->ip() Undefined

I have two methods to which I pass Request object:

public function pull(Request $requestSvr)
{
    if($requestSvr->user()->tokenCan('update'))
    {
        $requestSvr->all();

           dd(requestSvr->ip());//ip OK

while in this method:

public function updateDone(Request $requestSvr2) {

    if($requestSvr2->user()->tokenCan('update'))
    {


        $requestSvr2 = $requestSvr2->all();
	dd(requestSvr->ip());//he does not find it

I do not understand why

Jan
13
1 week ago
Activity icon

Replied to Call Controller Functionality In Other Controller

Fooservice where do i put it in the directory do i create one? or do I put it in app / http? @martinbean

Activity icon

Replied to Call Controller Functionality In Other Controller

ok could i find an example regarding this solution?

in fact I would like to avoid calling a controller inside another controller @martinbean

Activity icon

Replied to Call Controller Functionality In Other Controller

so such a thing?

class AController extends BController
{}

@michaloravec

Activity icon

Replied to Call Controller Functionality In Other Controller

you could give me an example that I'm a bit confused @topvillas

Activity icon

Started a new Conversation Call Controller Functionality In Other Controller

I have two controllers one called A and the other B.

controller A has the storeA and update method

controller B only storeB

A's update method is called via api at the api / update link

when the api / update is called I would like the storeB to be done as well. so I would also like to call the B-> storeB method inside the A-> update controller.

so if I did so, the update method of A:

    public function update(Project $project)
{

    $this->authorize('update',$project);

    $attributes = request()->validate([
        'title'=>'required',
        'description'=>'required',
        'notes'=>'min:3'
    ]);

    $project->update($attributes);

$s = new BController();
$s->storeB();

   return redirect($project->path());

}

I was wondering if there was a more elegant way than this. to do such an operation. In the sense it seems to me a bad practice

Activity icon

Started a new Conversation Model Vs Controller

I created Poll_Server with the following command:

php artisan make:model Poll_Server -c -m -f

I made a migration like this:

public function up()
{
    Schema::create('poll__servers', function (Blueprint $table) {
        $table->id();
        $table->text('server_id');
        $table->text('server_ip');
        $table->timestamp('last_activity');
    });
}

I wanted to write a store (Controller) or addServer (Model) function.

I was wondering whether to put the store function in the controller or to write a part also in the model ?.

In the sense I've always seen putting the store in the controller, I was wondering if it was wrong to put the usual function in the model?

Jan
12
1 week ago
Activity icon

Awarded Best Reply on TDD: Illuminate\Session\TokenMismatchException: CSRF Token Mismatch.

i solved with

 php artisan config:clear
Activity icon

Replied to TDD: Illuminate\Session\TokenMismatchException: CSRF Token Mismatch.

i solved with

 php artisan config:clear
Activity icon

Replied to TDD: Illuminate\Session\TokenMismatchException: CSRF Token Mismatch.

yes

<php>
    <server name="APP_ENV" value="testing"/>
    <server name="BCRYPT_ROUNDS" value="4"/>
    <server name="CACHE_DRIVER" value="array"/>
     <server name="DB_CONNECTION" value="sqlite"/>
     <server name="DB_DATABASE" value=":memory:"/>
    <server name="MAIL_MAILER" value="array"/>
    <server name="QUEUE_CONNECTION" value="sync"/>
    <server name="SESSION_DRIVER" value="array"/>
    <server name="TELESCOPE_ENABLED" value="false"/>
</php>
Activity icon

Started a new Conversation TDD: Illuminate\Session\TokenMismatchException: CSRF Token Mismatch.

I'm at this lesson https://laracasts.com/series/build-a-laravel-app-with-tdd/episodes/16 minute 11:00

when i launch this test i get a different error than the course one

public function test_a_user_can_update_a_project()
{
    $this->signIn();

    $this->withoutExceptionHandling();

    $project = Project::factory()->create(['owner_id'=>auth()->id()]);

    $this->patch($project->path(),[
        'notes'=>'Changed'
    ]);

    $this->assertDatabaseHas('projects',['notes'=>'Changed']);
}

gives me following errors:

  1. Tests\Feature\ManageProjectsTest::test_a_user_can_update_a_project Illuminate\Session\TokenMismatchException: CSRF token mismatch.

this is my route web:

Route::group(['middleware'=>'auth'],function(){
Route::get('/projects', [ProjectsController::class, 'index']);
Route::get('/projects/create', [ProjectsController::class, 'create']);

Route::get('/projects/{project}', [ProjectsController::class, 'show']);
Route::patch('/projects/{project}', [ProjectsController::class, 'update']);

Route::post('/projects', [ProjectsController::class, 'store']);
Route::post('/projects/{project}/tasks', [ProjectTasksController::class, 'store']);
Route::patch('/projects/{project}/tasks/{task}', [ProjectTasksController::class, 'update']);

});
Activity icon

Replied to TDD: LogicException: App\Models\Project::path Must Return A Relationship Instance.

now from this error:

Failed asserting that two strings are equal. --- Expected +++ Actual @@ @@ -'http://birdboard.test/projects/1' +'http://birdboard.test/projects'

Activity icon

Started a new Conversation TDD: LogicException: App\Models\Project::path Must Return A Relationship Instance.

I'm at this lesson https://laracasts.com/series/build-a-laravel-app-with-tdd/episodes/14 minute 18:16

when i launch this test i get a different error than the course one

   public function test_a_user_can_create_a_project()
    {

        $this->withoutExceptionHandling();

        $this->singIn();

        $this->get('/projects/create')->assertStatus(200);

        $attributes = [
            'title' => $this->faker->sentence,
            'description' => $this->faker->paragraph,
        ];

        $response = $this->post('/projects', $attributes);

        $project = Project::where($attributes)->first();

        $response->assertRedirect($project->path);

        $this->assertDatabaseHas('projects',$attributes);

        $this->get('/projects')->assertSee($attributes['title']);
    }

gives me following errors:

  1. Tests\Feature\ManageProjectsTest::test_a_user_can_create_a_project LogicException: App\Models\Project::path must return a relationship instance.
Activity icon

Started a new Conversation TDD: InvalidArgumentException: Unknown Formatter "sentence"

I'm at this lesson https://laracasts.com/series/build-a-laravel-app-with-tdd/episodes/14 minute 14:53

when i launch this test i get a different error than the course one

    use App\Models\Task;
use Illuminate\Foundation\Testing\RefreshDatabase;
use PHPUnit\Framework\TestCase;
use Illuminate\Foundation\Testing\WithFaker;
use Illuminate\Support\Collection;

class TaskTest extends TestCase
{
    use RefreshDatabase;

    public function test_it_has_a_path()
    {
        $task = Task::factory()->create();

        $this->assertEquals('/projects/'.$task->project->id . '/tasks/'.$task->id, $task->path());
    }
}

gives me following error:

  1. Tests\Unit\TaskTest::test_it_has_a_path InvalidArgumentException: Unknown formatter "sentence"

so i defined the task factory:

    public function definition()
{
    return [
        'body'=> $this->faker->sentence,
        'project_id' => function(){
            return Project::factory();
        }

    ];
}
Activity icon

Started a new Conversation TDD: Failed Asserting That A Row In The Table [tasks] Matches The Attributes

I'm at this lesson https://laracasts.com/series/build-a-laravel-app-with-tdd/episodes/14 minute 09:27

I wrote this feature test in ProjectTasksTest.php:

public function  test_a_task_can_be_updated()
{
    $this->withoutExceptionHandling();

    $this->singIn();

    $project = auth()->user()->projects()->create(
        Project::factory()->raw()
    );

    $task = $project->addTask('test task');

    $this->patch($project->path().'/tasks/'.$task->id, [
        'body'=>'changed',
        'completed'=> true
    ]);

    $this->assertDatabaseHas('tasks',[
        'body'=>'changed',
        'completed'=> true
    ]);

}

when he launched the specific test: vendor/bin/phpunit --filter test_a_task_can_be_updated

i get the following error:

Failed asserting that a row in the table [tasks] matches the attributes {
"body": "changed",
"completed": true

}.

Found: [ { "id": "1", "project_id": "1", "body": "test task", "completed": "0", "created_at": "2021-01-12 08:39:06", "updated_at": "2021-01-12 08:39:06" } ].

this is the controller:

public function update(Project $project, Task $task)
   {
       $task->updated([
           'body'=> request('body'),
           'completed'=> request()->has('completed')
       ]);

       return redirect($project->path());

   }

these are the web routes:

Route::group(['middleware'=>'auth'],function(){
    Route::get('/projects', [ProjectsController::class, 'index']);
    Route::get('/projects/create', [ProjectsController::class, 'create']);
    Route::get('/projects/{project}', [ProjectsController::class, 'show']);
    Route::post('/projects', [ProjectsController::class, 'store']);
//    Route::post('/projects/{project}/tasks', [ProjectTasksController::class, 'store']);
    Route::patch('/projects/{project}/tasks/{task}', [ProjectTasksController::class, 'update']);

});
Jan
11
2 weeks ago
Activity icon

Started a new Conversation TDD :Error: Call To Undefined Method Tests\Feature\ProjectTasksTest::signIn()

I'm doing the exercise: (https://laracasts.com/series/build-a-laravel-app-with-tdd/episodes/12) minute 07:00

I wrote this test in TestCase:

    abstract class TestCase extends BaseTestCase
{
    use CreatesApplication;

    protected function singIn($user = null)
    {
        $this->actingAs($user ?: User::factory()->create());
    }
}

then I wrote this test for Project Task Controller:

class ProjectTasksTest extends TestCase
{
    use RefreshDatabase;

    public function test_a_project_can_have_tasks()
    {
        $this->withoutExceptionHandling();

        $this->signIn();

        $project = Project::factory()->create(['owner_id'=>auth()->id()]);

        $this->post($project->path().'/tasks', ['body'=>'Test task']);

        $this->get($project->path())->assertSee('Test task');

    }

when I launch the test:

vendor/bin/phpunit tests/Feature/ProjectTasksTest.php

gives me following error:

  1. Tests\Feature\ProjectTasksTest::test_a_project_can_have_tasks Error: Call to undefined method Tests\Feature\ProjectTasksTest::signIn()
Activity icon

Replied to Storage Gitignore

ok. So if I wanted to test using .json files should I be able to save them? since I can't save them in storage ... @michaloravec

Activity icon

Started a new Conversation Storage Gitignore

I was wondering why the storage folder is put in gitignore? in the sense why it would be a bad practice to push the storage?

Activity icon

Started a new Conversation TDD:Call To Undefined Method Illuminate\Database\Eloquent\Relations\BelongsTo::getKey()

related to lesson 06 of Build A Laravel App With TDD . when i go to the one page show i get the following error:

Call to undefined method Illuminate\Database\Eloquent\Relations\BelongsTo::getKey()

in the Project model I wrote the following method:

 public function owner()
{
    return $this->belongsTo(User::class);
}

the Projects controller show I made it like this:

public function show(Project $project)
{
    if (auth()->user()->isNot($project->owner()))
    {
        abort(403);
    }
    return view('projects.show',compact('project'));
}
Activity icon

Replied to TDD: Symfony\Component\HttpKernel\Exception\HttpException:

I changed Project's show method from like this:

    public function show(Project $project)
{
    if (auth()->id() !== $project->owner_id)
    {
        abort(403);
    }
    return view('projects.show',compact('project'));
}

to so:

	    public function show(Project $project)
{
    if (auth()->id() != $project->owner_id)
    {
        abort(403);
    }
    return view('projects.show',compact('project'));
}

and it works

Activity icon

Replied to TDD: Symfony\Component\HttpKernel\Exception\HttpException:

  1. Tests\Feature\ProjectsTest::test_a_user_can_view_their_project Symfony\Component\HttpKernel\Exception\HttpException:

/Users/gianmarx/TDD/birdboard/vendor/laravel/framework/src/Illuminate/Foundation/Application.php:1071 /Users/gianmarx/TDD/birdboard/vendor/laravel/framework/src/Illuminate/Foundation/helpers.php:44 /Users/gianmarx/TDD/birdboard/app/Http/Controllers/ProjectsController.php:58 /Users/gianmarx/TDD/birdboard/vendor/laravel/framework/src/Illuminate/Routing/Controller.php:54 /Users/gianmarx/TDD/birdboard/vendor/laravel/framework/src/Illuminate/Routing/ControllerDispatcher.php:45 /Users/gianmarx/TDD/birdboard/vendor/laravel/framework/src/Illuminate/Routing/Route.php:254 /Users/gianmarx/TDD/birdboard/vendor/laravel/framework/src/Illuminate/Routing/Route.php:197 /Users/gianmarx/TDD/birdboard/vendor/laravel/framework/src/Illuminate/Routing/Router.php:692 /Users/gianmarx/TDD/birdboard/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php:128 /Users/gianmarx/TDD/birdboard/vendor/laravel/framework/src/Illuminate/Routing/Middleware/SubstituteBindings.php:41 /Users/gianmarx/TDD/birdboard/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php:167 /Users/gianmarx/TDD/birdboard/vendor/laravel/framework/src/Illuminate/Auth/Middleware/Authenticate.php:44 /Users/gianmarx/TDD/birdboard/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php:167 /Users/gianmarx/TDD/birdboard/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/VerifyCsrfToken.php:78 /Users/gianmarx/TDD/birdboard/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php:167 /Users/gianmarx/TDD/birdboard/vendor/laravel/framework/src/Illuminate/View/Middleware/ShareErrorsFromSession.php:49 /Users/gianmarx/TDD/birdboard/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php:167 /Users/gianmarx/TDD/birdboard/vendor/laravel/framework/src/Illuminate/Session/Middleware/StartSession.php:121 /Users/gianmarx/TDD/birdboard/vendor/laravel/framework/src/Illuminate/Session/Middleware/StartSession.php:63 /Users/gianmarx/TDD/birdboard/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php:167 /Users/gianmarx/TDD/birdboard/vendor/laravel/framework/src/Illuminate/Cookie/Middleware/AddQueuedCookiesToResponse.php:37 /Users/gianmarx/TDD/birdboard/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php:167 /Users/gianmarx/TDD/birdboard/vendor/laravel/framework/src/Illuminate/Cookie/Middleware/EncryptCookies.php:67 /Users/gianmarx/TDD/birdboard/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php:167 /Users/gianmarx/TDD/birdboard/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php:103 /Users/gianmarx/TDD/birdboard/vendor/laravel/framework/src/Illuminate/Routing/Router.php:694 /Users/gianmarx/TDD/birdboard/vendor/laravel/framework/src/Illuminate/Routing/Router.php:669 /Users/gianmarx/TDD/birdboard/vendor/laravel/framework/src/Illuminate/Routing/Router.php:635 /Users/gianmarx/TDD/birdboard/vendor/laravel/framework/src/Illuminate/Routing/Router.php:624 /Users/gianmarx/TDD/birdboard/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php:166 /Users/gianmarx/TDD/birdboard/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php:128 /Users/gianmarx/TDD/birdboard/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/TransformsRequest.php:21 /Users/gianmarx/TDD/birdboard/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php:167 /Users/gianmarx/TDD/birdboard/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/TransformsRequest.php:21 /Users/gianmarx/TDD/birdboard/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php:167 /Users/gianmarx/TDD/birdboard/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/ValidatePostSize.php:27 /Users/gianmarx/TDD/birdboard/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php:167 /Users/gianmarx/TDD/birdboard/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/PreventRequestsDuringMaintenance.php:87 /Users/gianmarx/TDD/birdboard/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php:167 /Users/gianmarx/TDD/birdboard/vendor/fruitcake/laravel-cors/src/HandleCors.php:37 /Users/gianmarx/TDD/birdboard/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php:167 /Users/gianmarx/TDD/birdboard/vendor/fideloper/proxy/src/TrustProxies.php:57 /Users/gianmarx/TDD/birdboard/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php:167 /Users/gianmarx/TDD/birdboard/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php:103 /Users/gianmarx/TDD/birdboard/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php:141 /Users/gianmarx/TDD/birdboard/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php:110 /Users/gianmarx/TDD/birdboard/vendor/laravel/framework/src/Illuminate/Foundation/Testing/Concerns/MakesHttpRequests.php:508 /Users/gianmarx/TDD/birdboard/vendor/laravel/framework/src/Illuminate/Foundation/Testing/Concerns/MakesHttpRequests.php:292 /Users/gianmarx/TDD/birdboard/tests/Feature/ProjectsTest.php:101

@tray2

Activity icon

Started a new Conversation TDD: Symfony\Component\HttpKernel\Exception\HttpException:

I wrote this test related to lesson 06 of Build A Laravel App With TDD minute 05:52

public function test_a_user_can_view_their_project()
{
    $this->be(User::factory()->create());
    $this->withoutExceptionHandling();

    $project = Project::factory()->create(['owner_id'=>auth()->id()]);

    $this->get('/projects/'.$project->id)
        ->assertSee($project->title)
        ->assertSee($project->description);

}

i get this error that i don't understand:

  1. Tests\Feature\ProjectsTest::test_a_user_can_view_their_project Symfony\Component\HttpKernel\Exception\HttpException:
Activity icon

Replied to TDD: Error: Class 'http\Client\Curl\User' Not Found

i changed as follows:

namespace Tests\Unit;

use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Foundation\Testing\WithFaker;

use Tests\TestCase;

class UserTest extends TestCase
{
    use RefreshDatabase;

    public function test_a_user_has_projects()
    {
        $user = User::factory()->create();

        $this->assertInstanceOf(Collection::class,$user->projects);
    }
}

but I get the following error always not present in the course:

PHPUnit\Framework\InvalidArgumentException: Argument #1 of PHPUnit\Framework\Assert::assertInstanceOf() must be a class or interface name

Activity icon

Started a new Conversation TDD: Error: Class 'http\Client\Curl\User' Not Found

I'm doing the exercise from lesson 05 :A Project Requires An Owner minute 09:47

I wrote this unit test for User:

namespace Tests\Unit;

use http\Client\Curl\User;
use PHPUnit\Framework\TestCase;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Foundation\Testing\WithFaker;

class UserTest extends TestCase
{
    use RefreshDatabase;

    public function test_a_user_has_projects()
    {
        $user = User::factory()->create();

        $this->assertInstanceOf(Collection::class,$user->projects);
    }
}

but i get this error which is not present in the course:

  1. Tests\Unit\UserTest::test_a_user_has_projects Error: Class 'http\Client\Curl\User' not found

i can't solve it

Activity icon

Commented on A Project Requires An Owner

I wrote this unit test User:

    public function test_a_user_has_projects()
{
    $user = User::factory()->create();

    $this->assertInstanceOf(Collection::class,$user->projects);
}

but i get a different error than the per minute course 09:47.

I get this weird error:

  1. Tests\Unit\UserTest::test_a_user_has_projects Error: Class 'http\Client\Curl\User' not found
Jan
10
2 weeks ago
Activity icon

Replied to PHP Session : Do Not Increment The Session Every Time I Refresh The Page

I'm trying to get a variable increment if and only if I press the button. I'll need that variable to iterate through an array @tray2

Activity icon

Replied to PHP Session : Do Not Increment The Session Every Time I Refresh The Page

could you help me in this operation? if an example were possible? many thanks @tray2

Activity icon

Replied to PHP Session : Do Not Increment The Session Every Time I Refresh The Page

so it doesn't increment me anymore when I click on the button @tray2

Activity icon

Started a new Conversation PHP Session : Do Not Increment The Session Every Time I Refresh The Page

I created this code that increments the session variable every time I click on the button. I just don't want it to increment every time I refresh the page:

	<?php
   session_start();
   // Page was not reloaded via a button press
   if (!isset($_POST['add'])) {
       $_SESSION['attnum'] = 0; // Reset counter
   }
?>

<form method='post'>
<input name='add' type="submit" value='+'>
<h3><em>att<?php echo $_SESSION['attnum']++ ?>: </em></h3>
</form>

how can i set the session to increment only when i click on the button and not to increment when i refresh?

Activity icon

Started a new Conversation Increment Array Index By Clicking A Button In PHP / JS

I would like to increment an array index through a button named next ?

I upload my json data.json:

[
{
  "id": 1,
  "name": "Survey",
  "distance": 5,
  "questions": [
    {
      "id": 1,
      "question": "select warm colors ?",
      "answer": [
             {
          "a": "red",
          "b": "blue",
          "c": "orange"
             }
        
         ],
      "correct": "a,c"
    },
    {
        "id": 2,
        "question": "select cool colors ?",
        "answer": [
               {
            "a": "yellow",
            "b": "blue",
            "c": "green",
            "d": "purple"
               }
          
           ],
        "correct": "b,c"
      },
      {
        "id": 3,
        "question": "What is a class in PHP?",
        "answer": [
               {
            "a": "A repository for storing key-value pairs.",
            "b": "A blueprint from which objects are created.",
            "c": "A group of related methods with empty bodies.",
            "d": "I don't know, and am not ready for this quiz."
               }
          
           ],
        "correct": "b"
      }
  ]
}

]

then in my php file I load the json file which I convert to array

in survey.php :

    <!doctype html>
<html lang="en">
   <head>
      <meta charset="utf-8">
      <meta http-equiv="X-UA-Compatible" content="IE=edge">
      <meta name="viewport" content="width=device-width, initial-scale=1">
      <link href="https://unpkg.com/[email protected]/dist/tailwind.min.css" rel="stylesheet">
   </head>
   <body class="h-screen overflow-hidden flex items-center justify-center" style="background: #edf2f7;">
      <div class="bg-gray-100 pt-10">
      <div class="mx-auto max-w-6xl">
         <div class="p-2 bg-gray-100 rounded">
            <div class="flex flex-col md:flex-row">
        
               <div class="md:w-2/3">
                  <div class="p-4">
                     <div class="mb-2">
                        <?php
                           $strJsonFileContents = file_get_contents("data.json");
                           //var_dump($strJsonFileContents->distance);
                           
                           $array = json_decode($strJsonFileContents, true);
                           
                           //var_dump($array[0]['questions'][0]);
                           ?>
                        <div class="font-medium rounded-sm text-lg px-2 py-3 flex text-gray-800 flex-row-reverse mt-2 cursor-pointer text-black bg-white hover:bg-white">
                           <div class="flex-auto mt-8">
                           <div class="flex flex-col items-center justify-center ">

                              <?php  echo $array[0]['questions'][0]['question']; ?>
                              </div>
                              <div class="mt-2">
                                 <div class="bg-white">
                                    <div class="flex flex-col items-left justify-left">
                                       <div class="flex flex-col">
                                          <?php 
                                             foreach($array[0]['questions'][0]['answer'][0] as $key=>$value){ ?>
                                          <label class="inline-flex items-left mt-8 ml-6">
                                          <input id="<?php $key; ?>" type="checkbox" class="form-checkbox h-5 w-5 text-gray-600"><span class="ml-2 text-gray-700"><?php echo $value; ?></span>
                                          </label>
                                          <?php } ?>
                                       </div>
                                    </div>
                                    <div class="float-right mt-8 mb-8">
                                       <a href="" class="bg-blue-500 rounded-lg font-bold text-white text-center px-4 py-3 transition duration-300 ease-in-out hover:bg-blue-600 mr-6">
                                        NEXT
                                       </a>
                                    </div>
                                 </div>
                              </div>
                           </div>
                        </div>
                     </div>
                  </div>
               </div>
            </div>
         </div>
      </div>
   </body>
</html>

basically I would like to iterate on the following variables at the click of the NEXT button:

$array[0]['questions'][$increment]['answer'][0] 
$array[0]['questions'][$increment]['question'][0]
Jan
08
2 weeks ago
Activity icon

Replied to Test Add Ip Server With Local Method

I'm doing the test locally. dd($response->server('SERVER_ADDR')) will always be null. i think i go mocked in this case @tray2

Activity icon

Replied to Test Add Ip Server With Local Method

yes ok I could add an ip_server field in the request. or do something like this:

$requestSvr1 = [ "id_server" => server_1', 
				"task_available" => ["A","B"] ,
				ip_server => '111.111.111'];

and then work it taking the value as follows:

$requestSvr->all();
$requestSvr['ip_server']	

but this would result in server side changes which I cannot do. What I was saying was to derive the ip value. server from the call.

and I found that this value can be obtained as follows:

$response->server('SERVER_ADDR')

I just have no idea how to test locally

@tray2

Activity icon

Started a new Conversation Test Add Ip Server With Local Method

I wanted to test this method with a feature test:

public function getTask(Request $requestSvr)
{
   
        $requestSvr->all();
        $requestSvr['id_server'] = (string) $requestSvr['id_server'];

        $task = Task::whereIn('works', $requestSvr['task_available'])->where('process_status','=','new')->first();

        if(!empty($task))
        {
            $task->process_status = 'processing';
            $task->id_server = $requestSvr['id_server'];

            if(!empty($requestSvr->server('SERVER_ADDR')))
            {
                $task->ip_server = (string) $requestSvr->server('SERVER_ADDR');
            }

            $task->save();

            return response()->json($task, 200);

        }
        else
        {
            return response()->json([], 204);
        }

}

doing the test locally I would not know how to verify that ip_server is entered

I would like to test it as follows:

//so he simulated the server call $requestSvr1 = [ "id_server" => server_1', "task_available" => ["A","B"] ];

        $response = $this->put('/api/get_task',$requestSvr1);
   	 $ja = Task::find($response['id']);
//this FAIL $response->server('SERVER_ADDR') is empty
    $this->assertSame($response->server('SERVER_ADDR'),$ja['ip_server']);

this $requestSvr->server ('SERVER_ADDR') value is null. It will only ever be null locally.

how could I test such a thing?

Jan
07
2 weeks ago
Activity icon

Started a new Conversation A Method That Calls Some Trello API: Model Or Controller?

I created a method that makes calls to trello api. I was wondering whether to put this method in the controller or in the model?