chr15k

chr15k

Member Since 2 Months Ago

Brighton

Experience Points
30,980
Total
Experience

4,020 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
203
Lessons
Completed
Best Reply Awards
15
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 7
30,980 XP
Aug
21
1 month ago
Activity icon

Awarded Best Reply on YouTube Autoplay Feature Not Working

@sauravs012 If I paste the code from my previous reply into an html file, it does work as expected for me, i.e it autoplays muted.

Aug
17
1 month ago
Activity icon

Replied to Password Reset

ResetPasswordController

    /**
     * Where to redirect users after resetting their password.
     *
     * @var string
     */
    protected $redirectTo = '/login';
Aug
09
1 month ago
Activity icon

Replied to How To Save To A Database With Multiple Tables?

@chrisf79 no worries! glad that helped you out 🙂

Activity icon

Awarded Best Reply on How To Save To A Database With Multiple Tables?

Couple things I noticed here which may be helpful:

In your User model, the hasMany relation should be plural (addresses):

public function addresses()
{
    return $this->hasMany('App\Address', 'user_id');
}

You also want to update your fillable array to reflect your actual column names:

protected $fillable = [
    'first_name', 'last_name', 'password', 'email',
];

In your Address model, the convention is to use camel case for method names (addressType):

public function addressType()
{
    return $this->hasOne('App\AddressType');
}

And also add your fillable array for mass assignment:

protected $fillable = [
    'address_1',
    'address_2',
    'address_3',
    'city',
    'state_or_province',
    'postal_code',
    'GoogleLat',
    'GoogleLong'
];

Set one of the relations to nullable in your addresses schema:

$table->unsignedBigInteger('address_type')->nullable();

Then you can do:

$user = User::create([
    'first_name' => 'Bob',
    'last_name' => 'Smith',
    'password' => 'password',
    'email' => '[email protected]'
]);

$address = $user->addresses()->create([
    'address_1' => '123 First Avenue',
    'city' => 'Some city',
    'state_or_province' => 'Some state',
    'postal_code' => '12345'
]);

// Then set the address type

$type = AddressType::find(1); // Get the relevant address type id

$address->addressType()->save($type);
Activity icon

Replied to Laravel In Container

You could try specifying your app's environment file assuming you're using docker-compose?

services:
  app:
    env_file:
      - .env // <-- path to your .env file

Then docker should automatically set the values required by Laravel from your .env file when the container builds.

Activity icon

Replied to How Can I Return A Value With Redirect Back

How are you accessing the data in the view? Have you tried:

session('calculations');
Activity icon

Replied to Laravel In Container

Not a fix of course, but just to test, does anything change if you hardcode the key in the config file so it doesn't read from .env?

config/app.php

'key' => 'base64:c/UPpkuqVLMs4T77KA6+TlQ7mAp8Xbugy0pRwdOh5gQ=',
php artisan config:clear
Activity icon

Replied to Laravel In Container

I'm assuming you have correct cipher set in app config?

echo config('app.cipher');

If it isn't set then IIRC the default is AES-128-CBC

in config/app.php you want:

'cipher' => 'AES-256-CBC',
Activity icon

Replied to How To Save To A Database With Multiple Tables?

Couple things I noticed here which may be helpful:

In your User model, the hasMany relation should be plural (addresses):

public function addresses()
{
    return $this->hasMany('App\Address', 'user_id');
}

You also want to update your fillable array to reflect your actual column names:

protected $fillable = [
    'first_name', 'last_name', 'password', 'email',
];

In your Address model, the convention is to use camel case for method names (addressType):

public function addressType()
{
    return $this->hasOne('App\AddressType');
}

And also add your fillable array for mass assignment:

protected $fillable = [
    'address_1',
    'address_2',
    'address_3',
    'city',
    'state_or_province',
    'postal_code',
    'GoogleLat',
    'GoogleLong'
];

Set one of the relations to nullable in your addresses schema:

$table->unsignedBigInteger('address_type')->nullable();

Then you can do:

$user = User::create([
    'first_name' => 'Bob',
    'last_name' => 'Smith',
    'password' => 'password',
    'email' => '[email protected]'
]);

