finchy70

finchy70

Head of Systems at EPS

Swansea

Member Since 1 Year Ago

Experience Points 10,420
Experience
Level
Lessons Completed 83
Lessons
Completed
Best Reply Awards 0
Best Answer
Awards
  • Start Your Engines Achievement

    Start Your Engines

    Earned once you have completed your first Laracasts lesson.

  • First Thousand Achievement

    First Thousand

    Earned once you have earned your first 1000 experience points.

  • One Year Member Achievement

    One Year Member

    Earned when you have been with Laracasts for 1 year.

  • Two Year Member Achievement

    Two Year Member

    Earned when you have been with Laracasts for 2 years.

  • Three Year Member Achievement

    Three Year Member

    Earned when you have been with Laracasts for 3 years.

  • Four Year Member Achievement

    Four Year Member

    Earned when you have been with Laracasts for 4 years.

  • Five Year Member Achievement

    Five Year Member

    Earned when you have been with Laracasts for 5 years.

  • School In Session Achievement

    School In Session

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

  • Welcome To The Community Achievement

    Welcome To The Community

    Earned after your first post on the Laracasts forum.

  • Full Time Learner Achievement

    Full Time Learner

    Earned once 100 Laracasts lessons have been completed.

  • Pay It Forward Achievement

    Pay It Forward

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

  • Subscriber Achievement

    Subscriber

    Earned if you are a paying Laracasts subscriber.

  • Lifer Achievement

    Lifer

    Earned if you have a lifetime subscription to Laracasts.

  • Laracasts Evangelist Achievement

    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 Achievement

    Chatty Cathy

    Earned once you have achieved 500 forum replies.

  • Laracasts Veteran Achievement

    Laracasts Veteran

    Earned once your experience points passes 100,000.

  • Ten Thousand Strong Achievement

    Ten Thousand Strong

    Earned once your experience points hits 10,000.

  • Laracasts Master Achievement

    Laracasts Master

    Earned once 1000 Laracasts lessons have been completed.

  • Laracasts Tutor Achievement

    Laracasts Tutor

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

  • Laracasts Sensei Achievement

    Laracasts Sensei

    Earned once your experience points passes 1 million.

  • Top 50 Achievement

    Top 50

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

07 Nov
1 month ago

finchy70 left a reply on All Tests Started Failing.

Thanks. I realised its due to me adding Voyager. The voyager migrations then break the tests. Not sure what to do with the migrations to stop the error so I decided to remove voyager and will reinstall it at the end of development I think.

finchy70 started a new conversation All Tests Started Failing.

I have 35 tests with 85 assertions that all were passing. The tests are done in an in memory database using DataBaseMigrations.

Every test now returns this error.

BadMethodCallException: SQLite doesn't support dropping foreign keys (you would need to re-create the table).

I have destroyed and re-upped my vagrant box (not that this would normally impact on in memory testing) but the errors still remain.

Also tried composer update.

Anyone else had this issue?

30 Oct
1 month ago

finchy70 left a reply on Tests Not Generating Id's.

@RyanSlicker You helped me notice I'd forgotten to return my helpers.

 create('App\Diary')->id;

should have been

return  create('App\Diary')->id;

finchy70 left a reply on Tests Not Generating Id's.

1) Tests\Feature\ResourceTest::it_can_display_resource_attached_to_a_diary_entry
Illuminate\Database\QueryException: SQLSTATE[23000]: Integrity constraint violation: 19 NOT NULL constraint failed: resources.labour_id (SQL: insert into "resources" ("labour_id", "resource_type_id", "diary_id", "hours", "works", "updated_at", "created_at") values (, , , 9.46, Est id accusamus ex adipisci sit autem atque id veritatis dolor., 2018-10-30 14:50:41, 2018-10-30 14:50:41))

finchy70 left a reply on Tests Not Generating Id's.

Yes heres one of them DiaryFactory

<?php

use Faker\Generator as Faker;

$factory->define(App\Diary::class, function (Faker $faker) {
    return [
        'user_id'        => function () {
            return create('App\User')->id;
        },
        'job_id'         => function () {
            return create('App\Job')->id;
        },
        'entry_date'     => $faker->date,
        'diary_entry' => $faker->sentence(25),
    ];
});

finchy70 started a new conversation Tests Not Generating Id's.

The following code is giving an error that suggests not values are being generated for 'diary_id', 'labour_id', 'resource_type_id'. I'm new to PHPUnit. Have I got my syntax wrong?

<?php

namespace Tests\Feature;

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


class ResourceTest extends TestCase
{
    use DatabaseMigrations;

    /**
     * @test
     */
    public function it_can_display_resource_attached_to_a_diary_entry()
    {
        $resource = create('App\Resource', [
            'diary_id'          => function() {
                create('App\Diary')->id;
            },

            'resource_type_id'  => function() {
                create('App\ResourceType')->id;
            },

            'labour_id'         => function() {
                create('App\Labour')->id;
            }]);

        dd($resource);

        $this->get('/diaries/entry/'.$resource->diary_id)
            ->assertSee(e($resource->labour->name));
    }
}
14 Sep
3 months ago

finchy70 left a reply on Difference Between Two Time Strings

This is working now. I was importing Carbon incorrectly.

13 Sep
3 months ago

finchy70 left a reply on Difference Between Two Time Strings

I'm struggling with handling times. I have used Carbon in the past but as I'm feeding a Vue component with return response and not returning a view dd() is not working and the errors produced by my component are not understandable. The resulting values with console logged show as invalid times.

finchy70 left a reply on Difference Between Two Time Strings

Tried this with no difference.

$start = DateTime($hours->start);
        $finish = DateTime($hours->finish);
        $hours->total = Carbon::parse($finish)->diffInMinutes(Carbon::parse($start));

finchy70 left a reply on Difference Between Two Time Strings

Can't dd. it has no effect. Just stops the controller saving the data.

finchy70 left a reply on Difference Between Two Time Strings

I had tried this previously but it throws a validation error in my coomponent.

