skoobi

Member Since 6 Years Ago

Ceredigion

Experience Points
42,950
Total
Experience

2,050 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
280
Lessons
Completed
Best Reply Awards
9
Best Reply
Awards
  • start your engines Created with Sketch.

    Start Your Engines

    Earned once you have completed your first Laracasts lesson.

  • first-thousand Created with Sketch.

    First Thousand

    Earned once you have earned your first 1000 experience points.

  • 1-year Created with Sketch.

    One Year Member

    Earned when you have been with Laracasts for 1 year.

  • 2-years Created with Sketch.

    Two Year Member

    Earned when you have been with Laracasts for 2 years.

  • 3-years Created with Sketch.

    Three Year Member

    Earned when you have been with Laracasts for 3 years.

  • 4-years Created with Sketch.

    Four Year Member

    Earned when you have been with Laracasts for 4 years.

  • 5-years Created with Sketch.

    Five Year Member

    Earned when you have been with Laracasts for 5 years.

  • school-in-session Created with Sketch.

    School In Session

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

  • welcome-newcomer Created with Sketch.

    Welcome To The Community

    Earned after your first post on the Laracasts forum.

  • full-time-student Created with Sketch.

    Full Time Learner

    Earned once 100 Laracasts lessons have been completed.

  • pay-it-forward Created with Sketch.

    Pay It Forward

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

  • subscriber Created with Sketch.

    Subscriber

    Earned if you are a paying Laracasts subscriber.

  • lifer Created with Sketch.

    Lifer

    Earned if you have a lifetime subscription to Laracasts.

  • evangelist Created with Sketch.

    Laracasts Evangelist

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

  • chatty-cathy Created with Sketch.

    Chatty Cathy

    Earned once you have achieved 500 forum replies.

  • lara-veteran Created with Sketch.

    Laracasts Veteran

    Earned once your experience points passes 100,000.

  • 10k-strong Created with Sketch.

    Ten Thousand Strong

    Earned once your experience points hits 10,000.

  • lara-master Created with Sketch.

    Laracasts Master

    Earned once 1000 Laracasts lessons have been completed.

  • laracasts-tutor Created with Sketch.

    Laracasts Tutor

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

  • laracasts-sensei Created with Sketch.

    Laracasts Sensei

    Earned once your experience points passes 1 million.

  • top-50 Created with Sketch.

    Top 50

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

Level 9
42,950 XP
Sep
03
1 month ago
Activity icon

Replied to Wrapping API Resource With Something Other Than Data

Thanks for that, Ive just started using API Resources and now starting to see how they're used and work.

Cheers.

Activity icon

Replied to (1/1) TokenMismatchException In VerifyCsrfToken.php (line 68)

You'll need to place the <meta name="csrf-token" content="{{ csrf_token() }}"> up in the header of your main blade template.

Like so

<!doctype html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width, initial-scale=1">

	<!-- CSRF Token -->
	<meta name="csrf-token" content="{{ csrf_token() }}">

	<title>{{ config('app.name', 'MY APP') }}</title>

	<!-- Scripts -->
	<script src="{{ asset('js/app.js') }}" defer></script>
	<!-- Styles -->
	<link href="{{ asset('css/app.css') }}" rel="stylesheet">
</head>
<body>
Activity icon

Replied to (1/1) TokenMismatchException In VerifyCsrfToken.php (line 68)

Not sure if this helps but do you have this in the template header.

<meta name="csrf-token" content="{{ csrf_token() }}">

and try

@csrf

// instead of
{{ csrf_field() }}
Activity icon

Started a new Conversation Wrapping API Resource With Something Other Than Data

Hi all...

I've been trying to wrap my API Resource in a wrapper named modules rather than data but it wont change the output when I add private static $wrap = 'modules';

The other output I needed to get right was to remove the outer shell as it were for the users api resource so it doesn't have the data in it at all...

So, here's my Modules API Resource.

// Route

Route::middleware('auth:api')->get('/modules', function () {
    return ModulesResource::collection(Module::active()->get());
});


//ModulesResource.php 

class ModulesResource extends JsonResource
{
    /**
     * The "data" wrapper that should be applied.
     *
     * @var string
     */
    public static $wrap = 'modules';