$address = $user->addresses()->create([
    'address_1' => '123 First Avenue',
    'city' => 'Some city',
    'state_or_province' => 'Some state',
    'postal_code' => '12345'
]);

// Then set the address type

$type = AddressType::find(1); // Get the relevant address type id

$address->addressType()->save($type);
Activity icon

Replied to Laravel In Container

@pcabral try clearing the config cache after generating the new key:

php artisan config:clear

Also, have you mounted your host directory to your container using volumes? If you're running the artisan command on your host machine for instance, and they're not mounted, then the key will only be generated on your host machine.

Aug
08
1 month ago
Activity icon

Awarded Best Reply on Polymorphic Relationships Doesn't Fill Out The Fields

@foks Fixed it my end by adding public $incrementing = false; to the DiscordAuth model:

class DiscordAuth extends Model
{
    protected $guarded = [];

    public $incrementing = false;

    public function auth()
    {
        return $this->morphOne(Auth::class, 'authable');
    }
}
Activity icon

Replied to Polymorphic Relationships Doesn't Fill Out The Fields

@foks Fixed it my end by adding public $incrementing = false; to the DiscordAuth model:

class DiscordAuth extends Model
{
    protected $guarded = [];

    public $incrementing = false;

    public function auth()
    {
        return $this->morphOne(Auth::class, 'authable');
    }
}
Activity icon

Replied to Polymorphic Relationships Doesn't Fill Out The Fields

Ah, I reproduced this - that's odd

Activity icon

Replied to Polymorphic Relationships Doesn't Fill Out The Fields

does $user->id return the actual id? Looking at the documentation it suggests to use $user->getId()

https://laravel.com/docs/7.x/socialite#retrieving-user-details

Aug
07
1 month ago
Activity icon

Replied to DataTable In Laravel Mix Not Working

@anonymouse703 looking at the documentation, it suggests to require the package after jQuery, like this:

window.$ = window.jQuery = require('jquery');

window.DataTable = require('datatables.net-bs4')($);

https://www.npmjs.com/package/datatables.net-bs4

Activity icon

Replied to DataTable In Laravel Mix Not Working

what error(s) are you seeing in the console, and have you included the package?

