giorg

giorg

Member Since 11 Months Ago

Experience Points 2,390
Experience Level 1

2,610 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 6
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.

26 Jul
3 weeks ago

giorg left a reply on Testing Model's Creation

Hi and thanks for your answer. This way it will be saved in the db, which is why I was trying to use the factory...

giorg started a new conversation Testing Model's Creation

Hi, wrote this test:

public function testAddProductsAfterSoftware() {
        Auth::loginUsingId(8);
        $software = factory(Software::class)->create();
        $lot_types = LotType::all();

        foreach ($lot_types as $lot_type) {
            $this->assertDatabaseHas('products', ['code' => $software->denominazione . ($lot_type->code ? '-' . $lot_type->code : $lot_type->code), 'price' => $lot_type->price, 'description' => $lot_type->product_description . ' ' . $software->nome_software]);
        }
    }

in the controller:

public function store(Request $request)
    {
        $user = Auth::user();
        if ($user->can('admin')) {
            $sw = Software::create($request->all());

            $lot_types = LotType::all();

            foreach ($lot_types as $lot_type) {
                $product = new Product();
                $product->code = $sw->denominazione . ($lot_type->code ? '-' . $lot_type->code : $lot_type->code);
                $product->price = $lot_type->price;
                $product->description = trim($lot_type->product_description) . ' ' . $sw->nome_software;
                // fixme: questo non è bello a codice: da' per scontato che la produzione sia 0 -- mettiamo nei parametri?
                $product->product_type_id = 0;
                $product->save();
            }

            return redirect('software/index')->with(['message' => 'Software creato con successo!', 'alert-class' => 'alert-success']);
        }
        return redirect('/')->with(['message' => 'Non hai i permessi!', 'alert-class' => 'alert-danger', 'user' => $user]);
    }

but when I run the test the store function is not executed at all, what am I doing wrong? thanks a lot

25 Jul
3 weeks ago

giorg left a reply on Testing Controller Update

I use the latest, but in fact I do get 419 if I don't disable csrf check... I had a look all over the project and I don't understand why env is not testing when... well, testing :) I have this in my phpunit.xml:

<env name="APP_ENV" value="testing"/>

which should override all other settings... ty

giorg left a reply on Testing Controller Update

damn forgot that. Thanks a lot!!

giorg left a reply on Testing Controller Update

actually I've just realized the response says "invoice updated successfully", so why te test is failing...

giorg left a reply on Testing Controller Update

Hi @mstrauss and thanks for you answer. total is a varchar, so should be fine. Auth is needed because my whole application is password protected. And here is the dd output:

Illuminate\Foundation\Testing\TestResponse {#11283
  +baseResponse: Illuminate\Http\RedirectResponse {#11417
    #request: Illuminate\Http\Request {#11337
      #json: null
      #convertedFiles: []
      #userResolver: Closure($guard = null) {#11362
        class: "Illuminate\Auth\AuthServiceProvider"
        this: Illuminate\Auth\AuthServiceProvider {#10851 …}
        parameters: {
          $guard: {
            default: null
          }
        }
        use: {
          $app: Illuminate\Foundation\Application {#10882 …}
        }
        file: "./vendor/laravel/framework/src/Illuminate/Auth/AuthServiceProvider.php"
        line: "85 to 87"
      }
      #routeResolver: Closure() {#11354
        class: "Illuminate\Routing\Router"
        this: Illuminate\Routing\Router {#10848 …}
        use: {
          $route: Illuminate\Routing\Route {#11020 …}
        }
        file: "./vendor/laravel/framework/src/Illuminate/Routing/Router.php"
        line: "650 to 652"
      }
      +attributes: Symfony\Component\HttpFoundation\ParameterBag {#11339
        #parameters: []
      }
      +request: Symfony\Component\HttpFoundation\ParameterBag {#11338
        #parameters: array:1 [
          "total" => "non prende"
        ]
      }
      +query: Symfony\Component\HttpFoundation\ParameterBag {#11345
        #parameters: []
      }
      +server: Symfony\Component\HttpFoundation\ServerBag {#11341
        #parameters: array:16 [
          "SERVER_NAME" => "aamscomm.test"
          "SERVER_PORT" => 80
          "HTTP_HOST" => "aamscomm.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" => 1564060420
          "PATH_INFO" => ""
          "REQUEST_METHOD" => "PATCH"
          "REQUEST_URI" => "/invoices/39"
          "QUERY_STRING" => ""
        ]
      }
      +files: Symfony\Component\HttpFoundation\FileBag {#11342
        #parameters: []
      }
      +cookies: Symfony\Component\HttpFoundation\ParameterBag {#11340
        #parameters: []
      }
      +headers: Symfony\Component\HttpFoundation\HeaderBag {#11343
        #headers: array:5 [
          "host" => array:1 [
            0 => "aamscomm.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"
          ]
        ]
        #cacheControl: []
      }
      #content: null
      #languages: null
      #charsets: null
      #encodings: null
      #acceptableContentTypes: null
      #pathInfo: "/invoices/39"
      #requestUri: "/invoices/39"
      #baseUrl: ""
      #basePath: null
      #method: "PATCH"
      #format: null
      #session: Illuminate\Session\Store {#11252
        #id: "khuLFKAr3gsviJ7WVmRvauwpn30tu2fkY3zLoC4C"
        #name: "set_intranet_session"
        #attributes: array:6 [
          "login_web_59ba36addc2b2f9401580f014c7f58ea4e30989d" => 8
          "_token" => "CuA6H5LJBBqFtL01aACpRrcoGv4pR1fxx5JKICzn"
          "message" => "Fattura modificata con successo!"
          "_flash" => array:2 [
            "new" => []
            "old" => array:3 [
              0 => "message"
              1 => "alert-class"
              2 => "user"
            ]
          ]
          "alert-class" => "alert-success"
          "user" => App\User {#11262
            #fillable: array:5 [
              0 => "firstname"
              1 => "lastname"
              2 => "enabled"
              3 => "email"
              4 => "password"
            ]
            #hidden: array:2 [
              0 => "password"
              1 => "remember_token"
            ]
            #connection: "mysql"
            #table: "users"
            #primaryKey: "id"
            #keyType: "int"
            +incrementing: true
            #with: []
            #withCount: []
            #perPage: 15
            +exists: true
            +wasRecentlyCreated: false
            #attributes: array:9 [
              "id" => 8
              "email" => "<my email>"
              "email_verified_at" => null
              "password" => "y$qDjhsl4dXRzllnuHbdJdz.3TLE5JDYEZnR0ERsfQRIRZle8P.38j2"
              "remember_token" => "xE1XPi3aEjEIWtZepjNaR7L7UmvFL8eHCr00CfNxWEloDmaPrBvhhwnpQ53P"
              "created_at" => "2019-05-03 17:15:58"
              "updated_at" => "2019-05-03 17:15:58"
              "firstname" => "Andrea"
              "lastname" => "Giorgini"
            ]
            #original: array:9 [
              "id" => 8
              "email" => "<my email>"
              "email_verified_at" => null
              "password" => "y$qDjhsl4dXRzllnuHbdJdz.3TLE5JDYEZnR0ERsfQRIRZle8P.38j2"
              "remember_token" => "xE1XPi3aEjEIWtZepjNaR7L7UmvFL8eHCr00CfNxWEloDmaPrBvhhwnpQ53P"
              "created_at" => "2019-05-03 17:15:58"
              "updated_at" => "2019-05-03 17:15:58"
              "firstname" => "Andrea"
              "lastname" => "Giorgini"
            ]
            #changes: []
            #casts: []
            #dates: []
            #dateFormat: null
            #appends: []
            #dispatchesEvents: []
            #observables: []
            #relations: array:1 [
              "permissions" => Illuminate\Database\Eloquent\Collection {#11427
                #items: array:1 [
                  0 => App\Permission {#11422
                    #fillable: array:2 [
                      0 => "name"
                      1 => "slug"
                    ]
                    #connection: "mysql"
                    #table: "permissions"
                    #primaryKey: "id"
                    #keyType: "int"
                    +incrementing: true
                    #with: []
                    #withCount: []
                    #perPage: 15
                    +exists: true
                    +wasRecentlyCreated: false
                    #attributes: array:5 [
                      "id" => 1
                      "slug" => "admin"
                      "name" => "Admin"
                      "created_at" => "2019-05-03 17:15:27"
                      "updated_at" => "2019-05-03 17:15:27"
                    ]
                    #original: array:7 [
                      "id" => 1
                      "slug" => "admin"
                      "name" => "Admin"
                      "created_at" => "2019-05-03 17:15:27"
                      "updated_at" => "2019-05-03 17:15:27"
                      "pivot_user_id" => 8
                      "pivot_permission_id" => 1
                    ]
                    #changes: []
                    #casts: []
                    #dates: []
                    #dateFormat: null
                    #appends: []
                    #dispatchesEvents: []
                    #observables: []
                    #relations: array:1 [
                      "pivot" => Illuminate\Database\Eloquent\Relations\Pivot {#11423
                        +incrementing: false
                        #guarded: []
                        #connection: "mysql"
                        #table: "users_permissions"
                        #primaryKey: "id"
                        #keyType: "int"
                        #with: []
                        #withCount: []
                        #perPage: 15
                        +exists: true
                        +wasRecentlyCreated: false
                        #attributes: array:2 [
                          "user_id" => 8
                          "permission_id" => 1
                        ]
                        #original: array:2 [
                          "user_id" => 8
                          "permission_id" => 1
                        ]
                        #changes: []
                        #casts: []
                        #dates: []
                        #dateFormat: null
                        #appends: []
                        #dispatchesEvents: []
                        #observables: []
                        #relations: []
                        #touches: []
                        +timestamps: false
                        #hidden: []
                        #visible: []
                        #fillable: []
                        +pivotParent: App\User {#11262}
                        #foreignKey: "user_id"
                        #relatedKey: "permission_id"
                      }
                    ]
                    #touches: []
                    +timestamps: true
                    #hidden: []
                    #visible: []
                    #guarded: array:1 [
                      0 => "*"
                    ]
                  }
                ]
              }
            ]
            #touches: []
            +timestamps: true
            #visible: []
            #guarded: array:1 [
              0 => "*"
            ]
            #rememberTokenName: "remember_token"
          }
        ]
        #handler: Illuminate\Session\FileSessionHandler {#11251
          #files: Illuminate\Filesystem\Filesystem {#10752}
          #path: "/Users/giorg/PhpstormProjects/aamscomm/storage/framework/sessions"
          #minutes: "120"
        }
        #started: false
      }
      #locale: null
      #defaultLocale: "en"
      -isHostValid: true
      -isForwardedValid: true
      basePath: ""
      format: "html"
    }
    #session: Illuminate\Session\Store {#11252}
    #targetUrl: "http://aamscomm.test/invoices/index"
    +headers: Symfony\Component\HttpFoundation\ResponseHeaderBag {#11414
      #computedCacheControl: array:2 [
        "no-cache" => true
        "private" => true
      ]
      #cookies: array:1 [
        "" => array:1 [
          "/" => array:1 [
            "set_intranet_session" => Symfony\Component\HttpFoundation\Cookie {#11395
              #name: "set_intranet_session"
              #value: "eyJpdiI6IitDT1piTHFcLzNYYnR3S0lpRitnZVlBPT0iLCJ2YWx1ZSI6IjhpZWNROFBadnphOVRrMDlQcm9ZMVgzb2NiY3NHSEJvcE85WVVnaUhKMHNqXC9JRjVtc0Q5NWFaOWc2QnJROGVMIiwibWFjIjoiMDg0ZDVlMzY0MzAyM2M4ZjY5OGFkZjVjODllODc4OTIyMTZkZmI2YTlkYzU5MjZlY2I1YjcwNzkwYWYzZThhMSJ9"
              #domain: null
              #expire: 1564067620
              #path: "/"
              #secure: false
              #httpOnly: true
              -raw: false
              -sameSite: null
              -secureDefault: false
            }
          ]
        ]
      ]
      #headerNames: array:5 [
        "cache-control" => "Cache-Control"
        "date" => "Date"
        "location" => "Location"
        "content-type" => "Content-Type"
        "set-cookie" => "Set-Cookie"
      ]
      #headers: array:4 [
        "cache-control" => array:1 [
          0 => "no-cache, private"
        ]
        "date" => array:1 [
          0 => "Thu, 25 Jul 2019 13:13:40 GMT"
        ]
        "location" => array:1 [
          0 => "http://aamscomm.test/invoices/index"
        ]
        "content-type" => array:1 [
          0 => "text/html; charset=UTF-8"
        ]
      ]
      #cacheControl: []
    }
    #content: """
      <!DOCTYPE html>\n
      <html>\n
          <head>\n
              <meta charset="UTF-8" />\n
              <meta http-equiv="refresh" content="0;url=http://aamscomm.test/invoices/index" />\n
      \n
              <title>Redirecting to http://aamscomm.test/invoices/index</title>\n
          </head>\n
          <body>\n
              Redirecting to <a href="http://aamscomm.test/invoices/index">http://aamscomm.test/invoices/index</a>.\n
          </body>\n
      </html>
      """
    #version: "1.1"
    #statusCode: 302
    #statusText: "Found"
    #charset: null
    +original: null
    +exception: null
  }
  #streamedContent: null
}

thank you

giorg left a reply on Testing Controller Update

hey nakov, thanks for your answer. doing that produces exactly the same result, here is my controller:

public function update($id, Request $request)
    {
        $user = Auth::user();
        if ($user->can('admin')) {
            $invoice = Invoice::findOrFail($id);

            foreach ($invoice->rows as $row) {
                $row->delete();
            }

            if (is_array($request->due_date) && count($request->due_date) > 1) {
                foreach ($request->due_date as $k => $date) {
                    if ($date) {
                        $var = 'due_date' . ($k + 1);
                        $invoice->{$var} = $date;
                    }
                }
            } else {
                $invoice->due_date1 = $request->due_date;
            }

            $invoice->number = $request->number;
            $invoice->payment_way_id = $request->payment_way;
            $invoice->payment_type_id = $request->payment_type;
            $invoice->update($request->all());
            $invoice->save();

            if ($request->products and is_array($request->products)) {
                foreach ($request->products as $k => $product) {
                    $row = new InvoiceRow();
                    $row->code = $request->products[$k];
                    $row->description = $request->descriptions[$k];
                    $row->quantity = $request->quantities[$k];
                    $row->price = $request->prices[$k];
                    $row->invoice_id = $invoice->id;
                    $row->save();
                }
            }
            return redirect('invoices/index')->with(['message' => 'Fattura modifica con successo!', 'alert-class' => 'alert-success', 'user' => $user]);
        }
        return redirect('/')->with(['message' => 'Non hai i permessi!', 'alert-class' => 'alert-danger', 'user' => $user]);
    }

weird thing is, as I mentioned, that in the frontend all of this works, and I have a lot of other tests that with this very same code (I mean the update test) on different models, that work too... Thank you

giorg started a new conversation Testing Controller Update

Hi, I have about a hundred tests working correctly, but this one is not:

public function testUpdate()
    {
        $this->withoutMiddleware(\App\Http\Middleware\VerifyCsrfToken::class);

        Auth::loginUsingId(8);

        $invoice = factory(Invoice::class)->create();

        $invoice->total = 'non prende';
        $response = $this->patch('invoices/' . $invoice->id, $invoice->toArray());

        $this->assertDatabaseHas('invoices', ['id' => $invoice->id, 'total' => 'non prende']);

        // dopo aver eliminato si è redirezionati alla lista
        $response->assertRedirect('invoices/index');
    }

result is:

Failed asserting that a row in the table [invoices] matches the attributes {
    "id": 340,
    "total": "non prende"
}

however on the frontend I can update invoices correctly. How can I find where the problem is?

Thanks a lot

23 Jul
3 weeks ago

giorg left a reply on Test Not Working

ok disabling the middleware leads to a 500: "[2019-07-23 15:37:43] local.ERROR: Trailing data {"userId":8,"exception":"[object] (InvalidArgumentException(code: 0): Trailing data at /Users/giorg/PhpstormProjects/aamscomm/vendor/nesbot/carbon/src/Carbon/Traits/Creator.php:563)"

which I don't understand...

UPDATE:

must have something to do with the factory, because if I don't use the factory:

public function testUpdate()
    {
//        $this->withoutExceptionHandling();
        $this->withoutMiddleware(\App\Http\Middleware\VerifyCsrfToken::class);

        Auth::loginUsingId(8);

        $deposit = Deposit::findOrFail(255); //factory(Deposit::class)->create();

        $deposit->nome = 'armando';
        $response = $this->patch('deposits/' . $deposit->id_deposito, $deposit->toArray());

//        $response->assertStatus(200);

        $this->assertDatabaseHas('deposito', ['id_deposito' => $deposit->id_deposito, 'nome' => 'armando']);

        // dopo aver eliminato si è redirezionati alla lista
        $response->assertRedirect('/deposits');
    }

this is green. But I still don't get it, because also this one is green:

public function testCreate()
    {
        $count = Deposit::all()->count();

        factory(Deposit::class)->create();
        $countAfter = Deposit::all()->count();
        $this->assertEquals($count + 1, $countAfter);
    }

and definitely env is not testing, because I tried to set database sqlite and memory in phpunit.xml, but my createTest still writes on mysql db.

giorg left a reply on Test Not Working

good question. In my phpunit.xml I have:

<env name="APP_ENV" value="testing"/>

and I've read this overrides .env when testing, so I should be good to go...

giorg left a reply on Test Not Working

thanks @tykus,

after changing that I now get "Expected status code 200 but received 419". After googling a bit I did put this at top of my test:

$this->withoutExceptionHandling();

which brought me to "1) Tests\Unit\DepositTest::testUpdate Illuminate\Session\TokenMismatchException:" and then a long trace, so I googled another bit, and added

use WithoutMiddleware;

now I get: "1) Tests\Unit\DepositTest::testUpdate InvalidArgumentException: Trailing data", but this time google don't help me...

thanks

giorg left a reply on Test Not Working

Thanks for all your answers, I modified the test this way:

public function testUpdate()
    {
        Auth::loginUsingId(8);

        $deposit = factory(Deposit::class)->create();

        $deposit->nome = 'armando';
        $response = $this->post('deposits/' . $deposit->id_deposito, $deposit->toArray());

        $response->assertStatus(200);

        $this->assertDatabaseHas('deposito', ['id_deposito' => $deposit->id_deposito, 'nome' => 'armando']);
    }

to be sure the route is fine, but in fact I get:

Expected status code 200 but received 405. Failed asserting that false is true.

but in my route.php I have:

Route::patch('deposits/{id}', '[email protected]');

so it should be fine... any further hint?

thanks again

giorg started a new conversation Test Not Working

Hi, I wrote these 2 tests that are not working:

public function testUpdate() {

        $deposit = factory(Deposit::class, 1)->create();

        $deposit->nome = 'armando';
        $this->post('deposits/' . $deposit[0]->id_deposito, $deposit[0]->toArray());

        $this->assertDatabaseHas('deposito',['id_deposito'=> $deposit[0]->id_deposito , 'nome' => 'armando']);
    }

    public function testDelete()
    {
        $deposit = factory(Deposit::class)->create();

        $this->get('deposits/' . $deposit->id_deposito . '/delete');

        $this->assertDatabaseMissing('deposito',['id_deposito'=> $deposit->id_deposito]);
    }

error i.e. in second case is: "Failed asserting that a row in the table [deposito] does not match the attributes { "id_deposito": 213 }"

but in my app I tried many times and it works perfectly. What am I doing wrong? Thanks a lot

12 Jul
1 month ago

giorg left a reply on Foreign Key With 2 Columns

thanks a lot!

giorg started a new conversation Foreign Key With 2 Columns

hello,

I have a table defined so:

$table->unsignedInteger('id');
            $table->integer('shipment_id')->nullable();
            $table->integer('customer_id');
            $table->integer('address_id');
            $table->string('appointed')->nullable();
            $table->string('causal')->nullable();
            $table->string('quantity')->nullable();
            $table->string('weight')->nullable();
            $table->string('appearance')->nullable();
            $table->string('carriage')->nullable();
            $table->date('transport_time')->nullable();
            $table->unsignedInteger('year')->default(date('Y'));

            $table->primary(array('id', 'year'));

            $table->timestamps();

now I need to have another table, with foreign key:

$table->unsignedInteger('id');
            $table->unsignedInteger('ddt_id');
            $table->unsignedInteger('year')->default(date('Y'));
            $table->string('code')->nullable();
            $table->text('description');
            $table->string('quantity')->nullable();

            $table->primary(array('id', 'ddt_id', 'year'));
            $table->foreign('ddt_id')->references('id')->on('ddts')->onDelete('cascade');
            $table->foreign('year')->references('year')->on('ddts')->onDelete('cascade');

            $table->timestamps();

but obviously when I migrate I get:

General error: 1215 Cannot add foreign key constraint (SQL: alter table ddtrows add constraint ddtrows_year_foreign foreign key (year) references ddts (year) on delete cascade)

how do I set foreign key in this case?

thanks a lot

09 Jul
1 month ago

giorg started a new conversation Horde Imap Client

hello, I've installed horde imap client this way: $ pear channel-discover pear.horde.org $ pear install horde/horde_imap_client now I would like to use it in my laravel project, I've built my own artisan command, inside app/Console/Commands. How do I autoload imap client? Thanks a lot

18 Jun
2 months ago

giorg left a reply on Sending Emails In Production

actually I've just realized the email IS sent, but then instead of redirection with success message, I get this exact message:

504 Gateway Time-out

and this is nginx error log:

2019/06/18 15:22:53 [error] 21807#21807: *2217 upstream timed out (110: Connection timed out) while reading response header from upstream, client: 192.168.1.120, server: intranet, request: "POST /preorders HTTP/1.1", upstream: "fastcgi://unix:/var/run/php/php7.2-fpm.sock", host: "intranet", referrer: "http://intranet/preorders/create

thanks

giorg started a new conversation Sending Emails In Production

hello, I'm working on iMac with valet and my laravel project, everything works perfectly. In production I did install sendmail, and this is the .env:

MAIL_DRIVER=sendmail MAIL_HOST=localhost MAIL_PORT=25 MAIL_USERNAME=null MAIL_PASSWORD=null MAIL_ENCRYPTION=null

if I telnet at port 25 I successfully send email to my gmail account, so sendmail is working. But when I try this:

$subject = 'Nuovo pre-ordine'; Mail::send('emails.preorder_notify', ['preorder' => $preorder], function ($message) use ($subject) { $message->from('[email protected]', 'Intranet SET'); $message->subject($subject); $message->to(''); });

I get a 504 gateway timeout. Any suggestion?

thanks a lot

14 May
3 months ago

giorg left a reply on Routes - Weird Behaviour

the get url brings me to a page where I can upload a file to import customers, from there I have the post url where I manilpulate the file importing customers... if this work locally why not in production... I also have another url which goes 404 only in production, but works perfectly locally. And I have like 300 urls in my route file, working on this project for months now, and got this error many times, always solved, I know what the error means, it just doesn't make any sense. It looks like it ignores this row:

Route::get('customers/import', '[email protected]');

thanks

giorg left a reply on Routes - Weird Behaviour

thanks for your answer,

I don't want this as a post, must be a get, as it works perfectly on my local dev machine.

giorg started a new conversation Routes - Weird Behaviour

Hello, I have these customer's routes:

Route::get('customers', '[email protected]'); Route::post('customers', '[email protected]'); Route::get('customers/create', '[email protected]'); Route::get('customers/{id}/edit/{address_id}', '[email protected]'); Route::get('customers/{id}/delete', '[email protected]'); Route::patch('customers/{id}/update', '[email protected]'); Route::get('customers/{id}/addaddress', '[email protected]'); Route::post('customers/toggleLegalOffice', '[email protected]'); Route::post('customers/toggleFavorite', '[email protected]'); Route::post('customers/toggleCanOrder', '[email protected]'); Route::post('customers/getPayment', '[email protected]'); Route::get('customers/{id}/destinations', '[email protected]'); Route::get('customers/{id}/deleteaddress', '[email protected]'); Route::get('customers/{id}/editaddress', '[email protected]'); Route::patch('customers/{id}/saveaddress', '[email protected]'); Route::get('customers/import', '[email protected]'); Route::post('customers/import', '[email protected]');

when I browse customers/import on my local dev machine everything is fine, but when I try on production machine I get:

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

how can this be? Thanks a lot

27 Feb
5 months ago

giorg left a reply on Email Attachment

Hi @mvd,

thanks for your answer. It does the same with other attachments and both with webmail and thunderbird...

thanks you

26 Feb
5 months ago

giorg started a new conversation Email Attachment

Hi, I'm writing an email this way in my controller:

Mail::send('emails.smartchange', ['manufacturer' => $manufacturer, 'subject' => $subject], function ($message) use ($manufacturer, $subject) {
                $message->from($manufacturer->pec_indirizzo, $manufacturer->nome);
                $message->subject($subject);
                $message->to('[email protected]');
                $message->attach(public_path() . '/storage/labels/ETICHETTE300518-876327252.txt', [
                    'as' => 'test.txt',
                    'mime' => 'text/plain'
                ]);

the email is sent but instead of the attachment, I see this in the body:

--_=swift_1551190146_2f993e7d31446485d662d662e585fc2d=_ Content-Type: text/plain; name=armando.txt Content-Transfer-Encoding: base64 Content-Disposition: attachment; filename=armando.txt UVAwNTE2MTM4N0E7U1RTMjIyMjcNClFQMDUxNjEyODJHO1NUUzIyMjI2DQpRUDA1MTYxNDEyTDtT VFMyMjIyOA0KUVAwNTE2MTQxM0s7U1RTMjIyMjk= --_=swift_1551190146_2f993e7d31446485d662d662e585fc2d=_--

what am I doing wrong? Thanks a lot

25 Feb
5 months ago

giorg started a new conversation Textarea Lines

Hi, I have a textarea like this:

Form::textarea('lista_seriali', null, ['class' => 'form-control', 'required' => 'required'])

where a user need to write 16-length digits per line. In my controller I need to cycle over each line, so I get the request:

var_dump(explode('\r\n', $request->get('lista_seriali')))

but what I get is: array(1) { [0]=> string(34) "0028569756548828 0028569756548829" } so a single string 2 chars more than expected. I tried exploding for 1 space, 2 spaces, \n, \r\n... nothing.

Any hint? Thanks a lot

21 Feb
5 months ago

giorg left a reply on Config Change At Runtime For Custom Smtp

You saved my day, thanks a lot!

giorg started a new conversation Config Change At Runtime For Custom Smtp

Hello, I need to send email using different smtp, so I'm trying to change .env data at runtime. This is what I've done so far:

$_ENV['MAIL_HOST'] = $smtp; $_ENV['MAIL_PORT'] = $smtp_port; $_ENV['MAIL_USERNAME'] = $address; $_ENV['MAIL_PASSWORD'] = $password; if ($ssl === '1') { $_ENV['MAIL_ENCRYPTION'] = 'tls'; }

but I receive

Expected response code 250 but got code "530", with message "530 5.7.1 Authentication required

but if I write the values of those variables directly in the .env, it works like a charm.

Any hint? thanks a lot

07 Dec
8 months ago

giorg left a reply on Change Locale

@GLOBALS - thanks a lot!

giorg started a new conversation Change Locale

Hello, my default configured locale in app.php is en. Now in my controller I do:

App::setLocale('it');

which is working, because if I look at the page source I can see

then I created the resource/lang/it folder, with a messages.php file returning the translations, but it's not working. In my template I have:

{{ __('Round') }}

which remains Round even if in my messages.php I have:

return [ 'Round' => 'Giocata', ];

any hint? thanks a lot

24 Oct
9 months ago

giorg left a reply on Logout From Other Devices

I overrided authenticated function in my login controller this way:

protected function authenticated(Request $request, $user) { if (!Auth::logoutOtherDevices($request->get('password'))) { Log::warning('User logged in but logoutOtherDevices failed: ' . $user->name); } }

and it works, hope this is the right way to do it.

thanks a lot @martinbean

giorg left a reply on Logout From Other Devices

omg did not realize that. Then I have another problem, because I need that when a user logins, all other sessions have to be disconnected...

thanks a lot

giorg left a reply on Logout From Other Devices

hey @martinbean,

thanks for you answer. I just realized that this line:

Auth::logoutOtherDevices($user->getAuthPassword());

compromises the correct hashing of the password. If I register a user without that line, and copy the hashed password from the db to the console with tinker through Hash::check, the password is correct. If I uncomment that line, and re-do the whole process, the check function return false. How can this be?

thanks a lot

giorg started a new conversation Logout From Other Devices

Hello,

I've created a UserLoggedIn listener, where in the handle function I do:

$user = Auth::user(); if ($user) { Log::info('user logged in, trying to logout from other devices'); Auth::logoutOtherDevices($user->getAuthPassword()); }

I see the message in the log, but looks like this is not working for me, I was logged in with another browser and I expected to be logged out instead... what am I doing wrong?

Thanks a lot

giorg left a reply on Custom Logging

thanks a lot!

giorg started a new conversation Custom Logging

Hi,

in my .env I have:

LOG_CHANNEL=stack

and my config/logging.php starts with:

'channels' => [
    'stack' => [
        'driver' => 'stack',
        'channels' => ['single'],
        'path' => storage_path('logs/set.log'),
    ],

    'single' => [
        'driver' => 'single',
        'path' => storage_path('logs/laravel.log'),
        'level' => 'debug',
    ],
    .....

I expected to log in my custom set.log, but when I use log functions all goes still to laravel.log...

What am I missing?

Thanks a lot

giorg left a reply on Debug Auth

thanks a lot for your help. Actually the one stored in my db doesn't match, now I have to understand why...

giorg left a reply on Timestamp

thank you very much!

23 Oct
9 months ago

giorg started a new conversation Timestamp

Hi,

I would like to have, for a specific model, eloquent to manage created_At for me, but I need not to have updated_at. Is this possible?

Thanks a lot

giorg left a reply on Debug Auth

thanks for your answers. I have that function because otherwise if I save passwords from laravel-admin they are in clear...

giorg left a reply on Debug Auth

doesn't change anything... this is my model:

namespace App;

use Illuminate\Support\Facades\Hash; use Illuminate\Notifications\Notifiable; use Illuminate\Contracts\Auth\MustVerifyEmail; use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable { use Notifiable;

/**
 * The attributes that are mass assignable.
 *
 * @var array
 */
protected $fillable = [
    'name', 'email', 'password', 'email_verified_at'
];

/**
 * The attributes that should be hidden for arrays.
 *
 * @var array
 */
protected $hidden = [
    'password', 'remember_token',
];

public function setPasswordAttribute($password){
    $this->attributes['password'] = Hash::needsRehash($password) ? Hash::make($password) : $password;
}

}

I had to add this function because otherwise inside laravel-admin passwords are being saved in clear.

thanks

giorg left a reply on Debug Auth

sure, it's the one created by make:auth artisan command:

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller; use Illuminate\Foundation\Auth\AuthenticatesUsers;

class LoginController extends Controller { /* |-------------------------------------------------------------------------- | Login Controller |-------------------------------------------------------------------------- | | This controller handles authenticating users for the application and | redirecting them to your home screen. The controller uses a trait | to conveniently provide its functionality to your applications. | */

use AuthenticatesUsers;

/**
 * Where to redirect users after login.
 *
 * @var string
 */
protected $redirectTo = '/home';

/**
 * Create a new controller instance.
 *
 * @return void
 */
public function __construct()
{
    $this->middleware('guest')->except('logout');
}

}

thanks

giorg left a reply on Debug Auth

I get no errors anywhere, simply I cannot login even if the email_verified_at is populated... I really expected this to work out of the box.

22 Oct
9 months ago

giorg started a new conversation Debug Auth

hello,

which can be the best way to debug why laravel's standard auth module is not authenticating my users (except at registration time)?

thanks a lot

giorg left a reply on Auth Credentials

that did the trick, thanks a lot! But I don't understand why when I do register as a new user then I'm automatically logged in, I should be waiting for the verification, doen't make much sense...

thanks again

giorg left a reply on Auth Credentials

I have a local installation of mysql, that is working for sure because I've created my own models, also installed laravel-admin and I can manage them in the backend:

https://ibb.co/cfLmff

thanks

giorg left a reply on Auth Credentials

sure, there we go:

APP_NAME=Laravel APP_ENV=local APP_KEY=base64:CQr6gUEGUoj+MKmVTqtQNRde/LsHrp3HfBr38i5N3DA= APP_DEBUG=true APP_URL=http://localhost

LOG_CHANNEL=stack

DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE=setonline DB_USERNAME=setonline DB_PASSWORD=socame

BROADCAST_DRIVER=log CACHE_DRIVER=file QUEUE_CONNECTION=sync SESSION_DRIVER=file SESSION_LIFETIME=120

REDIS_HOST=127.0.0.1 REDIS_PASSWORD=null REDIS_PORT=6379

MAIL_DRIVER=smtp MAIL_HOST=smtp.mailtrap.io MAIL_PORT=2525 MAIL_USERNAME=null MAIL_PASSWORD=null MAIL_ENCRYPTION=null

PUSHER_APP_ID= PUSHER_APP_KEY= PUSHER_APP_SECRET= PUSHER_APP_CLUSTER=mt1

MIX_PUSHER_APP_KEY="${PUSHER_APP_KEY}" MIX_PUSHER_APP_CLUSTER="${PUSHER_APP_CLUSTER}"

giorg left a reply on Auth Credentials

thanks again for your answer, unfortunately that didn't make it...

giorg left a reply on Auth Credentials

This is User.php inside app:

namespace App;

use Illuminate\Notifications\Notifiable; use Illuminate\Contracts\Auth\MustVerifyEmail; use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable { use Notifiable;

/**
 * The attributes that are mass assignable.
 *
 * @var array
 */
protected $fillable = [
    'name', 'email', 'password',
];

/**
 * The attributes that should be hidden for arrays.
 *
 * @var array
 */
protected $hidden = [
    'password', 'remember_token',
];

}

I did not touch any of the controllers generated inside Controllers/Auth folder by the command line.

thanks a lot

giorg left a reply on Unique Logged In User

thank you very much @tykus, you made my day :)

giorg left a reply on Auth Credentials

Please have a look here: https://ibb.co/jcNbwL

I tried this many times now: register a user, correctly logged in, then log out and try to login again with error message. I saw I'm not alone with this, happened to many people.

thanks

giorg left a reply on Auth Credentials

Hi,

thanks for your answer but no, I don't.