    /**
     * Transform the resource collection into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function toArray($request)
    {
        return [
            'id' => $this->id,
            'module_title' => $this->title,
            'playlist_steps' => ModuleStepsResource::collection($this->module_steps)
        ];
    }
}

but the output is still

// What it outputs
{
    "data": [
        	{}
	]
}

// What I want it to output
{
    "modules": [
        	{}
	]
}

and for my users resource I want to get rid of the above "data" part completely if thats possible.

Any help would be grateful.

Cheers

Sep
02
1 month ago
Activity icon

Replied to API Resources Return As Array

Hi @frankielee.

Ive been staring at that for hours and hadn't spotted the brackets... Code blind or what.

Thank you for your help but this returned the wrong ids for some reason.

@tykus that worked perfectly.. thank you

Activity icon

Started a new Conversation API Resources Return As Array

Hi.

Im a bit stuck on returning an api resource with a relationship and trying to get it to format the way I need.

Heres the UsersResource file::

/**
 * Transform the resource into an array.
 *
 * @param  \Illuminate\Http\Request  $request
 * @return array
 */
public function toArray($request)
{
    return [
        'id' => $this->unique_id,
        'name' => $this->name,
        'reference' => $this->reference,
        'modules' => UserModulesResource::collection($this->modules),
    ];
}

UserModuleResource file::

/**
 * Transform the resource into an array.
 *
 * @param  \Illuminate\Http\Request  $request
 * @return array
 */
public function toArray($request)
{
    return [
        $this->module->id
    ];
}

The layout im trying to get is ::

{
	"id": 5f451a3c7827a,
	"name": "Test User 1",
	"reference": 1234567890,
	"modules": [1,2,3]
},

Actual output ::


[
    {
        "id": "5f451a3c7827a",
        "name": "Test User 1",
        "reference": "1234567890",
        "modules": [
            [
                1
            ],
            [
                2
            ],
	    [
                2
            ]
        ]
    }
]

How do I get it looking as the one im trying to replicate?

Many thanks

Aug
07
2 months ago
Activity icon

Started a new Conversation Vapor AWS IAM Access Denied

Hi.

Im trying to setup Vapor on my machine but every time I try "vapor init" and create a new project I get through the app name, location and then I get::

Whoops! There were some problems with your request.

    - There was a problem creating one or more AWS resources for your project. AWS Error Message: Access Denied

now obviously theres an issue with the access credentials, but Ive gone through the setup process of creating a new IAM user with 'AdministratorAccess' and I've copied and pasted the credentials into "Team Settings > AWS Accounts". Ive tried this several times but I keep getting the above error.

Any ideas??

many thanks

Aug
03
2 months ago
Activity icon

Replied to Creating A Json Api And Creating Multiple Charts

Ok... Solved using collections :)

Route::get('/v1/questions/{sheet_id}', function (Request $request) {
    $collection = Question::where('sheet_id', $request->sheet_id)->with('answers')->get();

    $dataset = $collection->map(function ($item) {
        return [
                'title' => $item['title'],
                'question' => $item['question'],
                'answers' => [
                    collect($item['answers']->where('answer', 1))->count(),
                    collect($item['answers']->where('answer', 2))->count(),
                    collect($item['answers']->where('answer', 3))->count(),
                    collect($item['answers']->where('answer', 4))->count(),
                ]
            ];
    })->all();

    return  response()->json(['dataset' => $dataset], Response::HTTP_OK);
});

Turns out the database that I was collecting from, hadn't transferred the data across correctly and as a result had the exact same figures throughout!!!! Gutted isn't the word... I knew I wasn't going mad

Activity icon

Replied to Creating A Json Api And Creating Multiple Charts

Im getting the correct format for the output but for some reason its not incrementing. Its the same result for every answer for every question.

Route::get('/v1/questions/{sheet_id}', function (Request $request) {
    
$collection = Question::where('sheet_id', $request->sheet_id)->with('answers')->get();

    $questions = Question::where('sheet_id', $request->sheet_id)->with('answers')->get();
    $dataset = [];

    foreach ($questions as $q) {
        $one = 0;
        $two = 0;
        $three = 0;
        $four = 0;

        foreach ($q->answers as $answer) {
            if ($answer->answer == 1 && $answer->question_id == 2) {
                $one++;
            } elseif ($answer->answer == 2 && $answer->question_id == $q->id) {
                $two++;
            } elseif ($answer->answer == 3 && $answer->question_id == $q->id) {
                $three++;
            } elseif ($answer->answer == 4 && $answer->question_id == $q->id) {
                $four++;
            }
        }

        array_push(
            $dataset,
            [
                'id' => $q->id,
                'title' => $q->title,
                'question' => $q->question,
                'answers' => [
                    $one,
                    $two,
                    $three,
                    $four,
                ]
            ]
        );
    }
    return  response()->json(['dataset' => $dataset], Response::HTTP_OK);
});