Please correct the following error(s):
{ "config": { "transformRequest": {}, "transformResponse": {}, "timeout": 0, "xsrfCookieName": "XSRF-TOKEN", "xsrfHeaderName": "X-XSRF-TOKEN", "maxContentLength": -1, "headers": { "Accept": "application/json, text/plain, */*", "X-Requested-With": "XMLHttpRequest", "X-CSRF-TOKEN": "gBGZ7I8K3TXKxSiGOyuOefvgewhCzIc4zJO1y0H2", "Content-Type": "application/json;charset=utf-8", "X-XSRF-TOKEN": "eyJpdiI6IjhUNTIydTlQckluOWtcL0pmZU5ZK2RRPT0iLCJ2YWx1ZSI6ImVsenFnOCtzczBHT1g2b3BGeVdBQ3FSSHk4UmJ1UEthMURmWGhpOTFxekZJQ2JPVktQTXpyNWRWdCt2bGtKYzgiLCJtYWMiOiJhYjRkODFjOWVmMWZiZTI3NGJiZjVlOTBiZjRjOWE1ZTJkYzE2N2Y2MmE1MDAyNTJhMTU1ZDNiZTY0NWFlOTFmIn0=" }, "method": "post", "url": "/payroll", "data": "{\"employee_id\":\"1\",\"week_ending\":\"2018-07-29\",\"start\":\"02:30\",\"finish\":\"18:45\",\"job_number\":\"3\",\"climbing\":0,\"day\":\"Tuesday\",\"total\":null,\"period_id\":\"{\\"id\\":1,\\"period_week_ending\\":\\"2018-08-19\\",\\"weeks\\":4,\\"week1\\":\\"2018-07-29\\",\\"week2\\":\\"2018-08-05\\",\\"week3\\":\\"2018-08-12\\",\\"week4\\":\\"2018-08-19\\",\\"week5\\":null,\\"current\\":1,\\"created_at\\":\\"2018-09-13 10:03:03\\",\\"updated_at\\":\\"2018-09-13 10:03:03\\"}\"}" }, "request": {}, "response": { "data": { "message": "Object of class DateInterval could not be converted to string", "exception": "ErrorException", "file": "/Users/paulfinch/Documents/GitHub/pay/vendor/laravel/framework/src/Illuminate/Support/Str.php", "line": 338, "trace": [ { "function": "handleError", "class": "Illuminate\Foundation\Bootstrap\HandleExceptions", "type": "->" }, { "file": "/Users/paulfinch/Documents/GitHub/pay/vendor/laravel/framework/src/Illuminate/Support/Str.php", "line": 338, "function": "substr_replace" }, { "file": "/Users/paulfinch/Documents/GitHub/pay/vendor/laravel/framework/src/Illuminate/Support/Str.php", "line": 315, "function": "replaceFirst", "class": "Illuminate\Support\Str", "type": "::" }, { "file": "/Users/paulfinch/Documents/GitHub/pay/vendor/laravel/framework/src/Illuminate/Database/QueryException.php", "line": 56, "function": "replaceArray", "class": "Illuminate\Support\Str", "type": "::" }, { "file": "/Users/paulfinch/Documents/GitHub/pay/vendor/laravel/framework/src/Illuminate/Database/QueryException.php", "line": 39, "function": "formatMessage", "class": "Illuminate\Database\QueryException", "type": "->" }, { "file": "/Users/paulfinch/Documents/GitHub/pay/vendor/laravel/framework/src/Illuminate/Database/Connection.php", "line": 665, "function": "__construct", "class": "Illuminate\Database\QueryException", "type": "->" }, { "file": "/Users/paulfinch/Documents/GitHub/pay/vendor/laravel/framework/src/Illuminate/Database/Connection.php", "line": 624, "function": "runQueryCallback", "class": "Illuminate\Database\Connection", "type": "->" }, { "file": "/Users/paulfinch/Documents/GitHub/pay/vendor/laravel/framework/src/Illuminate/Database/Connection.php", "line": 459, "function": "run", "class": "Illuminate\Database\Connection", "type": "->" }, { "file": "/Users/paulfinch/Documents/GitHub/pay/vendor/laravel/framework/src/Illuminate/Database/Connection.php", "line": 411, "function": "statement", "class": "Illuminate\Database\Connection", "type": "->" }, { "file": "/Users/paulfinch/Documents/GitHub/pay/vendor/laravel/framework/src/Illuminate/Database/Query/Processors/Processor.php", "line": 32, "function": "insert", "class": "Illuminate\Database\Connection", "type": "->" }, { "file": "/Users/paulfinch/Documents/GitHub/pay/vendor/laravel/framework/src/Illuminate/Database/Query/Builder.php", "line": 2494, "function": "processInsertGetId", "class": "Illuminate\Database\Query\Processors\Processor", "type": "->" }, { "file": "/Users/paulfinch/Documents/GitHub/pay/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Builder.php", "line": 1283, "function": "insertGetId", "class": "Illuminate\Database\Query\Builder", "type": "->" }, { "file": "/Users/paulfinch/Documents/GitHub/pay/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php", "line": 787, "function": "__call", "class": "Illuminate\Database\Eloquent\Builder", "type": "->" }, { "file": "/Users/paulfinch/Documents/GitHub/pay/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php", "line": 752, "function": "insertAndSetId", "class": "Illuminate\Database\Eloquent\Model", "type": "->" }, { "file": "/Users/paulfinch/Documents/GitHub/pay/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php", "line": 615, "function": "performInsert", "class": "Illuminate\Database\Eloquent\Model", "type": "->" }, { "file": "/Users/paulfinch/Documents/GitHub/pay/app/Http/Controllers/PayrollController.php", "line": 47, "function": "save", "class": "Illuminate\Database\Eloquent\Model", "type": "->" }, { "function": "store", "class": "App\Http\Controllers\PayrollController", "type": "->" }, { "file": "/Users/paulfinch/Documents/GitHub/pay/vendor/laravel/framework/src/Illuminate/Routing/Controller.php", "line": 54, "function": "call_user_func_array" }, { "file": "/Users/paulfinch/Documents/GitHub/pay/vendor/laravel/framework/src/Illuminate/Routing/ControllerDispatcher.php", "line": 45, "function": "callAction", "class": "Illuminate\Routing\Controller", "type": "->" }, { "file": "/Users/paulfinch/Documents/GitHub/pay/vendor/laravel/framework/src/Illuminate/Routing/Route.php", "line": 212, "function": "dispatch", "class": "Illuminate\Routing\ControllerDispatcher", "type": "->" }, { "file": "/Users/paulfinch/Documents/GitHub/pay/vendor/laravel/framework/src/Illuminate/Routing/Route.php", "line": 169, "function": "runController", "class": "Illuminate\Routing\Route", "type": "->" }, { "file": "/Users/paulfinch/Documents/GitHub/pay/vendor/laravel/framework/src/Illuminate/Routing/Router.php", "line": 665, "function": "run", "class": "Illuminate\Routing\Route", "type": "->" }, { "file": "/Users/paulfinch/Documents/GitHub/pay/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php", "line": 30, "function": "Illuminate\Routing\{closure}", "class": "Illuminate\Routing\Router", "type": "->" }, { "file": "/Users/paulfinch/Documents/GitHub/pay/vendor/laravel/framework/src/Illuminate/Routing/Middleware/SubstituteBindings.php", "line": 41, "function": "Illuminate\Routing\{closure}", "class": "Illuminate\Routing\Pipeline", "type": "->" }, { "file": "/Users/paulfinch/Documents/GitHub/pay/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php", "line": 151, "function": "handle", "class": "Illuminate\Routing\Middleware\SubstituteBindings", "type": "->" }, { "file": "/Users/paulfinch/Documents/GitHub/pay/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php", "line": 53, "function": "Illuminate\Pipeline\{closure}", "class": "Illuminate\Pipeline\Pipeline", "type": "->" }, { "file": "/Users/paulfinch/Documents/GitHub/pay/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/VerifyCsrfToken.php", "line": 68, "function": "Illuminate\Routing\{closure}", "class": "Illuminate\Routing\Pipeline", "type": "->" }, { "file": "/Users/paulfinch/Documents/GitHub/pay/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php", "line": 151, "function": "handle", "class": "Illuminate\Foundation\Http\Middleware\VerifyCsrfToken", "type": "->" }, { "file": "/Users/paulfinch/Documents/GitHub/pay/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php", "line": 53, "function": "Illuminate\Pipeline\{closure}", "class": "Illuminate\Pipeline\Pipeline", "type": "->" }, { "file": "/Users/paulfinch/Documents/GitHub/pay/vendor/laravel/framework/src/Illuminate/View/Middleware/ShareErrorsFromSession.php", "line": 49, "function": "Illuminate\Routing\{closure}", "class": "Illuminate\Routing\Pipeline", "type": "->" }, { "file": "/Users/paulfinch/Documents/GitHub/pay/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php", "line": 151, "function": "handle", "class": "Illuminate\View\Middleware\ShareErrorsFromSession", "type": "->" }, { "file": "/Users/paulfinch/Documents/GitHub/pay/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php", "line": 53, "function": "Illuminate\Pipeline\{closure}", "class": "Illuminate\Pipeline\Pipeline", "type": "->" }, { "file": "/Users/paulfinch/Documents/GitHub/pay/vendor/laravel/framework/src/Illuminate/Session/Middleware/StartSession.php", "line": 63, "function": "Illuminate\Routing\{closure}", "class": "Illuminate\Routing\Pipeline", "type": "->" }, { "file": "/Users/paulfinch/Documents/GitHub/pay/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php", "line": 151, "function": "handle", "class": "Illuminate\Session\Middleware\StartSession", "type": "->" }, { "file": "/Users/paulfinch/Documents/GitHub/pay/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php", "line": 53, "function": "Illuminate\Pipeline\{closure}", "class": "Illuminate\Pipeline\Pipeline", "type": "->" }, { "file": "/Users/paulfinch/Documents/GitHub/pay/vendor/laravel/framework/src/Illuminate/Cookie/Middleware/AddQueuedCookiesToResponse.php", "line": 37, "function": "Illuminate\Routing\{closure}", "class": "Illuminate\Routing\Pipeline", "type": "->" }, { "file": "/Users/paulfinch/Documents/GitHub/pay/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php", "line": 151, "function": "handle", "class": "Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse", "type": "->" }, { "file": "/Users/paulfinch/Documents/GitHub/pay/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php", "line": 53, "function": "Illuminate\Pipeline\{closure}", "class": "Illuminate\Pipeline\Pipeline", "type": "->" }, { "file": "/Users/paulfinch/Documents/GitHub/pay/vendor/laravel/framework/src/Illuminate/Cookie/Middleware/EncryptCookies.php", "line": 66, "function": "Illuminate\Routing\{closure}", "class": "Illuminate\Routing\Pipeline", "type": "->" }, { "file": "/Users/paulfinch/Documents/GitHub/pay/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php", "line": 151, "function": "handle", "class": "Illuminate\Cookie\Middleware\EncryptCookies", "type": "->" }, { "file": "/Users/paulfinch/Documents/GitHub/pay/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php", "line": 53, "function": "Illuminate\Pipeline\{closure}", "class": "Illuminate\Pipeline\Pipeline", "type": "->" }, { "file": "/Users/paulfinch/Documents/GitHub/pay/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php", "line": 104, "function": "Illuminate\Routing\{closure}", "class": "Illuminate\Routing\Pipeline", "type": "->" }, { "file": "/Users/paulfinch/Documents/GitHub/pay/vendor/laravel/framework/src/Illuminate/Routing/Router.php", "line": 667, "function": "then", "class": "Illuminate\Pipeline\Pipeline", "type": "->" }, { "file": "/Users/paulfinch/Documents/GitHub/pay/vendor/laravel/framework/src/Illuminate/Routing/Router.php", "line": 642, "function": "runRouteWithinStack", "class": "Illuminate\Routing\Router", "type": "->" }, { "file": "/Users/paulfinch/Documents/GitHub/pay/vendor/laravel/framework/src/Illuminate/Routing/Router.php", "line": 608, "function": "runRoute", "class": "Illuminate\Routing\Router", "type": "->" }, { "file": "/Users/paulfinch/Documents/GitHub/pay/vendor/laravel/framework/src/Illuminate/Routing/Router.php", "line": 597, "function": "dispatchToRoute", "class": "Illuminate\Routing\Router", "type": "->" }, { "file": "/Users/paulfinch/Documents/GitHub/pay/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php", "line": 176, "function": "dispatch", "class": "Illuminate\Routing\Router", "type": "->" }, { "file": "/Users/paulfinch/Documents/GitHub/pay/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php", "line": 30, "function": "Illuminate\Foundation\Http\{closure}", "class": "Illuminate\Foundation\Http\Kernel", "type": "->" }, { "file": "/Users/paulfinch/Documents/GitHub/pay/vendor/fideloper/proxy/src/TrustProxies.php", "line": 57, "function": "Illuminate\Routing\{closure}", "class": "Illuminate\Routing\Pipeline", "type": "->" }, { "file": "/Users/paulfinch/Documents/GitHub/pay/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php", "line": 151, "function": "handle", "class": "Fideloper\Proxy\TrustProxies", "type": "->" }, { "file": "/Users/paulfinch/Documents/GitHub/pay/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php", "line": 53, "function": "Illuminate\Pipeline\{closure}", "class": "Illuminate\Pipeline\Pipeline", "type": "->" }, { "file": "/Users/paulfinch/Documents/GitHub/pay/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/TransformsRequest.php", "line": 31, "function": "Illuminate\Routing\{closure}", "class": "Illuminate\Routing\Pipeline", "type": "->" }, { "file": "/Users/paulfinch/Documents/GitHub/pay/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php", "line": 151, "function": "handle", "class": "Illuminate\Foundation\Http\Middleware\TransformsRequest", "type": "->" }, { "file": "/Users/paulfinch/Documents/GitHub/pay/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php", "line": 53, "function": "Illuminate\Pipeline\{closure}", "class": "Illuminate\Pipeline\Pipeline", "type": "->" }, { "file": "/Users/paulfinch/Documents/GitHub/pay/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/TransformsRequest.php", "line": 31, "function": "Illuminate\Routing\{closure}", "class": "Illuminate\Routing\Pipeline", "type": "->" }, { "file": "/Users/paulfinch/Documents/GitHub/pay/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php", "line": 151, "function": "handle", "class": "Illuminate\Foundation\Http\Middleware\TransformsRequest", "type": "->" }, { "file": "/Users/paulfinch/Documents/GitHub/pay/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php", "line": 53, "function": "Illuminate\Pipeline\{closure}", "class": "Illuminate\Pipeline\Pipeline", "type": "->" }, { "file": "/Users/paulfinch/Documents/GitHub/pay/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/ValidatePostSize.php", "line": 27, "function": "Illuminate\Routing\{closure}", "class": "Illuminate\Routing\Pipeline", "type": "->" }, { "file": "/Users/paulfinch/Documents/GitHub/pay/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php", "line": 151, "function": "handle", "class": "Illuminate\Foundation\Http\Middleware\ValidatePostSize", "type": "->" }, { "file": "/Users/paulfinch/Documents/GitHub/pay/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php", "line": 53, "function": "Illuminate\Pipeline\{closure}", "class": "Illuminate\Pipeline\Pipeline", "type": "->" }, { "file": "/Users/paulfinch/Documents/GitHub/pay/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/CheckForMaintenanceMode.php", "line": 62, "function": "Illuminate\Routing\{closure}", "class": "Illuminate\Routing\Pipeline", "type": "->" }, { "file": "/Users/paulfinch/Documents/GitHub/pay/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php", "line": 151, "function": "handle", "class": "Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode", "type": "->" }, { "file": "/Users/paulfinch/Documents/GitHub/pay/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php", "line": 53, "function": "Illuminate\Pipeline\{closure}", "class": "Illuminate\Pipeline\Pipeline", "type": "->" }, { "file": "/Users/paulfinch/Documents/GitHub/pay/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php", "line": 104, "function": "Illuminate\Routing\{closure}", "class": "Illuminate\Routing\Pipeline", "type": "->" }, { "file": "/Users/paulfinch/Documents/GitHub/pay/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php", "line": 151, "function": "then", "class": "Illuminate\Pipeline\Pipeline", "type": "->" }, { "file": "/Users/paulfinch/Documents/GitHub/pay/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php", "line": 116, "function": "sendRequestThroughRouter", "class": "Illuminate\Foundation\Http\Kernel", "type": "->" }, { "file": "/Users/paulfinch/Documents/GitHub/pay/public/index.php", "line": 55, "function": "handle", "class": "Illuminate\Foundation\Http\Kernel", "type": "->" }, { "file": "/Users/paulfinch/.composer/vendor/laravel/valet/server.php", "line": 147, "function": "require" } ] }, "status": 500, "statusText": "Internal Server Error", "headers": { "date": "Thu, 13 Sep 2018 12:07:06 GMT", "cache-control": "no-cache, private", "server": "nginx/1.15.3", "connection": "keep-alive", "x-powered-by": "PHP/7.2.9", "transfer-encoding": "chunked", "content-type": "application/json" }, "config": { "transformRequest": {}, "transformResponse": {}, "timeout": 0, "xsrfCookieName": "XSRF-TOKEN", "xsrfHeaderName": "X-XSRF-TOKEN", "maxContentLength": -1, "headers": { "Accept": "application/json, text/plain, */*", "X-Requested-With": "XMLHttpRequest", "X-CSRF-TOKEN": "gBGZ7I8K3TXKxSiGOyuOefvgewhCzIc4zJO1y0H2", "Content-Type": "application/json;charset=utf-8", "X-XSRF-TOKEN": "eyJpdiI6IjhUNTIydTlQckluOWtcL0pmZU5ZK2RRPT0iLCJ2YWx1ZSI6ImVsenFnOCtzczBHT1g2b3BGeVdBQ3FSSHk4UmJ1UEthMURmWGhpOTFxekZJQ2JPVktQTXpyNWRWdCt2bGtKYzgiLCJtYWMiOiJhYjRkODFjOWVmMWZiZTI3NGJiZjVlOTBiZjRjOWE1ZTJkYzE2N2Y2MmE1MDAyNTJhMTU1ZDNiZTY0NWFlOTFmIn0=" }, "method": "post", "url": "/payroll", "data": "{\"employee_id\":\"1\",\"week_ending\":\"2018-07-29\",\"start\":\"02:30\",\"finish\":\"18:45\",\"job_number\":\"3\",\"climbing\":0,\"day\":\"Tuesday\",\"total\":null,\"period_id\":\"{\\"id\\":1,\\"period_week_ending\\":\\"2018-08-19\\",\\"weeks\\":4,\\"week1\\":\\"2018-07-29\\",\\"week2\\":\\"2018-08-05\\",\\"week3\\":\\"2018-08-12\\",\\"week4\\":\\"2018-08-19\\",\\"week5\\":null,\\"current\\":1,\\"created_at\\":\\"2018-09-13 10:03:03\\",\\"updated_at\\":\\"2018-09-13 10:03:03\\"}\"}" }, "request": {} } }

