andersb

andersb

Member Since 1 Year Ago

Experience Points 5,810
Experience Level 2

4,190 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 53
Lessons
Completed
Best Reply Awards 0
Best Reply
Awards
  • start-engines Created with Sketch.

    Start Your Engines

    Earned once you have completed your first Laracasts lesson.

  • first-thousand Created with Sketch.

    First Thousand

    Earned once you have earned your first 1000 experience points.

  • 1-year Created with Sketch.

    One Year Member

    Earned when you have been with Laracasts for 1 year.

  • 2-years Created with Sketch.

    Two Year Member

    Earned when you have been with Laracasts for 2 years.

  • 3-years Created with Sketch.

    Three Year Member

    Earned when you have been with Laracasts for 3 years.

  • 4-years Created with Sketch.

    Four Year Member

    Earned when you have been with Laracasts for 4 years.

  • 5-years Created with Sketch.

    Five Year Member

    Earned when you have been with Laracasts for 5 years.

  • school-session Created with Sketch.

    School In Session

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

  • welcome-newcomer Created with Sketch.

    Welcome To The Community

    Earned after your first post on the Laracasts forum.

  • full-time-student Created with Sketch.

    Full Time Learner

    Earned once 100 Laracasts lessons have been completed.

  • pay-it-forward Created with Sketch.

    Pay It Forward

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

  • subscriber-token Created with Sketch.

    Subscriber

    Earned if you are a paying Laracasts subscriber.

  • lifer-token Created with Sketch.

    Lifer

    Earned if you have a lifetime subscription to Laracasts.

  • lara-evanghelist Created with Sketch.

    Laracasts Evangelist

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

  • chatty-cathy Created with Sketch.

    Chatty Cathy

    Earned once you have achieved 500 forum replies.

  • lara-veteran Created with Sketch.

    Laracasts Veteran

    Earned once your experience points passes 100,000.

  • 10k-strong Created with Sketch.

    Ten Thousand Strong

    Earned once your experience points hits 10,000.

  • lara-master Created with Sketch.

    Laracasts Master

    Earned once 1000 Laracasts lessons have been completed.

  • laracasts-tutor Created with Sketch.

    Laracasts Tutor

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

  • laracasts-sensei Created with Sketch.

    Laracasts Sensei

    Earned once your experience points passes 1 million.

  • top-50 Created with Sketch.

    Top 50

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

21 Jun
4 weeks ago

andersb left a reply on Conditional Filtering On Related Model

@MTHOMAS - The problem with your solution is that it looks from a given date. I am asking about a relative condition.

So the problem is that I want all comments that are posted after a month of the date which the associated post was created.

Can you see the difference? Each post was published on different days, so the condition would be something like “JOIN ... WHERE posts.created_at < DATE_ADD(comments.created_at, INTERVAL 1 MONTH)”

20 Jun
4 weeks ago

andersb left a reply on Conditional Filtering On Related Model

@MTHOMAS - @mthomas This is how you would do it for a given post. So if you would like to find all old comments for post with id=123. But imagine now that you would like to find comments for all posts that fulfill the same criteria.

andersb left a reply on Conditional Filtering On Related Model

@RAS1212 - I am aware of the documentation :) Unfortunately, it only include details about how to query the relationship for a single post. I am trying to dynamically set the "field" of the post so to say.

This could be done in SQL using a JOIN on posts and comments or a subquery for each post, but I am not sure how to do it in Eloquent.

andersb started a new conversation Conditional Relation On Related Model

I have two models A and B with a 1:n relationship and would like to find all A records where the associated B record meets a condition on A.

Example:

Get all comments that were created after a month of the original post being created.

It's possible for a single post to get all the comments meeting the condition using something like:

$post->comments()->whereDate('created_at', '>', $post->created_at->addMonth());

But how do you get all comments (for all posts) that were created after a month of the post being created?

Secondly, how do you get all posts that has a least one comment created after a month of the post being created?

Thanks so much.

03 Aug
11 months ago

andersb left a reply on Scope With Constraint On Latest Entry In Many To Many Relation

I ended up adding softDelete to my status model and only have one non-deleted status for each user. That way I have the history in my trash and can query the current status.

Still just a workaround unfortunatly.

06 Jun
1 year ago

andersb left a reply on Scope With Constraint On Latest Entry In Many To Many Relation

@arukomp This was a great idea, but unfortunatly the limit(1) does not make it to the query which then becomes:

select * from `users` where exists (select * from `statuses` inner join `status_user` on `statuses`.`id` = `status_user`.`status_id` where `users`.`id` = `status_user`.`user_id` and `code` = 'created' and `statuses`.`deleted_at` is null)

I don't quite get why the limit is not used.

andersb started a new conversation Scope With Constraint On Latest Entry In Many To Many Relation

I am trying to figure out how to add a scope that is capable of finding users where their latest status is equal to a specified value.

Imagine that two models, for example user and status, has a many to many relation with timestamps:

So on the User model:

public function statuses()
    {
        return $this->belongsToMany('App\Models\Status')
            ->withTimestamps()
            ->latest('status_user.created_at');//ordering by the created_at field in the pivot table
    }

And on the Status model:

public function users()
    {
        return $this->belongsToMany('App\Models\User')
            ->withTimestamps();
    }

I have added this scope to the User model:

public function scopeLatestStatus($query, $status_code){
        return $query->whereHas('statuses', function ($q) use ($status_code) {
            $q->where('code', $status_code);
        });
    }

But the problem is that if the has has status (in this order): status1,status2,status3, then the scope will return the user if you query by status2.

For the love of god, I don't get how one can limit the scope to the users latest status.

andersb left a reply on Creating An API Token When A User Signs Up

@beetuco this looks like a really good approach. I ended up doing it much more manually right now. I will try with your solution.

06 Apr
1 year ago

andersb left a reply on Creating An API Token When A User Signs Up

Dear @Cronix, I found the same code, but I have so far been unable to get me head around using this.

Spark uses the following API route for creating an API token from backend:

$router->post('/settings/api/token', 'Settings\API\[email protected]');

which uses a token repository instance to save the token. But I don't understand what I need to implement to get the ability to create tokens for a given user.

andersb started a new conversation Creating An API Token When A User Signs Up

I am trying to automatically create an API Token when a user signs up using Laravel Spark, but I keep getting an error Method Illuminate\Database\Query\Builder::createToken does not exist`

Here is the approach I found relevant:

Firstly I added an event CreateApiToken which is registred in app/Providers/EventServiceProvider.php as:

'Laravel\Spark\Events\Auth\UserRegistered' => [
    'App\Listeners\CreateApiToken',
],

Secondly I created a listener app/Listeners/CreateApiToken.php as:

<?php

namespace App\Listeners;

use Laravel\Spark\Events\Auth\UserRegistered;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Laravel\Spark\Contracts\Repositories\TokenRepository;
use Laravel\Spark\User;

class CreateApiToken
{
    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     *
     * @param  UserRegistered  $event
     * @return void
     */
    public function handle(UserRegistered $event)
    {
        $event->user->createToken('default')->token;
    }

Does anyone know, why the createToken() method cannot be used?

andersb left a reply on Returning JOSN:API Errors Instead Of Standard Error Handling Results

We ended up with a solution where we first rendered the request by the parent and then added the fields afterwards. That seemed to work for all errors.

We made the following changes to app\Exceptions\Handler.php

/**
     * Render an exception into an HTTP response.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Exception  $exception
     * @return \Illuminate\Http\Response
     */
    public function render($request, Exception $exception)
    {
        // Convert all non-http exceptions to a proper 500 http exception
        // if we don't do this exceptions are shown as a default template
        // instead of our own view in resources/views/errors/500.blade.php
        if ($this->shouldReport($exception) && !$this->isHttpException($exception) && !config('app.debug')) {
            $exception = new HttpException(500, 'Whoops!');
        }

        $response = parent::render($request, $exception);

        // If the API request wants JSON then return custom JSON API error
        if ($this->isApiCall($request) && $request->wantsJson()) {
            // add fields to the content
            $content = json_decode($response->getContent());
            $content->links = [
                'about' => App::make('url')->to('/errors/'.class_basename($exception)),
            ];
            $content->id = app('sentry')->getLastEventID();
            $content->code = class_basename($exception);
            // If debug, then add debug info
            if(config('app.env') !== 'production' && config('app.debug')) {
                $content->debug = [
                    'message' => $exception->getMessage(),
                    'exception' => get_class($exception),
                    'file' => $exception->getFile(),
                    'line' => $exception->getLine(),
                    'trace' => collect($exception->getTrace())->map(function ($trace) {
                        return Arr::except($trace, ['args']);
                    })->all(),
                ];
            }
            $response->setContent(json_encode($content));
        }

        return $response;
    }
`` `
28 Mar
1 year ago

andersb started a new conversation Addin Custom Settings Tab

I am trying to add a custom settings tab to Spark 6.0, but unfortunatly not with much luck. Do anyone have a guide or understand why I am getting the following error?

ERROR  Failed to compile with 1 errors                                                                                00:08:28
This relative module was not found:
* ../../spark-components/settings/test in ./resources/assets/js/components/bootstrap.js
                                                              Asset     Size  Chunks                    Chunk Names
    fonts/radio-select-default.svg?480bc0aebb3da809dc5b8d6f7ec60576  1.55 kB          [emitted]         
fonts/radio-select-is-selected.svg?ac228fff7b6af5be6d1620e5352ee43c  1.56 kB          [emitted]         
                                                         /js/app.js  2.15 MB       0  [emitted]  [big]  /js/app
                                                       /css/app.css   223 kB       0  [emitted]         /js/app
                                                   /css/app-rtl.css   223 kB       0  [emitted]         /js/app
                                              /js/sweetalert.min.js    17 kB          [emitted]         