The results::

{
  "dataset": [
    {
      "id": 1,
      "title": "Q1",
      "question": "My question 1.",
      "answers": [
        0,
        29,
        86,
        24
      ]
    },
    {
      "id": 2,
      "title": "Q2",
      "question": "My question 2",
      "answers": [
        1,
        29,
        86,
        24
      ]
    },
{
      "id": 3,
      "title": "Q3",
      "question": "My question 3",
      "answers": [
        1,
        29,
        86,
        24
      ]
    },
}

Unfortunately the answers are wrong/all the same. The answers are correct for the first question but thats it.

Ill try to lookup collections and see if I can do anything with that to filter and map the array.

Sorry here's my revised collection::

Route::get('/v1/questions/{sheet_id}', function (Request $request) {
    $collection = Question::where('sheet_id', $request->sheet_id)->with('answers')->get();

    $dataset = $collection->map(function ($item) {
        return [
            'id' => $item['id'],
            'title' => $item['title'],
            'question' => $item['question'],
            'answers' => [
                12,23,44,22
            ]
        ];
    });

    return  response()->json(['dataset' => $dataset], Response::HTTP_OK);
});

Just need to fill in the answers.

Activity icon

Replied to Creating A Json Api And Creating Multiple Charts

Hi @msslgomez . Thanks for your reply, definitely reassures me that im heading in the right direction now.

After a walk down the beach, it helped clear things a bit, but this is what I've been working on:

Route::get('/v1/questions/{sheet_id}', function (Request $request) {
    $questions = Question::where('sheet_id', $request->sheet_id)->with('answers')->get();
    $question = [];

    foreach ($questions as $items) {
        array_push(
            $question,
            [
                'title' => $items->title,
                'question' =>$items->question,
                'answers' => [
                    $items->answers->where('answer', 1)->count(),
                    $items->answers->where('answer', 2)->count(),
                    $items->answers->where('answer', 3)->count(),
                    $items->answers->where('answer', 4)->count(),
                ]
            ]
        );
    }

    return  response()->json(['question' => $question], Response::HTTP_OK);
});

I need to add the counter ideally now as the ->count didnt work,

Thank you

Activity icon

Started a new Conversation Creating A Json Api And Creating Multiple Charts

Hi. Sorry this is an update from a post I did a little while ago...

I really have no idea how to do this (my brain is cooked), so hoping someone can help me out. I wanted to try something completely out of my depth and now that i've realised its out of my depth, Its frustrating that I cant find the answer...

What I want to do is, create multiple charts in VueJs from a laravel collection and relationship. So...

I have the api route setup which gets a list of answers that has an answers relationship that belongs to that question.

In Vue, im using axios to get the data and saved it into an array. I then use v-for to iterate through the questions so I can display them in separate boxes with the question text in it. This all works perfect.

The issue im facing is now getting the answers and doing something meaningful with them.

What I need to do is group the answers (answers are either, 1,2,3,4) and count how many answered 1, how many answered 2 etc.

Then I need to display this in the chart as an array [23,45,32,2], but for the correct question.

Heres the route and api call:

Route::get('/v1/questions/{sheet_id}', function (Request $request) {
    $questions = Question::where('sheet_id', $request->sheet_id)->with('answers')->get();
    return  response()->json(['questions' => $questions], Response::HTTP_OK);
});

Heres The Vue template so far:

<template>
	<div>
		<div class="mt-5 grid grid-cols-1 gap-5 sm:grid-cols-2 lg:grid-cols-3">
			<div v-for="item in questions">


                <dl>
                   <dt class="text-sm leading-5 font-medium">
                      <strong class="text-gray-700">{{ item.title }}</strong> - <strong class="text-gray-500">{{ item.question }}</strong>
                  </dt>
                  <dd>
                      <apexchart
                      type="radialBar"
                      height="390"
                      :options="chartOptions"
                      :series="series">
                  </apexchart>
              </dd>
          </dl>


      </div>
  </div>
</div>
</template>

And here's the script::

<template>
    <div>
        <div class="mt-5 grid grid-cols-1 gap-5 sm:grid-cols-2 lg:grid-cols-3">
            <div v-for="item in questions">

                <div class="flex flex-col justify-between bg-white overflow-hidden shadow rounded-lg">
                    <div class="px-4 py-5 sm:p-6">
                        <div class="flex items-center">
                            <div class="ml-5 w-0 flex-1">

                                <dl>
                                    <dt class="text-sm leading-5 font-medium">
                                        <strong class="text-gray-700">{{ item.title }}</strong> - <strong class="text-gray-500">{{ item.question }}</strong>
                                    </dt>
                                    <dd>
                                        <apexchart
                                            type="radialBar"
                                            height="390"
                                            :options="chartOptions"
                                            :series="series">
                                        </apexchart>
                                </dd>
                            </dl>

                        </div>
                    </div>
                </div>
            </div>

        </div>
    </div>
</div>
</template>

<script>

    import VueApexCharts from 'vue-apexcharts'

    Vue.component('apexchart', VueApexCharts)

    export default {

        props: {
            sheet_id: Number
        },

        data: function() {
            return {
                questions:[],
                answers: [],
                series: [90,34,56,76],

                chartOptions: {
                    chart: {
                        height: 390,
                        type: 'radialBar',
                    },
                    plotOptions: {
                        radialBar: {
                            offsetY: 0,
                            startAngle: 0,
                            endAngle: 270,
                            hollow: {
                                margin: 5,
                                size: '30%',
                                background: 'transparent',
                                image: undefined,
                            },
                            dataLabels: {
                                name: {
                                    show: false,
                                },
                                value: {
                                    show: false,
                                }
                            }
                        }
                    },
                    colors: ['#E53E3E', '#DD6B20', '#3182CE', '#38A169'],
                    labels: ['Strongly Disagree', 'Disagree', 'Agree', 'Strongly Agree' ],
                    legend: {
                        show: true,
                        position: 'bottom'
                    },
                    legend: {
                        show: true,
                        floating: true,
                        fontSize: '12px',
                        position: 'left',
                        offsetY: 10,
                        labels: {
                            useSeriesColors: true,
                        },
                        markers: {
                            size: 0
                        },
                        formatter: function(seriesName, opts) {
                            return seriesName + ":  " + opts.w.globals.series[opts.seriesIndex]
                        },
                        itemMargin: {
                            vertical: 3
                        }
                    },
                    responsive: [{
                        breakpoint: 480,
                        options: {
                            legend: {
                                show: false
                            }
                        }
                    }]
                },

            }
        },

        created() {
            this.getQuestions()
        },

        methods: {

            getQuestions() {
                axios.get('/api/v1/questions/' + this.sheet_id)
                .then((response)=>{
                    this.questions = response.data.questions
                    this.answers = this.questions['answers']
                })
            },

        },

    };

</script>

I cant figure out how to iterate through the answers and display them in the correct chart for the correct question.

Any pointers or help would be great.

Many thanks

Activity icon

Started a new Conversation ApexCharts And VueJS Resetting Data

Hi.

What Im trying toileting do::

I have a set of answers that relate to questions and I want to get the count of the same answers per question. So if question 1 has the answer of 1 then I want to count the amount of people answered 1 etc.

So the temp api ive done to grab that sheet and return the data is here::

Route::get('/v1/answers/{sheet_id}/{question}', function (Request $request) {

        $sheet = SheetA::all();
        $response = response()->json([
            $sheet->where($request->question, 1)->count($request->question),
            $sheet->where($request->question, 2)->count($request->question),
            $sheet->where($request->question, 3)->count($request->question),
           $sheet->where($request->question, 4)->count($request->question)
        ], Response::HTTP_OK);
   
    }

    return $response;
});