finchy70 started a new conversation Difference Between Two Time Strings

A Vue component is sending 2 strings representing times to a Laravel controller using axios.

start "09:30:00" finish "14:30:00"

How do I get the time difference between $request->finish - $request->start?

11 Sep
3 months ago

finchy70 left a reply on Displaying Time From Database Query In Vue Without The Seconds.

Thank you @Cronix for the code.

Thank you @cmdobueno . Moving it into methods fixed it.

finchy70 left a reply on Displaying Time From Database Query In Vue Without The Seconds.

I passed item.start to timeFormat like this

<div>{{timeFormat(item.finish)}}}</div>

Here is the computed property

computed: {
            timeFormat(value){
                let time = moment("2018-03-01 " + value).format('hh:mm');
                console.log('Time=', time)
            return time;
            }
        },

The console shows Time = Invalid Time

Also get this error.

app.js:2361 TypeError: _vm.timeFormat is not a function at app.js:48654 at Proxy.renderList (app.js:4325) at Proxy.render (app.js:48648) at VueComponent.Vue._render (app.js:5164) at VueComponent.updateComponent (app.js:3408) at Watcher.get (app.js:3762) at Watcher.run (app.js:3839) at flushSchedulerQueue (app.js:3601) at Array. (app.js:2457) at flushCallbacks (app.js:2378)