ERROR in ./resources/assets/js/components/bootstrap.js
Module not found: Error: Can't resolve '../../spark-components/settings/test' in '/resources/assets/js/components'
 @ ./resources/assets/js/components/bootstrap.js 16:0-47
 @ ./resources/assets/js/app.js
 @ multi ./resources/assets/js/app.js ./resources/assets/sass/app.scss ./resources/assets/sass/app-rtl.scss
npm ERR! code ELIFECYCLE
npm ERR! errno 2
npm ERR! @ dev: `cross-env NODE_ENV=development node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js`
npm ERR! Exit status 2
npm ERR! 
npm ERR! Failed at the @ dev script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
npm ERR! A complete log of this run can be found in:
npm ERR!     /.npm/_logs/2018-03-28T22_08_29_141Z-debug.log

I added the extra Spark settings tab by firstly creating the tab blade file resources/views/settings/test.blade.php:

<spark-test :user="user" inline-template>
    <div>
        <!-- Test section -->
    </div>
</spark-test>

Secondly we add the menu item to resources/views/vendor/spark/settings.blade.php

<li class="nav-item ">
    <a class="nav-link" href="#test" aria-controls="test" role="tab" data-toggle="tab">
        <svg class="icon-20 " xmlns="http://www.w3.org/2000/svg" viewBox="0 0 640 512">
            <path d=""/>
        </svg>
        {{__('Test')}}
    </a>
</li>

Thirdly, I added the new tab section to the same file:

<!-- Test  -->
<div role="tabcard" class="tab-pane" id="test">
    @include('spark::settings.test')
</div>

Forthly, I define the JavaScript Component in the file resources/assets/js/spark-components/settings/test.js as:

var base = require('settings/test');

Vue.component('spark-test', {
    mixins: [base]
});

Lastly, we require the components in resources/assets/js/components/bootstrap.js by adding:

require('../../spark-components/settings/test');

I am sorry for the long description, but I hope this can help understanding the problem, and preferably help others creating custom setting tabs in Spark 6.0.

20 Mar
1 year ago

andersb left a reply on Saving A Request Of Nested Related Models (1:n With 1:n With ...)

@ahmeddabak: Your solution seem to work like a charm.

I was wondering if there were some easy way of adding relations (and nested relations) without having to specifying the relationships explicitly when saving, but it seems that we have to save the related models (and those related models related models) manually when saving the main model.

Thank you for your assistance.

andersb left a reply on Saving A Request Of Nested Related Models (1:n With 1:n With ...)

@ahmeddabak: This is not completely the case, but I understand what you are trying to do.

My Request is s json object containing:

{
   "name":"test",
   "submodels":[
      {
         "comment":"commentforsubmodelA",
         "subsubmodels":[
            {
               "description":"testdescriptionA1"
            },
            {
               "description":"testdescriptionA2"
            }
         ]
      },
      {
         "comment":"commentforsubmodelB",
         "subsubmodels":[
            {
               "description":"testdescriptionB1"
            },
            {
               "description":"testdescriptionB2"
            }
         ]
      }
   ]
}

So I would like to add each submodels, and while doing that, take the subsubmodels which is nested under the submodel and save it.

Does it make sense? I do not have real model names, as I am only mocking it up right now, but are unable to make it work.

andersb left a reply on Saving A Request Of Nested Related Models (1:n With 1:n With ...)

Hi @ahmeddabak, I don't really follow your thoughts. The use($subsubmodels) of you example would just be an unassigned variabel?

Can you explain you train of though perhaps?

Thanks.

andersb started a new conversation Saving A Request Of Nested Related Models (1:n With 1:n With ...)

Let say we have a model Mainmodel(). This Mainmodel() has n Submodel (so relationship is 1:n). But Submodel has a 1:n relationship with Subsubmodel so we have:

Mainmodel *1:n* Submodel *1:n* Subsubmodel

I can easily save Mainmodel with Submodels by:

public function store(Request $request) {
    $mainmodel->submodels()->createMany($request->submodels);
}

But how do I save the Subsubmodels which are also present in the Request?

22 Jan
1 year ago

andersb started a new conversation Returning JOSN:API Errors Instead Of Standard Error Handling Results

If API request contain the header "Accept: application/json", then the standard Laravel 5.5 error handling returns a JSON object containing a "message"-field (in case of a development environment, the fields exception, file, line and trace are also present).

I am trying to alter this response to follow the JSON:API error format: http://jsonapi.org/examples/#error-objects

{
  "errors": [
    {
      "id": "unique-trace-code-abcdefg123456798",
      "code": "abcdefg123456798",
      "title": "Pass this message on to the app user, if needed.",
    }
  ]
}

Preferably, then the id would be the unique code assigned to the error by a report service like Bugsnag or Sentry.

The code should be the Exception name and the title should be the regular message.

I am wondering if this should be implemented as a condition ($request->expectsJson()) in the render() function in /app/Exceptions/Handler.php that checks if the requested format is JSON and returns a custom error Resource.

Does anyone have any experience with implementing such an error handling?

Thank you.