I know theres a better way to grab and display the data, but just wanting to get the data to test at moment.

Im pretty sure I've done something wrong here but when the page is loaded it displays the initially set data, then the component it mounted and it then displays the data thats grabbed from the API, but then once the page is loaded, it goes back to the defaulted 0.

For the blade template ::

@foreach($questions as $q)
	<div class="flex flex-col justify-between bg-white overflow-hidden shadow rounded-lg">
		<div class="px-4 py-5 sm:p-6">
			<div class="flex items-center">
				<div class="ml-5 w-0 flex-1">
					<dl>
						<dt class="text-sm leading-5 font-medium">
							<strong class="text-gray-700">{{ $q->title }}</strong> - <strong class="text-gray-500">{{ $q->question }}</strong>
						</dt>
					<dd>
						<report-answers :sheet_id="{!! $q->sheet_id !!}" question="{!! \Str::lower($q->title) !!}"></report-answers>
					</dd>
				</dl>
			</div>
		</div>
	</div>
	</div>
@endforeach

<template>
<div>
	<apexchart type="radialBar" height="390" :options="chartOptions" :series="series">
		</apexchart>
</div>
</template>

<script>

	import VueApexCharts from 'vue-apexcharts'

	Vue.component('apexchart', VueApexCharts)

	export default {

		props: {
			question: String,
			sheet_id: Number
		},

		data: function() {
			return {
				answers: [],

				chartOptions: {
					chart: {
						height: 390,
						type: 'radialBar',
					},
					plotOptions: {
						radialBar: {
							offsetY: 0,
							startAngle: 0,
							endAngle: 270,
							hollow: {
								margin: 5,
								size: '30%',
								background: 'transparent',
								image: undefined,
							},
							dataLabels: {
								name: {
									show: false,
								},
								value: {
									show: false,
								}
							}
						}
					},
					colors: ['#E53E3E', '#DD6B20', '#3182CE', '#38A169'],
					labels: ['Strongly Disagree', 'Disagree', 'Agree', 'Strongly Agree' ],
					legend: {
						show: true,
						position: 'bottom'
					},
					legend: {
						show: true,
						floating: true,
						fontSize: '12px',
						position: 'left',
						offsetY: 10,
						labels: {
							useSeriesColors: true,
						},
						markers: {
							size: 0
						},
						formatter: function(seriesName, opts) {
							return seriesName + ":  " + opts.w.globals.series[opts.seriesIndex]
						},
						itemMargin: {
							vertical: 3
						}
					},
					responsive: [{
						breakpoint: 480,
						options: {
							legend: {
								show: false
							}
						}
					}]
				},

				series: [0,0,0,0]

			}
		},

		mounted() {
			this.updateChart()

		},



		methods: {

			updateChart() {
				axios.get('/api/v1/answers/' + this.sheet_id + '/' + this.question)
				.then((response)=>{
					this.series = response.data
					console.log(response.data)
				})
			},
		},

	};