10 Sep
3 months ago

finchy70 left a reply on Displaying Time From Database Query In Vue Without The Seconds.

As mentioned I have already tried moment. Could not get it to work. It was outputing Invalid Date.

finchy70 started a new conversation Displaying Time From Database Query In Vue Without The Seconds.

I pass an data from an eloquent query to Vue using props. I want then to display the time data in this collection as 00:00 instead of 00:00:00.

I have tried moment.js with no luck.

How can I do this.

The data is stored in item.start and item.finish in the vue instance.

<template>
    <div>
        <div v-for="item in todays_hours">
            <div class="row">
                <div class="col-2">
                    <div hidden="" ></div>
                </div>
                <div class="col-2" >
                    <div v-text="{{ item.start }}"></div>
                </div>
                <div class="col-2" >
                    <div>{{ item.finish }}</div>
                </div>
                <div class="col-2" >
                    <div v-text="item.job_number"></div>
                </div>
                <div class="col-2" >
                    <div v-text="(item.climbing)?'Yes':'No'"></div>
                </div>
                <div class="col-2" >
                    <button @click="onEdit" class="btn-warning btn-sm mb-1">Edit</button>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
    export default {
        name: 'DisplayHoursComponent',

        props: ['dayCheck', 'hoursWorked'],

        data() {
            return {
                hours_list: this.hoursWorked,
                todays_hours: []
            }
        },

        mounted() {
            for (var i = 0; i < this.hours_list.length; i++) {
                if (this.hours_list[i].day === this.dayCheck) {
                    this.todays_hours.push(this.hours_list[i])
                }
            }

            Event.$on('onAddedEntry', (data) => {
                if(data.day === this.dayCheck){
                    this.todays_hours.push(data);
                }
            })
        },

        methods: {
            onEdit()
            {

            }
        }
    }