in boostrap.js (assuming datatables.net-bs4 is the package you're using?)

window.DataTable = require('datatables.net-bs4');
Aug
06
1 month ago
Activity icon

Awarded Best Reply on Data Truncated When Trying To Create Personal Access Client For Passport

the id 913a0ac7-5e2b-4d0c-abcd-aa6eb4d52085 is too big for your id column so it can't store it. It also contains hyphens which won't work as I'm assuming your id column type is BIGINT?

Do you have a code example?

Activity icon

Replied to Copy File To Storage Disk

How about this:

Storage::disk('remoteftp')->put(
    "test/$foldername/".basename($file),
    fopen("$relative_source_dir/$filename", 'r+')
);
Activity icon

Replied to Data Truncated When Trying To Create Personal Access Client For Passport

the id 913a0ac7-5e2b-4d0c-abcd-aa6eb4d52085 is too big for your id column so it can't store it. It also contains hyphens which won't work as I'm assuming your id column type is BIGINT?

Do you have a code example?

Activity icon

Replied to YouTube Autoplay Feature Not Working

@sauravs012 If I paste the code from my previous reply into an html file, it does work as expected for me, i.e it autoplays muted.

Activity icon

Replied to YouTube Autoplay Feature Not Working

you need to also add &mute=1 to the url

<iframe width="560" height="315" src="https://www.youtube.com/embed/7i8GSNvVpfM?autoplay=1&mute=1" frameborder="0" allowfullscreen></iframe>

See here: https://developers.google.com/web/updates/2017/09/autoplay-policy-changes

Activity icon

Replied to Polymorphic Relationships Doesn't Fill Out The Fields

@foks is it because that long id in your screenshot exceeds the maximum value for your id column in your table?

'id' => intval($user->id) // <-- this value
Activity icon

Replied to Reference Error `name` Not Defined When Importing Or Requiring

app.js

const luxon = require('luxon');

window.DateTime = luxon.DateTime; 

view

<script type="text/javascript">
    DateTime.local();
</script>
Aug
05
1 month ago
Activity icon

Replied to Polymorphic Relationships Doesn't Fill Out The Fields

Hi @foks

What do you get if you dump the $user instance?

Activity icon

Replied to Lumen VS Laravel

@martinbean Yeh, all comes down to requirements doesn't it; if you need those features then going with Laravel makes more sense.

I can see Laravel being the viable choice in most cases, even when you look at it from a performance perspective (Lumen known to be able to handle more requests per sec. etc), once the app touches a database, there really isn't much in it.

Funnily enough, I'm starting a new job next week and they use Lumen for a lot of projects, so it'll be interesting to see the use cases and whether they've also back-ported features from Laravel framework :-)

Aug
04
1 month ago
Activity icon

Replied to Lumen VS Laravel

@martinbean I've used API resources with Lumen, just doesn't come with the artisan command afaia.

https://github.com/laravel/lumen-framework/blob/6f599287fc1f689c0ec8dc0c15ba9180f5bb7c72/composer.json#L32

This works:

use Illuminate\Http\Resources\Json\JsonResource;
Jul
31
1 month ago
Activity icon

Replied to (T_STRING), Expecting Function (T_FUNCTION) Or Const (T_CONST)

do you have a code example of your Post model and the line of the error?

Activity icon

Replied to (T_STRING), Expecting Function (T_FUNCTION) Or Const (T_CONST)

where have you included ResponseCacheRepository ? Probably just missing a semi colon somewhere?

Jul
29
1 month ago
Activity icon

Replied to How To Update Relationship?

You need to specify the field name to update the urls

$game->urls()->update(['fieldname' => $request->get('url')]);
Jul
28
1 month ago
Activity icon

Awarded Best Reply on Relationships - With() : Get List Of Objects Instead Of An Array

Ah yeh ok. What about:

QuestionResource

<?php

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\JsonResource;

class QuestionResource extends JsonResource
{
    public function toArray($request)
    {
        return [
            'color' => $this->color,
            'size'   => $this->size
        ];
    }
}

use keyBy when returning Questions

<?php

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\JsonResource;
use App\Http\Resources\QuestionResource;


class PetResource extends JsonResource
{
    public function toArray($request)
    {
        return [
            'id' => $this->id,
	    'name' => $this->name,
	    'questions' => QuestionResource::collection($this->questions->keyBy->code),
        ];
    }
}
Route::get('/p', function () {
    return PetResource::collection(Pet::all());
});
Activity icon

Replied to Relationships - With() : Get List Of Objects Instead Of An Array

Ah yeh ok. What about:

QuestionResource

<?php

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\JsonResource;

class QuestionResource extends JsonResource
{
    public function toArray($request)
    {
        return [
            'color' => $this->color,
            'size'   => $this->size
        ];
    }
}

use keyBy when returning Questions

<?php

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\JsonResource;
use App\Http\Resources\QuestionResource;


class PetResource extends JsonResource
{
    public function toArray($request)
    {
        return [
            'id' => $this->id,
	    'name' => $this->name,
	    'questions' => QuestionResource::collection($this->questions->keyBy->code),
        ];
    }
}
Route::get('/p', function () {
    return PetResource::collection(Pet::all());
});
Activity icon

Replied to Relationships - With() : Get List Of Objects Instead Of An Array

@devondahon Perhaps try making Pet and Question Resource classes.

To get a collection:

return ModelResource::collection(Model::all());

To retrieve a single instance you can use it like this:

return new ModelResource(Model::find(1));

QuestionResource

<?php

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\JsonResource;

class QuestionResource extends JsonResource
{
    public function toArray($request)
    {
        return [
            $this->code => [
                'color' => $this->color,
                'size' => $this->size
            ]
        ];
    }
}

PetResource

<?php

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\JsonResource;
use App\Http\Resources\QuestionResource;


class PetResource extends JsonResource
{
    public function toArray($request)
    {
        return [
            'id' => $this->id,
	    'name' => $this->name,
	    'questions' => QuestionResource::collection($this->questions),
        ];
    }
}
Route::get('/p', function () {
    return PetResource::collection(Pet::all());
});
Activity icon

Replied to Relationships - With() : Get List Of Objects Instead Of An Array

they're transformer classes, so you can pass the collection in like this:

use App\Http\Resources\Pet as PetResource;
use App\Pet;

Route::get('/p', function () {
    return PetResource::collection(Pet::all());
});

Then in Pet Resource (assuming you've also created the QuestionResource) you pass the Pet's questions into the QuestionResource:

    public function toArray($request)
    {
        return [
            'id' => $this->id,
	    'name' => $this->name,
	    'questions' => QuestionResource::collection($this->questions),
        ];
    }

That'll then spit out the format you want, rather than the direct model response.

There's some good documentation here https://laravel.com/docs/7.x/eloquent-resources#resource-collections

Note - I haven't tested this myself so apologies if there are any typos.

Activity icon

Replied to Relationships - With() : Get List Of Objects Instead Of An Array

If it's for presentation purposes then you could use Laravel resources https://laravel.com/docs/7.x/eloquent-resources to add a transformation layer. Might save you some headaches!

If you're using an old version of Laravel then you can use https://fractal.thephpleague.com/transformers/

You can create collections like this:

<?php

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\ResourceCollection;

class PetCollection extends ResourceCollection
{
    /**
     * Transform the resource collection into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function toArray($request)
    {
        return [
            'id' => $this->id,
	    'name' => $this->name,
	    'questions' => QuestionResource::collection($this->questions),
        ];
    }
}

The easily set the format you want in the Question class:

<?php

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\JsonResource;

class Question extends JsonResource
{
    public function toArray($request)
    {
        return [
            $this->code => [
                'color' => $this->color,
                'size' => $this->size
            ]
        ];
    }
}
Activity icon

Awarded Best Reply on Dropzone CSRF Token Mismatch

I can send you what worked quite well for me:

dropzone options

    Dropzone.options.dropzone = {
        maxFilesize: 12,
        renameFile: function(file) {
            return file.name;
        },
        acceptedFiles: ".jpeg,.jpg,.png",
        addRemoveLinks: false,
        timeout: 5000,
        success: function(file, response) {
            return console.log(response);
        },
        error: function(file, response) {
            return console.log(response);
        }
    };

view - use the @csrf directive here

<form
    method="post" 
    action="{{ route('store') }}"
    enctype="multipart/form-data"
    class="dropzone"
    id="dropzone"
>
    @csrf
    <div class="dz-message">
        <div class="col-xs-8">
            <div class="message">
                <p>Drop files here or Click to Upload</p>
            </div>
        </div>
    </div>
    <div class="fallback">
        <input name="file" type="files" multiple accept="image/jpeg, image/png, image/jpg" />
    </div>
</form>

Hope it helps

Activity icon

Replied to Dropzone CSRF Token Mismatch

I can send you what worked quite well for me:

dropzone options

    Dropzone.options.dropzone = {
        maxFilesize: 12,
        renameFile: function(file) {
            return file.name;
        },
        acceptedFiles: ".jpeg,.jpg,.png",
        addRemoveLinks: false,
        timeout: 5000,
        success: function(file, response) {
            return console.log(response);
        },
        error: function(file, response) {
            return console.log(response);
        }
    };

view - use the @csrf directive here

<form
    method="post" 
    action="{{ route('store') }}"
    enctype="multipart/form-data"
    class="dropzone"
    id="dropzone"
>
    @csrf
    <div class="dz-message">
        <div class="col-xs-8">
            <div class="message">
                <p>Drop files here or Click to Upload</p>
            </div>
        </div>
    </div>
    <div class="fallback">
        <input name="file" type="files" multiple accept="image/jpeg, image/png, image/jpg" />
    </div>
</form>

Hope it helps

Jul
27
1 month ago
Activity icon

Replied to Dropzone CSRF Token Mismatch

You can pass the token in the header:

<script src="{{ asset('themes/js/dropzone.js') }}"></script>
<script>
    Dropzone.autoDiscover = false;
    $(document).ready(function(){
        $('#drop').dropzone({
            url: '{{ route('dropzone') }}',
            method: 'post',
	    headers: {
                'X-CSRF-TOKEN': $('meta[name="token"]').attr('content')
            }
        });
    });
</script>
Activity icon

Replied to How To Display All Files In A Directory In My View

You could use the File facade which should give you an array of Symfony\Component\Finder\SplFileInfo instances:

use Illuminate\Support\Facades\File;

$storage = File::allFiles(storage_path('pdfs'));


=> [
     Symfony\Component\Finder\SplFileInfo {#3371
       path: "/project-directory/storage/pdfs",
       filename: "test.pdf",
       basename: "test.pdf",
       pathname: "/project-directory/storage/pdfs/test.pdf",
       extension: "pdf",
       realPath: "/project-directory/storage/pdfs/test.pdf",
       aTime: 2020-07-27 23:03:25,
       mTime: 2020-07-27 23:03:25,
       cTime: 2020-07-27 23:03:25,
       inode: 13314623,
       size: 0,
       perms: 0100644,
       owner: 501,
       group: 20,
       type: "file",
       writable: true,
       readable: true,
       executable: false,
       file: true,
       dir: false,
       link: false,
     },
   ]

Example to get filename:

use Illuminate\Support\Facades\File;

$storage = File::allFiles(storage_path('pdfs'));

foreach ($storage as $file) {
    echo $file->getFilename();
}

// test.pdf

If these files need to be publicly accessible then you can create a sym link from storage to public directory, then use the asset helper:

https://laravel.com/docs/7.x/filesystem#the-public-disk

Activity icon

Replied to Relationship Returns Empty Array

this reminded me of this package https://github.com/staudenmeir/eloquent-has-many-deep which allows for unlimited levels of hasManyThrough

Might be of interest

Jul
25
2 months ago
Activity icon

Replied to Add OrderBy To A ::with

@dadub remove Semi colon on first line

Activity icon

Replied to Add OrderBy To A ::with

Hi @snapey good point 👍

Jul
24
2 months ago
Activity icon

Replied to Take(1) Applying To All Related Models

As above, that approach won't work, you could use load after get but then you might have the n+1 issue.

What you could do is use a hasOne relation like this in your Customer model:

Customer model

public function latestOrder()
{
  return $this->hasOne('App\Order')->latest();
}

Then you can simply eager load this relationship:

Customer::where('gender','=','female')->with('latestOrder')->get();
Jul
23
2 months ago
Activity icon

Awarded Best Reply on Editing Robots.txt

You could use File::get()

use Illuminate\Support\Facades\File;

File::get(public_path('robots.txt'));

outputs:

=> """
   User-agent: *\n
   Disallow:
   """

Then to write to the file:

use Illuminate\Support\Facades\File;

File::put(public_path('robots.txt'), 'new contents');
Activity icon

Replied to Editing Robots.txt

You could use File::get()

use Illuminate\Support\Facades\File;

File::get(public_path('robots.txt'));

outputs:

=> """
   User-agent: *\n
   Disallow:
   """

Then to write to the file:

use Illuminate\Support\Facades\File;

File::put(public_path('robots.txt'), 'new contents');
Activity icon

Awarded Best Reply on How To With Array Send?

Whenever you use the directive {{ }}, the blade engine expects the value to be a string.

The value get passed through htmlspecialchars() function which helps prevent XSS attacks; it throws the error due to it being an object, collection of objects, or an array.

You can print the message like this:

@foreach (session('msg') as $msg)
    {{ $msg }}
@endforeach
Activity icon

Replied to Testing Controller Edit Method

Possibly blade syntax related.

Are you able to post the code for view user.project.edit?

Also, do you have any errors in your app logs when you run the test? (worth checking)

Activity icon

Awarded Best Reply on How Can I Allow Only One Route?

You could use the fallback method:

Route::fallback(function () {
    return redirect()->route('index');
});

https://laravel.com/docs/7.x/routing#fallback-routes