</script>

any ideas???

Many thanks

Jul
15
3 months ago
Activity icon

Replied to Not Deleting Or Updating

Hi @snapey, no just good old regular deletes. Im sure its got something to do with the auth, but the response doesn't show up much to point to it. Thank you anyway

Activity icon

Replied to Not Deleting Or Updating

I've tried a different approach which kind of fixes one problem.

I've added a setup method to create an admin user and authenticate the user. This allows me to delete and update the user....

Activity icon

Started a new Conversation Not Deleting Or Updating

Hi. Im running a test to create/update/delete which has the 'auth' middleware on it.

For some reason I can create the user and run the other tests, but as soon as I try to update and delete it fails. If I try it in the app itself it all works perfect. I've been working on this all day and now banging my head against a brick wall.

Heres the delete test::


// THE CONTROLLER 

/**
 * Remove the specified resource from storage.
 *
 * @param \App\Models\User $user
 * @return \Illuminate\Http\Response
 */
public function destroy(User $user)
{
    $user->delete();
    return redirect()->route('users.index');
}



// THE TEST

use RefreshDatabase, WithFaker, WithoutMiddleware;

/** @test */
public function a_user_can_be_deleted()
{
    // $this->withoutExceptionHandling();
    // Creates a user
    $response = $this->create_user($this->user_data());
    $this->assertCount(1, User::all());
    $response = $this->delete('/admin/users/delete/' . User::first()->id);
    dd(User::first());
    $this->assertCount(0, User::all());

    $response->assertRedirect('/admin/users');
}


// THE ERROR

  Failed asserting that actual size 1 matches expected size 0.

  at tests/Feature/UserManagementTest.php:95
    91|
    92|
    93|         $response = $this->delete('/admin/users/delete/' . User::first()->id);
    94|         // dd(User::first());
  > 95|         $this->assertCount(0, User::all());
    96|
    97|         $response->assertRedirect('/admin/users');
    98|     }
    99|




Again... If I try it through the app, it all works perfect! I just cannot pin point the issue. Also worth pointing out, that I have a organisation test which mirrors the tests and that works!!!

I get the exact same on the update. Any ideas. Im guessing its something i've missed...

Many thanks

Jul
01
3 months ago
Activity icon

Replied to Testing Password Confirmed Field

Hi @vincent15000.

If I go through and add a user manually it all works as it should but when I run phpunit it fails to add the record as it fails the validation. If I remove confirmed it all passes.

Heres the password inputs

<div class="sm:col-span-4">
    <label for="email" class="block text-sm font-medium leading-5 text-gray-700">
        Password
    </label>
    <div class="mt-1 rounded-md shadow-sm">
        <input id="password" name="password" type="password"
            class="form-input block w-full transition duration-150 ease-in-out sm:text-sm sm:leading-5" />
    </div>
    @error('password') <span class="text-red-600 text-xs">{{ $message }}</span> @enderror