</script>

<style scoped>

finchy70 left a reply on Items Added To Array That Is Displayed With V-for Remain Reactive And Mirror Input Box Inputs.

Fixed by emiting a copy of the this.hours data using

''' let data={...this.hours} this.$eventHub.$emit('onAddedEntry', this.hours); '''

05 Sep
3 months ago

finchy70 started a new conversation Problems With Communications Between Components

I have a vue app.js file that looks like this


/**
 * First we will load all of this project's JavaScript dependencies which
 * includes Vue and other libraries. It is a great starting point when
 * building robust, powerful web applications using Vue and Laravel.
 */

require('./bootstrap');

window.Vue = require('vue');
Vue.config.devtools = true;

var bus = new Vue();
Vue.prototype.$bus = bus

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

Vue.component('input-hours', require('./components/InputHoursComponent.vue'));
Vue.component('display-hours', require('./components/DisplayHoursComponent.vue'));

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

My blade file looks like this.


@section('head')

@stop

@section('content')

    <div id="app">
        @foreach($days as $day)
            <div class="row">
                <div class="col-2">{{$day}}</div>
                <div class="col-2">Start</div>
                <div class="col-2">Finish</div>
                <div class="col-2">Job No</div>
                <div class="col-2">Climbing</div>
                <div class="col-2">Total</div>
            </div>

            <display-hours :day-check="'{{$day}}'"
                           :hours-worked="{{ $hours }}"
                           v-cloak>
            </display-hours>

            <input-hours :day-check="'{{$day}}'"
                         :week-ending="'{{$week_ending}}'"
                         :employee-id="'{{$employee->id}}'"
                         v-cloak>
            </input-hours>

        @endforeach
    </div>

    <script src="{{asset('js/app.js')}}"></script>
@stop

display-hours component

<template>
    <div>
        <div v-for="data in this.list">
            <div class="row">
                <div class="col-2">
                    <div hidden="" ></div>
                </div>
                <div class="col-2" >
                    <div>{{data.start}}</div>
                </div>
                <div class="col-2" >
                    <div>{{data.finish}}</div>
                </div>
                <div class="col-2" >
                    <div>{{data.job_number}}</div>
                </div>
                <div class="col-2" >
                    <div>{{(data.climbing)?"Yes":"No"}}</div>
                </div>
                <div class="col-2" >
                    <button @click="onUpdate" class="btn-warning btn-sm mb-1">Edit</button>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
    export default {
        props: ['dayCheck', 'hoursWorked', 'filter'],

        data() {
            return{
                list: []
            }
        },

        mounted() {
            this.onUpdate();

            this.$bus.$on('onAddedEntry', filter => {
                console.log('I am listening : ',
                    this.hoursWorked.push(filter))
                this.onUpdate()
            })



        },

        methods: {
            onUpdate() {
                this.list = []
                this.hoursWorked.forEach(hours => {
                    if(hours.day === this.dayCheck){
                        this.list.push(hours)
                    }
                })
            }
        }

    }
</script>

<style scoped>

input-hours component

<template>
    <div>
        <div class="row">
            <div class="col-2">
                <input hidden="" v-model="hours.day">
            </div>
            <div class="col-2" >
                <input v-model="hours.start">
            </div>
            <div class="col-2" >
                <input v-model="hours.finish">
            </div>
            <div class="col-2" >
                <input v-model="hours.job_number">
            </div>
            <div class="col-2" >
                <select v-model="hours.climbValue">
                    <option v-for="climb in climbing">{{ climb }}</option>
                </select>
            </div>
            <div class="col-2" >
                <button @click="onSave" class="btn-success btn-sm">Save</button>
            </div>
        </div>
        <hr>
    </div>
</template>

<script>
    export default {
        props: ['employeeId', 'dayCheck', 'weekEnding'],

        data() {
            return {
                hours: {
                    start: 0,
                    finish: 0.0,
                    job_number: "",
                    total: 0.0,
                    climbValue: "No",
                    periodCheck: 1,
                    week_ending: this.weekEnding,
                    employee_id: this.employeeId,
                    day: this.dayCheck
                },
                climbing: ['Yes', 'No'],
            }
        },

        methods: {
            onSave(){
                axios.post('/payroll',{
                    employee_id: this.hours.employee_id,
                    week_ending: this.hours.week_ending,
                    start: this.hours.start,
                    finish: this.hours.finish,
                    job_number: this.hours.job_number,
                    climbing: this.hours.climbValue,
                    day: this.hours.day
                })
                .then(response => {})
                .catch(e => {this.errors.push(e)}
                )
                this.$bus.$emit('onAddedEntry', this.hours)
            }
        }
    }