</div>

<div class="sm:col-span-4">
    <label for="email" class="block text-sm font-medium leading-5 text-gray-700">
        Confirm Password
    </label>
    <div class="mt-1 rounded-md shadow-sm">
        <input id="password_confirmation" name="password_confirmation" type="password"
            class="form-input block w-full transition duration-150 ease-in-out sm:text-sm sm:leading-5" />
    </div>
    @error('password_confirmation') <span class="text-red-600 text-xs">{{ $message }}</span> @enderror
</div>

The Validation rules

 /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'name' => 'required',
            'email' => 'required',
            'password' => 'required|string|min:8|confirmed',
            'status' => 'required'
        ];
    }


Activity icon

Started a new Conversation Testing Password Confirmed Field

Hi. I've got my tests running and they all are green, but I've now added Validation to the mix and in particular the confirmed validation rule for the password.

With this it fails but when I remove it it shows up. Im guessing that I need to add the password_confirmation data in somewhere, but not sure where.

Heres the code:

/** Setup Test */
    public function setUp() : void
    {
        parent::setUp();
        $user = factory(User::class)->create();
        $response = $this->actingAs($user);
    }



    /** @test */
    public function a_user_can_be_created()
    {
        $response = $this->create_user($this->user_data());
        $this->assertCount(2, User::all());
        $response->assertRedirect('/admin/users');
    }


/** Creates a new User Object */
    public function create_user($data)
    {
        return $this->post('/admin/users/create', $data);
    }



    /** Creates data to insert into the created user*/
    private function user_data()
    {
        return [
            'name' => 'My Name',
            'reference' => '123456',
            'email' => '[email protected]',
            'password' => 'password',
            'status' => 1
        ];
    }

Any help would be grateful

Thank you

Jun
16
4 months ago
Activity icon

Replied to ErrorException Illegal Offset Type In Isset Or Empty

I've mangaged to rollback to my last commit and run composer update there and its back to working. But if I update it again it produces that error again

Activity icon

Replied to ErrorException Illegal Offset Type In Isset Or Empty

Hi @tinfoilman. This is code is from vendor/laravel/framework/src/Illuminate/Container/Container.php:1159 Ive reverted back to an earlier working commit and its still displaying the error which is really odd as i've been working on it all day. I thought it was to do with updating composer but it doesn't seem to be that.

Activity icon

Started a new Conversation ErrorException Illegal Offset Type In Isset Or Empty

Hi. Ive just updated composer, can't see many changes or updates but its now throwing an exception, but can't figure out what's causing it.

ErrorException Illegal offset type in isset or empty

Illuminate\Container\Container::getAlias
vendor/laravel/framework/src/Illuminate/Container/Container.php:1159

I've checked the docs and made sure the correct things are updated but I can't see what the issue is.

here's th line its flagging up

public function getAlias($abstract)
    {
      >>>  if (! isset($this->aliases[$abstract])) {
            return $abstract;
        }
 
        return $this->getAlias($this->aliases[$abstract]);
    }

Any ideas?

Cheers

Activity icon

Replied to Close A Modal After X Seconds

@michaloravec that worked perfect. I don't do much with JS and knew I was missing something but couldn't figure out what. Thank you.

Activity icon

Started a new Conversation Close A Modal After X Seconds

Hi. I have a laravel app which uses an alert component with a close icon that is closed using Vue. I wanted to add a timer to it so that it closed automatically after 10 seconds, but I can get so far but then gets errors.

If I run ::

const app = new Vue({
	el: '#app',

	data: {
		isOpen: false,
		closed: true
	},

	mounted() {
		setTimeout(function() { this.closed = false; }, 1000);
	},

	methods: {

		toggleProfileMenu() {
			// this.toggleProfileMenu == !this.isOpen;
			if(this.isOpen === false){
				this.isOpen = true;
			} else if (this.isOpen === true) {
				this.isOpen = false;
			}
		},

		closeAlert() {
			this.closed = false;
		}
	}
});

I get an error TypeError: Attempted to assign to readonly property.

I've tried to call the method as well but hit the error TypeError: this.closeAlert is not a function. (In 'this.closeAlert()', 'this.closeAlert' is undefined)

Any help or pointers would be grateful. Just wondering is it something to so with using mounted and the scope!

Many thanks

May
27
4 months ago
Activity icon

Replied to How To Pass A Id To The Controller Via The Route And View??

Route::post('institutes/{institute}', '[email protected]_confirm')->name('delete');