</script>

I'm new to Vue.js but I have managed to get this working to a certain extent. However if I input a new line on any day and save the hours save in database and appear on the webpage. However any additional entries alter all the entries for that day also. So my additional data sent from input component to display component remains reactive until the page is refreshed.

See image

Capture

I need the saved lines to not be reactive. Any ideas what I'm doing wrong?

04 Sep
3 months ago

finchy70 left a reply on Passing A Collection To Vue

That's great thanks. Getting manageable arrays now.

If I wanted to add specific objects that match a specific day to an array then use that as my array to v-for fir display.

I tried

mounted() {
            this.hoursWorked.forEach(hours => {
                if(hours.day === this.dayCheck){
                    this.list.push(hours)
                }
                console.log(hours.day)
            });
        },

but it don't work.

finchy70 left a reply on Passing A Collection To Vue

Im new to Javascript so Im not sure how to iterate through and access Collections.

finchy70 started a new conversation Passing A Collection To Vue

I have a collection from the following query:-

$hours = Hours::where('employee_id', $employee->id)->where('period_id', $request->period)->where('week_ending', $request->week_ending)->get();

I then pass this to my vue component like this:-

                           :hours-worked="'{{ $hours }}'">
            </display-hours>```
I want to be able to iterate through the collection of hours and add the ones that match that day to an new array of Objects I have v-for through to display.

This is what the hours-worked prop looks like when I view it in Vue dev tools.

hoursWorked:"[{"id":2,"employee_id":1,"period_id":2,"week_ending":"2018-08-26","day":"Tuesday","job_number":null,"start":"00:00:00","finish":"00:00:00","climbing":0,"late":0,"created_at":"2018-09-04 08:33:08","updated_at":"2018-09-04 08:33:08"},{"id":3,"employee_id":1,"period_id":2,"week_ending":"2018-08-26","day":"Thursday","job_number":null,"start":"00:00:00","finish":"00:00:00","climbing":0,"late":0,"created_at":"2018-09-04 08:33:10","updated_at":"2018-09-04 08:33:10"},{"id":4,"employee_id":1,"period_id":2,"week_ending":"2018-08-26","day":"Friday","job_number":null,"start":"00:00:00","finish":"00:00:00","climbing":0,"late":0,"created_at":"2018-09-04 08:33:13","updated_at":"2018-09-04 08:33:13"},{"id":5,"employee_id":1,"period_id":2,"week_ending":"2018-08-26","day":"Monday","job_number":null,"start":"00:00:00","finish":"00:00:00","climbing":0,"late":0,"created_at":"2018-09-04 08:34:54","updated_at":"2018-09-04 08:34:54"},{"id":6,"employee_id":1,"period_id":2,"week_ending":"2018-08-26","day":"Wednesday","job_number":null,"start":"00:00:00","finish":"00:00:00","climbing":0,"late":0,"created_at":"2018-09-04 08:35:11","updated_at":"2018-09-04 08:35:11"},{"id":7,"employee_id":1,"period_id":2,"week_ending":"2018-08-26","day":"Monday","job_number":2356,"start":"09:00:00","finish":"17:00:00","climbing":0,"late":0,"created_at":"2018-09-04 08:35:36","updated_at":"2018-09-04 08:35:36"}]"
typeany

29 Aug
3 months ago

finchy70 started a new conversation Query To Return Totals By Job Number

I have a table that stores job numbers and hours as shown here.

Imgur

02 Aug
4 months ago

finchy70 left a reply on Summing Values From Multiple Records

It worked thanks but my query has now become a little more complex..

Example a single record now consists of the following for each day of the week

'job_number_mon1' => '2000' 'hours_worked_mon1' => '5.5'

'job_number_mon2' => '2000' 'hours_worked_mon2' => '4.5'

'job_number_mon3' => '3000' 'hours_worked_mon3' => '5.5'

would return

'2000' => '10' ,

'3000' => '5.5'

I now have to perform the same operation for multiple values in each record across multiple records. Basically each record consist of 3 job numbers for each day with corresponding hours worked and across multiple records I need to return a list of job numbers with the hours worked on them.

01 Aug
4 months ago

finchy70 left a reply on Summing Values From Multiple Records

@Tray2 . Thanks. I will try this tomorrow.

finchy70 started a new conversation Summing Values From Multiple Records

From a collection of hours worked on job numbers I ned to return the distincrt job numbers and the hours worked.

I have a query that returns multiple versions of the following

'job_number' => '2000' 'hours_worked' => '5.5'

Example the following 3 records 1 'job_number' => '2000' 'hours_worked' => '5.5'

2 'job_number' => '2000' 'hours_worked' => '4.5'

3 ''job_number' => '3000' 'hours_worked' => '5.5'

would return '2000' => '10' '3000' => '5.5'

I have no idea how to do this with eloquent. Any ideas?

26 Jul
4 months ago

finchy70 left a reply on Raw Sql To Eloquent

Thanks. I tried that but missed the () after favouritePosts.

Everything now works.

finchy70 left a reply on Raw Sql To Eloquent

Managed to eager load with

public function index()
    {
        $posts =Auth::user()->favouritePosts;
        $posts->load('tags', 'category', 'comments', 'favourite'); 
        return view('posts.index', compact('posts'));
    }

Can't work out how to paginate the results though. Inserting $post->paginate(15); before the return statement throws the following error.

Method Illuminate\Database\Eloquent\Collection::paginate does not exist.

finchy70 left a reply on Raw Sql To Eloquent

How can I then eager load these with that ->with('tags')->with('category')->with('favourite')

finchy70 started a new conversation Raw Sql To Eloquent

I have 3 models. Post User Favorite

Post has posts and the following relationship

public function favourite()
    {
        return $this->hasMany(Favourite::class);
    }

User is users and the following relationship

public function favourite()
    {
        return $this->hasMany(Favourite::class);
    }

Favorite is user_id , post_id when a user likes a post. and the following relationships

class Favourite extends Model
{
    public function post()
    {
        return $this->hasMany(Post::class);
    }

   public function user()
   {
        return $this->hasMany(User::class);
    }

This raw mySql query returns all the posts favorited by a user.

select posts.* from users, posts, favourites where(users.id = '1' && users.id = favourites.user_id && favourites.post_id = posts.id);

Can I create an eloquent query to tidy thisup or if not how do I use this query in laravel.

Thanks
Paul
25 Jul
4 months ago

finchy70 left a reply on Access Collection Passed To Vue As Prop

I need to check if any instance of user_id === the current user (userId).

finchy70 left a reply on Access Collection Passed To Vue As Prop

On further investigation the favourite data object is showing in vue dev-tools.

finchy70 left a reply on Access Collection Passed To Vue As Prop

This has now moved on as I couldn't find a value in the passed prop. Now I have used axios to retrieve the data.

<template>
    <div>
        <i v-show="this.toggle" @click="onClick" style="color: red" class="fas fa-heart"></i>
        <i v-show="!(this.toggle)" @click="onClick" style="color: white" class="fas fa-heart"></i>
    </div>
</template>

<script>

    export default {
        data() {
            return {
                toggle: 0,
                favourite: {}
            }
        },

        props: ['postData', 'userId'],

        created: function () {
            axios.get('post-favourite').then((response) => {
                console.log(response.data)
                this.favourite = response.data
            })
                .catch((error) => {
                    console.log(error)
            });

            console.log("Post is :" + this.postData);
            console.log("User id is: " + this.userId);
        },

        mounted () {
            console.log("postFavourite: " + this.favourite);
        },

        methods: {
            onClick() {
                console.log(this.postData);
                this.toggle = this.toggle ? 0 : 1;
            }
        }
    }
</script>

I assign the response data to this.favourite but when i output this.favourite to the console it shows as [object Object]. If I then remove the assignment the console output is the same [object Object]. I don't think I'm assigning the data to this.favourite properly.

Anyone see what I'm doing wrong?

24 Jul
4 months ago

finchy70 left a reply on Access Collection Passed To Vue As Prop

Here in my component code and the console output

<script>
    export default {
        props: ['postData', 'postFavourite', 'userId']
        ,
        data() {
            return {
                toggle: 0,
            }
        },

        mounted() {
            console.log("Post is :"+ this.postData)
            console.log("User id is: "+ this.userId)
            console.log("Favourite Object is :" +this.postFavourite);
            let pf = _.find(this.postFavourite, { user_id: this.user_id });
            console.log("pf is:" + pf)
        },

        methods: {
            onClick() {
                console.log(this.postData);
                this.toggle = this.toggle ? 0 : 1;
            }
        }
    }
</script>```