<form action="{{ route('delete', ['institute' => $institute->id]) }}" method="post"> 
May
26
4 months ago
Activity icon

Replied to Login As User From Admin Panel

So this is a quick setup ::

    // Impersonates a user. User_id comes from a link
    public function impersonate($user_id)
    {
        session(['admin_id' => Auth::id()]);
        Auth::logout();
        Auth::loginUsingId($user_id);

        return redirect()->route('my-route');
    }

    // Sets it back to admin
    public function back_to_admin()
    {
        Auth::logout();
        Auth::loginUsingId(session('admin_id'));
	session()->forget('admin_id')

        return redirect()->route('my-route');
    }
Activity icon

Replied to Storage_link Copy Issue

Just a stab in the dark, but just check the permissions for the folder, just in case...

Activity icon

Replied to Elequent GroupBy Date And Order By Asc Inside The Date Group

The scans are in a table of its own where it stores the path to the image and the order I want it to be in. I then have a blade template that shows all the images on 1 page. The order of the images are important as I need the Latest group on the top so this is where grouping by date is important but within that group (the images) I want to order them in ascending so they become 1,2,3 etc rather than newest first which would be 3,2,1..

So in the table layout I posted above, I want the layout to be like so:

26-05-2020
img 1, img 2, img 3

25-05-2020
img 1, img 2, img 3

etc. 

If I do it all by the latest images it becomes

26-05-2020
img 3, img 2, img 1

25-05-2020
img 3, img 2, img 1

etc. 
Activity icon

Replied to Elequent GroupBy Date And Order By Asc Inside The Date Group

Not quite sure what im doing wrong to be honest.

The table looks like this (path names aren't img1 and duplicating but just for clarity and easier to see the layout)

id.  |  user_id    | path                    | name.     | order        | created_at  | 
-----------------------------------------------------------------------------------
1   |  23          | \storage\img1.jpg.      | img 1     |  1            | 2020-05-25 |
2   |  23          | \storage\img2.jpg.      | img 2     |  2            | 2020-05-25 | 
3   |  23          | \storage\img3.jpg.      | img 3     |  3            | 2020-05-25 | 
4   |  23          | \storage\img1.jpg.      | img 1     |  1            | 2020-05-26 | 
5   |  23          | \storage\img2.jpg.      | img 2     |  2            | 2020-05-26 | 
6   |  23          | \storage\img3.jpg.      | img 3     |  3            | 2020-05-26 | 
-----------------------------------------------------------------------------------

Activity icon

Replied to Elequent GroupBy Date And Order By Asc Inside The Date Group

Hi @mkshingrakhiya. The issue is that doing it that way will order it by the latest scans first which is what I want but then the scan images that are grouped are ordered by latest which is not what id like. Its a bit of a pain as I want it grouped by date so I can display the scans and then order the scans inside the group so that they are ascending. Otherwise the images don't make sense and are backwards.

Hi @michaloravec. Still the same im afraid.

Cheers

Activity icon

Replied to Elequent GroupBy Date And Order By Asc Inside The Date Group

Hi @michaloravec. Strangely the scans are still going the wrong way. The date order is correct.

So its still doing

Today (26-05-2020)

img5, img4, img3, img2, img1

Yesterday(25-05-2020)

img3,img2,img1

etc...

Am I missing something, or doing something wrong?

Activity icon

Replied to Elequent GroupBy Date And Order By Asc Inside The Date Group

Hi @nickcourage.

Sorry the created_at or latest() works fine as its grouping by date 'desc' so the latest items are on the top, its the items inside that group that are backwards.

How it is now:

Today

img 5 img 4 img 3 img 2 img 1

Yesterday

img 3 img 2 img 1

How I want it to look:

Today

img 1 img 2 img 3 img 4 img 5

Yesterday

img 1 img 2 img 3

If that makes sense... :)

Activity icon

Replied to Login As User From Admin Panel

The way I did it before I realised there was a package was to set a session of your user id (so you can set a button to log back in to the last user id i.e. admin), then in the controller Auth::logout(); followed by Auth::loginUsingId(3 ); then if you have a button that keeps the admin session id as a link to login back as the admin at the end.

So what its doing is logging out the current user but then login in using the provided user id. You can then redirect it to the correct page for the user

Activity icon

Started a new Conversation Elequent GroupBy Date And Order By Asc Inside The Date Group

Sorry, the thread I opened last week, I marked as answered, and can't un mark it. https://laracasts.com/discuss/channels/laravel/ordering-by-date-and-title