<blockquote class="imgur-embed-pub" lang="en" data-id="2MiaYBG"><a href="//imgur.com/2MiaYBG">View post on imgur.com</a></blockquote><script async src="//s.imgur.com/min/embed.js" charset="utf-8"></script>

finchy70 left a reply on Access Collection Passed To Vue As Prop

@burlresearch pf is returned as undefined regardless of wether the id matches or not.

23 Jul
4 months ago

finchy70 started a new conversation Access Collection Passed To Vue As Prop

I have passed a collection to vue from laravel. It's referenced with postFavourite and contains the following data

"[{"id":1,"user_id":1,"post_id":1,"created_at":"2018-07-23 23:06:41","updated_at":"2018-07-23 23:06:41"}, {"id":2,"user_id":2,"post_id":1,"created_at":"2018-07-23 23:06:41","updated_at":"2018-07-23 23:06:41"}]"

How do I loop through this in the vue mounted component to check the user_id against the current user which is userId.

finchy70 left a reply on Vue Like Component In Posts View

Here is my post view.

 @foreach($posts as $post)
        <div class="row">
            <div class="col-2">
                <div id="app">
                    <favorite :post-data="'{{ $post->id }}'" :post-favourite="1"></favorite>
                </div>
                <a href="/posts/{{$post->user->id}}/user">{{$post->user->name}}</a><br/>
                {{Carbon\Carbon::parse($post->created_at)->format('d-m-Y')}}<br>
                <img class="avatar-img" src="https://www.gravatar.com/avatar/{{md5( strtolower( trim($post->user->email)))}}?d=wavatar" width=40 height=40/><br/>
                <p class="joined-text mb-0">Joined {{Carbon\Carbon::parse($post->user->created_at)->diffForHumans()}}.</p>
                <p class="joined-text mb-0">Posted {{Carbon\Carbon::parse($post->created_at)->diffForHumans()}}.</p>
                <p class="joined-text mb-0">Posts: {{$post->user->posts_count}}</p>

            </div>
            <div class="col-6">
                <div class="row">
                    <span class="font-weight-bold font-italic mb-2"><a href="/posts/{{$post->id}}">{{$post->title}}</a></span>
                </div>
                <div class="row">
                    <div>
                        <p class="font-italic d-inline-block">{!! strip_tags(str_limit($post->body, 140, '   ......')) !!}</p>
                    </div>
                    <p class="bottom-right comments">Comments: {{count($post->comments)}} - Views: {{$post->read_counter}}</p>
                    <p></p>
                </div>


            </div>

            <div class="col-2">
                @if(($post->category_id)<>null)
                    <a href="/posts/categories/{{$post->category_id}}">{{$post->category->name}}</a>
                @endif
            </div>

            <div class="col-2">
                @if (($post->tags)->isNotEmpty())
                    @foreach($post->tags as $tag)
                        <a class="badge badge-info" href="/posts/tags/{{$tag->id}}">{{$tag->name}}</a>
                    @endforeach
                @endif
            </div>
        </div>

        <hr class="custom-hr-divider"/>

    @endforeach 

The favourite component only shows in the first post.

finchy70 left a reply on Vue Like Component In Posts View

@m7vm7v . I have tried that but the button in my template only sits below the first post although its inside the loop.

22 Jul
4 months ago

finchy70 started a new conversation Vue Like Component In Posts View

Is it possible to create a vue like component which can be toggled and have the component in each post on a blade posts.index view or is it not possible to have multiple instances of a single component on one page? As you can see I'm new to Vue.js.

19 Jul
4 months ago

finchy70 started a new conversation Create Layout From Database Objects In Blade Template

I'm building an App that displays Operations, the risks involved, and the measures / mitigation required to minimise the risk.

They are accessed through a hasManyThrough relationship.

My problem is if it have a collection Operations from eloquent and want to loop through the Operations, Risks, and Measures i use the following.

@foreach($job->operations as $operation)
    <p>{{$operation->operation_name}}</p>
     @foreach($operation->risks as $risk)
         <p>{{$risk->risk_name}}</p>
    @foreach($risk->measures as $measure)
            <p>{{ $measure->measure_name }}</p>             
        @endforeach
    @endforeach