what is happening is that I call "latest()" which I then can group the newest images by date and have the latest ones show at the top. But, what I want to happen once they have been grouped is to order the images in "asc" order so that the images are in the correct order. If I order them by created_at then the documents are displayed backwards which isn't what I want.

After some testing over the past few days it turns out it hasn't worked.

Im not sure why but, while testing I added numbers to the image to make sure they were uploaded in order. It then saved the path and order in the database. From this I can call the path and retrieve the images from s3 storage and as I have the "order_by" column in the database I can use this to order it correctly.

My controller works to get the collection in the date order that I want. But as soon as I add "OrderBy('order', 'asc')" the date ordering is good, but the image order is completely off and random.

My Controller::

    public function show(User $user)
    {
        $collection = CustomerScan::where('user_id', $user->id)
        ->latest()
        ->get()
        ->groupBy(function ($item) {
            return $item->created_at->format('Y-m-d');
        });

        return view('admin.customers-profile.sections.scan-viewer.show')->with([
            'collection' => $collection,
            'user' => $user
        ]);
    }

My View

@foreach ($collection as $date => $scans)

	<div style="margin-top: 50px;">
		
		@if(Carbon\Carbon::today()->toDateString() == $date)
			<strong>TODAY</strong>
		@elseif(Carbon\Carbon::today()->subDay()->toDateString() == $date)
			<strong>YESTERDAY</strong>
		@else
			<strong>{{ Carbon\Carbon::parse($date)->format('jS F Y') }}</strong>
		@endif
		
		<small style="float: right">
			{{ $scans->count() }} {{ Illuminate\Support\Str::plural('Scan',$scans->count()) }}
		</small>

	</div>

	<hr style="border-top: 1px #ccc solid;">

	<div class="row midsection">

		{{-- @foreach($scans->chunk(3) as $chunk) --}}

			@foreach($scans as $scan)
				{{-- My template layout -- }}
			@endforeach

		{{-- @endforeach --}}

	</div>

@endforeach

Any ideas.?

Many thanks

May
16
5 months ago
Activity icon

Replied to Ordering By Date And Title

Cheers @michaloravec... and thanks everyone for your replies

Activity icon

Started a new Conversation Ordering By Date And Title

Hi. Ive been trying a few different things and failing miserably, but what im trying to do is to group the collection by day/date and then the items inside that day are then ordered by title. In the controller the orderBy I have already orders the dates which is how I want it, but not sure how to order everything in the group.

Controller ::

$collection = CustomerScan::where('user_id', $user->id)
        ->orderBy('created_at', 'desc')
        ->get()
        ->groupBy(function ($item) {
            return $item->created_at->format('Y-m-d');
        });

Template::

@foreach ($collection as $date => $scans)

	<div style="margin-top: 50px;">

		<strong>{{ Carbon\Carbon::parse($date)->format('jS F Y') }}</strong>
		<small style="float: right">
			{{ $scans->count() }} {{ Illuminate\Support\Str::plural('Scan',$scans->count()) }}
		</small>
	</div>

	<hr style="border-top: 1px #ccc solid;">

	<div class="row midsection">

		@foreach($scans->chunk(3) as $chunk)
			@foreach($chunk as $scan)
				<a href="{{ Storage::disk('s3')->temporaryUrl( $scan->scan_paths, now()->addMinutes(1)) }}" target="_blank">
			@endforeach
		@endforech

What I want is to order the scan images in title order but still have the date order in "desc" if that makes sense. Any help would be grateful.

Cheers

Apr
30
5 months ago
Activity icon

Replied to Collections And Adding Logic

@tykus. Ah wow! I didn't even think about sql query! Thank you very much, that gets me past that hurdle. Along with some more reading on sql.

Activity icon

Started a new Conversation Collections And Adding Logic

Hi.

I've not done much with collections and mapping them etc and need to do some stuff with the database to achieve the desired results. What I'm trying to do is get data from the DB, reverse the order of certain column and also minus 1 on the figures.

DB structure::

 ---------------------------------------
| id |  ref | q1  |  q2  |  q3  |
 ---------------------------------------
| 1  | 321 |  3   |   4   |    3  |
 ---------------------------------------
| 2  | 313 |  4   |   1   |    2  |
 ---------------------------------------
| 3  | 213 |  1   |   3   |    2  |
 ---------------------------------------

What I want to is for example, "q1", "q2", "q3" get the values and take away 1 so that q1 => 3 becomes q1 => 2 etc.

I had a look at collections and tried various things but im struggling to understand how to get it to do what I want.

Any help would be grateful.