@endforeach 

Now the issue is I want to layout the results like this.

I have tried bootstrap rows and cols but cant get it to layout as required. Don't really understand css grid so was wondering if someone could help.

Thanks Paul.

02 Jul
5 months ago

finchy70 left a reply on Ajax Request To A Laravel Controller

Got it working by returning the $data and checking the result in the developers tools response tab on Chrome.

Thank you.

finchy70 left a reply on Out Put PDF's From Laravel Using Bootstrap 4 Row And Col Classes.

Also tried barryvdh/laravel-snappy but cant get this to work on my Mac.

finchy70 started a new conversation Out Put PDF's From Laravel Using Bootstrap 4 Row And Col Classes.

Anyone know of a package that will allow me to generate pdf's from a html page. I have been using barryvdh/laravel-dompdf but this does not work with Bootstrap 4.

01 Jul
5 months ago

finchy70 left a reply on Ajax Request To A Laravel Controller

Console not showing any errors.

finchy70 started a new conversation Ajax Request To A Laravel Controller

I have a simple like button

<button type="like" data-my-attribute="{{$post->id}}" class="like btn btn-sm btn-primary">Like</button>

And some Javascript

<script>
        $.ajaxSetup({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            }
        });
        $('.like').on('click', function(){
            $.ajax({
                type: "POST",
                url: '/like',
                data: {
                    id: $(this).data('myAttribute') },
                success: function(data){
                    alert('its done')
                },
            });
        })
    </script>

My routes file looks like this

/*Like Route*/
Route::post('/like','[email protected]')->name('like.store');

and my controller like this

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class LikeController extends Controller
{

    public function __construct()
    {
        $this->middleware('auth');
    }

    /**
     * @param Request $request
     */
    public function store(Request $request)
    {
        $data = $request->all();
        dd($data);

    }
}

I get the 'its done' alert but no errors and my controller is not firing.

I'm a complete newbie with Javascript. Have I done something wrong?

29 Jun
5 months ago

finchy70 left a reply on Associating Models Through BelongsToMany Relationships

Update: Changing the controller code to

$job = Job::find($id)->with('operations.risks.measures')->first();

Allowed me to access the job in the view with just $job instead of $job[0]

That looks better.

finchy70 left a reply on Associating Models Through BelongsToMany Relationships

Now my controller look slike this.

public function show($id)
    {
        $job = Job::find($id)->with('operations.risks.measures')->get();
        return view('jobs.show', compact('job'));
    }

My view looks like this.

@extends('main')

@section('content')


    <h1>{{$job[0]->job_number}} - {{$job[0]->site}}  -  {{$job[0]->client}}</h1>

    @foreach($job[0]->operations as $operation)
        <h1>{{$operation->operation_name}}</h1>
        @foreach($operation->risks as $risk)
            <h3>{{$risk->risk_name}}</h3>
            @foreach($risk->measures as $measure)
                <h6>{{$measure->measures}}</h6>
            @endforeach
        @endforeach
    @endforeach
@stopassola 

And I had errors in my models. They now look like this

namespace App;

use Illuminate\Database\Eloquent\Model;

class Job extends Model
{
    public function operations()
    {
        return $this->belongsToMany(Operation::class, 'jobs_operations','job_id', 'operation_id');
    }
}

namespace App;

use Illuminate\Database\Eloquent\Model;

class Operation extends Model { public function risks() { return $this->belongsToMany(Risk::class, 'operations_risks', 'risk_id', 'operation_id'); } public function jobs() { return $this->belongsToMany(Job::class, 'operations_risks', 'operation_id', 'job_id'); } }


namespace App;

use Illuminate\Database\Eloquent\Model;

class Risk extends Model { public function measures() { return $this->belongsToMany(Measure::class, 'measures_risks', 'risk_id', 'measure_id'); }

public function operations()
{
    return $this->belongsToMany(Operation::class, 'operations_risks', 'risk_id', 'operation_id');
}

}


namespace App;

use Illuminate\Database\Eloquent\Model;

class Measure extends Model { public function risks() { return $this->belongsToMany(Risk::class, 'measures_risks', 'measure_id', 'risk_id'); }

}

I extended the belongsToMany line to incorporate additional info.
return $this->belongsToMany(*class here*, '8name of pivot table here8', '*this models id col*', '*model your referencing's id col*');

So on my Measure model it reads 

public function risks() { return $this->belongsToMany(Risk::class, 'measures_risks', 'measure_id', 'risk_id'); }


Not sure if this is the most efficient way but it does now work as I want it to.

Thanks all for the help.
Please feel free to post any improvements I could make.

finchy70 left a reply on Associating Models Through BelongsToMany Relationships

I also need to relate specific risks to operations, and operations jobs.

finchy70 left a reply on Associating Models Through BelongsToMany Relationships

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Job extends Model
{
    public function operations()
    {
        return $this->belongsToMany(Operation::class);
    }
}
<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Operation extends Model
{
    public function risks()
    {
        return $this->belongsToMany(Risk::class);
    }
    public function jobs()
    {
        return $this->belongsToMany(Job::class);
    }
}
<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Risk extends Model
{
    public function measures()
    {
        return $this->belongsToMany(Measure::class);
    }

    public function operations()
    {
        return $this->belongsToMany(Operation::class);
    }
}
<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Measure extends Model
{
    public function risks()
    {
        return $this->belongsToMany(Risk::class);
    }


}

finchy70 started a new conversation Associating Models Through BelongsToMany Relationships

I have 4 models. Job, Operation, Risk, and Measure. A Job can have many operations. An Operation can have many risks. A Risk can have many measures.

I have intermediate tables jobs_operations, operations_risks, and risks_measures.

The job model has a belongsToMany relationship with Operations. The Operation model has a belongsToMany relationship with Job and Risk. The Risk model has a belongsToMany relationship with Operation and Measure. The measure model has a belongsToMany relationship with Risk.

Is there a specific naming convention for the intermediate tables or have I just missed something out?

The following code in my JobController

        $job = Job::find($id)->with('operations')->with('risks')->with('measures')->get();
        return view('jobs.show', compact('job'));

creates the following error.

SQLSTATE[42S02]: Base table or view not found: 1146 Table 'risks.job_operation' doesn't exist (SQL: select `operations`.*, `job_operation`.`job_id` as `pivot_job_id`, `job_operation`.`operation_id` as `pivot_operation_id` from `operations` inner join `job_operation` on `operations`.`id` = `job_operation`.`operation_id` where `job_operation`.`job_id` in (1))

If anyone can help I'll be very greatful.