GeordieJackson

GeordieJackson

Member Since 3 Years Ago

South Tyneside, UK

Experience Points
48,350
Total
Experience

1,650 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
324
Lessons
Completed
Best Reply Awards
25
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 10
48,350 XP
Sep
28
3 weeks ago
Activity icon

Awarded Best Reply on Method Illuminate\Database\Eloquent\Collection::paginate Does Not Exist.

It looks like you've been trying to search for $request['name'] whereas your search field is passed as $request['search'];

Just change your method to:

public static function search($request)
{
    $categories = Category::query();

    if (isset($request['search'])) {
        $categories = $categories->where('name', 'like', '%'.$request['search'].'%');
    }

    return $categories->paginate(1);
}

and you should be there.

You may also need to put:

Route::resource('categories', 'CategoryController');

Route::post('categories', [CategoryController::class, 'index']);

In your routes too as you're posting to an index method. Which is actually another no-no!

Sep
27
3 weeks ago
Activity icon

Replied to Method Illuminate\Database\Eloquent\Collection::paginate Does Not Exist.

It looks like you've been trying to search for $request['name'] whereas your search field is passed as $request['search'];

Just change your method to:

public static function search($request)
{
    $categories = Category::query();

    if (isset($request['search'])) {
        $categories = $categories->where('name', 'like', '%'.$request['search'].'%');
    }

    return $categories->paginate(1);
}

and you should be there.

You may also need to put:

Route::resource('categories', 'CategoryController');

Route::post('categories', [CategoryController::class, 'index']);

In your routes too as you're posting to an index method. Which is actually another no-no!

Activity icon

Replied to Method Illuminate\Database\Eloquent\Collection::paginate Does Not Exist.

Sorry, I was using a collection to test this rather than the request Object.

Try changing the method to:

public static function search($request)
{
    $categories = Category::query();

    if (isset($request->name) || isset($request['name'])) {
        $categories = $categories->where('name', 'like', '%'.$request['name'].'%');
    }

    return $categories->paginate(2);
}

This should work with either the request object or the request->all() array.

Activity icon

Replied to Method Illuminate\Database\Eloquent\Collection::paginate Does Not Exist.

You shouldn't have a collection when you're calling the paginate method.

Have you copied and pasted my method exactly?

i.e.

public static function search($request)
{
    $categories = Category::query();

    if (array_key_exists('name', $request)) {
        $categories = $categories->where('name', 'like', '%'.$request['name'].'%');
    }

    return $categories->paginate(1);
}

Note: I've changed collect() to array_key_exists() - as you're passing in an array rather than a collection.

Activity icon

Replied to Method Illuminate\Database\Eloquent\Collection::paginate Does Not Exist.

Just change it to:

if (collect($request)->has('name')) 
Activity icon

Replied to Method Illuminate\Database\Eloquent\Collection::paginate Does Not Exist.

Here's the search function refactored:

public static function search($request)
{
    $categories = Category::query();

    if ($request->has('name')) {
        $categories = $categories->where('name', 'like', '%'.$request['name'].'%');
    }

    return $categories->paginate(1);
}

I've still no idea what you're trying to achieve with $string, as you ignored my question, so I'll leave you with this and hope it helps.

Activity icon

Replied to Method Illuminate\Database\Eloquent\Collection::paginate Does Not Exist.

If you have a $category it will be a collection. You can't paginate a collection - only a database query.

What are you trying to do, search categories by 'name'?

Only, it looks all wrong to me.

Sep
26
3 weeks ago
Activity icon

Replied to How To Pass Variable To Form Request From Controller?

@sagar001 If anyone show me better way than my own than i will mark the ans as the best answer. :)

<GRINS>

You're actually extracting the height and width from 'file' and then doing a required check on file. If file is not present you'll get an exception and not the error message you want.

And...

function ($attribute, $value, $fail){
if($this->width < 1080 && $this->height < 1080) {
    $fail("Wallpaper's width or height must be greater than 1080px.");
   }
}

will only give an error message when both height AND width are less than 1080 - not the OR condition you're checking for.

Your solution isn't quite as good as you seem to think!

Sep
25
3 weeks ago
Activity icon

Awarded Best Reply on This Should Be Simple.

EDITED: This answer is not (quite) correct - see following posts.

Creating a new model using save() and then accessing the model's id is safe as the model will be populated with the auto-increment value assigned to it when it was persisted to the database.

Activity icon

Replied to How To Pass Variable To Form Request From Controller?

In your FormRequest class you can override the prepareForValidation method and extract your dimensions there.

e.g.

protected function prepareForValidation()
{
    if( $this->has('file')) {
        $image = $this->file('file');
        list($width,$height) = getimagesize($image);
        $this->merge(['width' => $width, 'height' => $height]);
    }
}

public function rules()
{
    return [
       // Validation rules...
    ];
}

Width and Height are now available for the rules() method for validation.

This moves all of the logic out of your controller - nice and clean.

Activity icon

Replied to Opens A New Window On The Same Page

If you want your page to open in a new window/tab you can add the target="_blank" attribute to your link.

e.g.

<a target="_blank" class="nav-link" id="pp-apartments-tab" data-toggle="tab" href="#pp-apartments" role="tab" aria-controls="pp-apartments" aria-selected="true">
    <span> Apartaments </span>
    <span class="items-counter"> {{ $project->count }} </span>
    {{-- <i class="fad fa-building"></i> --}}
</a>
Sep
23
4 weeks ago
Activity icon

Replied to Factory Two Functions In One

Can't you just use:

Poll::factory()->count(10)->make(['status' => 'A']);
Poll::factory()->count(10)->make(['status' => 'B']);
Poll::factory()->count(10)->make(['status' => 'C']);

Or are you after something else?

Activity icon

Replied to How To Create A Static And Non-static Method On Model?

If you have a model and you want to access its methods statically, you could use a real time facade. See: https://laravel.com/docs/8.x/facades#real-time-facades

Sep
22
4 weeks ago
Activity icon

Replied to This Should Be Simple.

@jlrdw

it uses

$id = $query->getConnection()->getPdo()->lastInsertId($sequence);

I'm not sure it's always going to work unless he puts a temp small fraction of a second lock.

You're right.

The potential for an Id mismatch, however small, is there.

If Laravel + MySql is used in the standard way then accessing the model->id after a save() is perfectly safe and reliable.

However, if you have a heavy-traffic website and you've changed Laravel's default behaviour to pool MySql connections then you can run into problems doing this.

Activity icon

Awarded Best Reply on Laravel On VPS Server

It may depend on your Plesk panel version.

On mine, I just select the domain I'm using and under "Dev Tools" there's a Git option (should show enabled or disabled). Obviously you need to enable it, set up the auth key for GitHub etc. and pull your repo into the correct folder.

When you go through the set up, the instructions are there for you.

Activity icon

Replied to Laravel On VPS Server

You can choose any folder you like to upload the repo to (it doesn't have to go into httpdocs first) - then just point to the public folder when setting your document_root in your hosting settings.

Activity icon

Replied to Laravel On VPS Server

It may depend on your Plesk panel version.

On mine, I just select the domain I'm using and under "Dev Tools" there's a Git option (should show enabled or disabled). Obviously you need to enable it, set up the auth key for GitHub etc. and pull your repo into the correct folder.

When you go through the set up, the instructions are there for you.

Activity icon

Replied to This Should Be Simple.

EDITED: This answer is not (quite) correct - see following posts.

Creating a new model using save() and then accessing the model's id is safe as the model will be populated with the auto-increment value assigned to it when it was persisted to the database.

Activity icon

Replied to Laravel On VPS Server

I have a VPS that I use for my personal Laravel projects - Ubuntu server with Plesk panel (includes Git, Composer support, etc.)

Deploying, using Git, is a breeze. Likewise, updating via Composer is simply point and click.

I don't use them for personal projects, but setting up a dev server and staging server would be equally as simple and convenient.

So, I'd say give it a go on a VPS and only move to something more sophisticated if you need to.

Sep
19
1 month ago
Activity icon

Replied to How To Exclude Child And Subcategories While Editing In Multi Level Category In Laravel?

When you print out your dropdown, you need to check whether the current category->id or the ids of its descendants matches the current dropdown->id and skip it if it does.

e.g. something like:

@foreach($categories as $category)
// Print out category info...
    @foreach($categories as $dropdown)
        @if($category->getIdList()->contains($dropdown->id))
            @continue
        @endif
        // Print option...
    @endforeach
@endforeach

Where $category->getIdList() is a recursive function that returns the id of the current category + its descendants' ids.

Activity icon

Awarded Best Reply on ErrorException: Undefined Offset: 1 In Data-bootstrap-switch

If either of weekend_inclusive or holiday_inclusive is not checked in the form, they won't be passed into the input array.

i.e. they won't be passed in as parameters with a value of "0" - they will simply be omitted unless their value is "1".

You could use:

'weekend_inclusive'                 => $request->weekend_inclusive[$key] ?? 0,
'holiday_inclusive'                 => $request->holiday_inclusive[$key] ?? 0,

To insert the zero when not set.

Sep
18
1 month ago
Activity icon

Replied to ErrorException: Undefined Offset: 1 In Data-bootstrap-switch

If either of weekend_inclusive or holiday_inclusive is not checked in the form, they won't be passed into the input array.

i.e. they won't be passed in as parameters with a value of "0" - they will simply be omitted unless their value is "1".

You could use:

'weekend_inclusive'                 => $request->weekend_inclusive[$key] ?? 0,
'holiday_inclusive'                 => $request->holiday_inclusive[$key] ?? 0,

To insert the zero when not set.

Activity icon

Replied to How To Change Laravel Database Value Before Compare?

You can compare strings in a case-insensitive way without having to alter them:

if(strcasecmp('StrINg', 'string') == 0) {
    // OK to proceed...
}
Sep
17
1 month ago
Activity icon

Awarded Best Reply on Argument Count Error

Should

$threads = $threads->get();

be:

$threads = Thread::get();
Activity icon

Replied to Argument Count Error

Should

$threads = $threads->get();

be:

$threads = Thread::get();
Sep
16
1 month ago
Activity icon

Replied to L8 Many To Many Returning Only 1 Record

@cac

Your code, as you've posted it, works OK for me.

What I would look at first is when you use: $e->workouts, is Laravel creating a database query and if so, what is it?

It should be the same query as what using $e->workouts()->get() produces when the workouts property isn't set.

Sep
08
1 month ago
Activity icon

Replied to Author And Product Relationship Query Issue

Laravel doesn't have built-in support for limiting eager loaded relations - as far as I'm aware anyway.

If you NEED this functionality there's a package here: https://github.com/staudenmeir/eloquent-eager-limit

Activity icon

Replied to PHP Unit Testing

@sauravs012

Your User details aren't the default fields Laravel uses. Have you set the migration with the new fields properly, and have you changed the validation at all?

It's obviously not storing your user in the database so the problem is most likely with your input data.

Sep
07
1 month ago
Activity icon

Replied to User In Laravel Controllers

@elb98rm

If you need to eager load the user's relations on every login, why not put an event listener on the Login Event and load them when it's fired? i.e. whenever a user logs in, their relations are automatically loaded for use in controllers etc.

That should work OK as long as you're not loading in too much data.

Sep
06
1 month ago
Activity icon

Awarded Best Reply on Recursive Eloquent Using "with" Method?

As the relationship is a One to Many, the inverse will mean that each category will only have one parent and each parent will have only one parent etc...

So in order to get a sequential list, the results will need to be looped through and built up. e.g.

$taxon = Taxon::with('parents')->find($id);

$parents = collect();
$currentTaxon = $taxon;

do {
    $parents[] = ['name' => $currentTaxon->name];
} while ($currentTaxon = $currentTaxon->parents);

Then just return $parents or $parents->reverse() depending on which order you want them in.

@foreach ($parents as $parent)
    {{ $parent['name'] }}
@endforeach

Should now work OK

Activity icon

Replied to What Is The Best Theme For Laravel In Phpstorm ???

Whichever one you like the most!

There's a light and a dark version of a nicely contrasted theme here: https://github.com/brendt/phpstorm-photon-theme

Activity icon

Replied to Recursive Eloquent Using "with" Method?

As the relationship is a One to Many, the inverse will mean that each category will only have one parent and each parent will have only one parent etc...

So in order to get a sequential list, the results will need to be looped through and built up. e.g.

$taxon = Taxon::with('parents')->find($id);

$parents = collect();
$currentTaxon = $taxon;

do {
    $parents[] = ['name' => $currentTaxon->name];
} while ($currentTaxon = $currentTaxon->parents);

Then just return $parents or $parents->reverse() depending on which order you want them in.

@foreach ($parents as $parent)
    {{ $parent['name'] }}
@endforeach

Should now work OK

Activity icon

Replied to Recursive Eloquent Using "with" Method?

For all parents try:

public function parents()
{
    return $this->belongsTo('App\Taxon', 'parent_id', 'id')->with('parents');
}

And for descendants:

public function descendants()
{
    return $this->hasMany('App\Taxon', 'parent_id', 'id')->with('descendants');
}
Activity icon

Awarded Best Reply on How Can I Validate The From For Null Value Or Exist In Laravel?

Just use:

'sponsor' => ['nullable', 'exists:users,user_name'],  
Activity icon

Replied to How Can I Validate The From For Null Value Or Exist In Laravel?

Just use:

'sponsor' => ['nullable', 'exists:users,user_name'],  
Activity icon

Replied to More Table Confusion

In Event.php your relationship should be:

public function user()
{
    $this->belongsTo(User::class);
{

Then your Event's show() method should be:

public function show($id)
{       
    $event = Event::with('user')->findOrFail($id);    
}

The user will be available via:

$event->user;

This is assuming a One to Many relationship: https://laravel.com/docs/7.x/eloquent-relationships#one-to-many

Sep
05
1 month ago
Activity icon

Replied to How To Access Eloquent

@dipcb05

In your controller, use:

$posts = Post::with('user')->get();

Then in your blade, using:

@foreach($posts as $post)
<h1> {{ $post->user->name }} </h1>
@endforeach

Should work OK.

Sep
04
1 month ago
Activity icon

Awarded Best Reply on Get Primary Key Field Name?

You can add a static method to the model and return the primary key:

public static function primaryKey()
{
    return (new static())->getPrimaryKey();
}

and fetch it with: $primaryKey = ModelName::primaryKey();

Activity icon

Replied to Get Primary Key Field Name?

Or...

You could hard code the key name into a constant, use that to set the field in the class, and then you'd be able to access the key without having to instantiate the class. e.g.

    class Test extends Model
    {
        const PRIMARYKEY = 'id';

        protected $primaryKey = self::PRIMARYKEY;
    }

It can be accessed with: $key = Test::PRIMARYKEY

You would have to change the const value if you ever changed the key but that's straightforward and unlikely to be required anyway once the key has been chosen.

Activity icon

Replied to Get Primary Key Field Name?

You can add a static method to the model and return the primary key:

public static function primaryKey()
{
    return (new static())->getPrimaryKey();
}

and fetch it with: $primaryKey = ModelName::primaryKey();

Sep
03
1 month ago
Activity icon

Replied to Should I Not Use Database In Unit Testing?

@untymage

It really depends on how strict you want to be.

A unit test should:

  • Test one thing and one thing only; and
  • Not depend on other functionality in order to run; therefore
  • Run independently.

So, a test that requires a database connection to pull in data that's required to test something is not actually a unit test (by these criteria): it's a feature test.

However, a test is a test and it's up to you as a developer whether you want to segregate tests into unit/feature.etc. based on strict definitions or take a more pragmatic approach and use some other criteria.

Most tests that you write when using a framework such as Laravel will be feature tests as you're almost always using the functionality of the framework (and trusting that it works as it's been tested itself independently) to some degree in your tests.

Sep
01
1 month ago
Activity icon

Replied to Relationship Within The Same Model

Siblings would all share a parent and cousins would all share a grandparent. It's the only way to relate records within one table. This approach is usually used with nested relationships: categories, subcategories, sub-subcategories, etc.

If you want to achieve the many-to-many set up you seem to be looking for, then just use a standard many-to-many set up - i.e. use a pivot table as normal to relate the table records to related records in the same table rather than another one.

There may be other solutions, but those are the simplest I would say.

Activity icon

Replied to Calling TestCase Methods Within A Response Macro?

If you do this in your test:

$this->withoutExceptionHandling();

$this->patch('some-path')->assertSomething();

It should work OK.

Off the top of my head, but I would expect it to work. You shouldn't need, indeed can't, turn off exception handling in the Response class.

Activity icon

Awarded Best Reply on Variable Constant

My previous answer was incorrect - posting without checking first!

If you want to access a class constant with a variable use:

$var = "FIRSTNAME"

constant(ClassName::class."::".$var)

That should do it.

Activity icon

Replied to Variable Constant

My previous answer was incorrect - posting without checking first!

If you want to access a class constant with a variable use:

$var = "FIRSTNAME"

constant(ClassName::class."::".$var)

That should do it.

Activity icon

Replied to Unit Test Keeps Failing

This here in a_user_can_be_updated():

$user = factory(User::class)->create();

        $this->assertDatabaseMissing('users', [
            'id' => $user->id,
            'type' => User::TYPE_ADMIN,
            'name' => 'John Doe',
            'username' => 'JohnDoe',
            'email' => '[email protected]',
        ]);

Will fail because you're creating a user (i.e. saving them to the database) and then checking that they're missing from the database.

If you use:

$user = factory(User::class)->make();

instead of create, it will create a user in memory but not save it in the database.

Activity icon

Replied to How To Delete An Item In Database , Not The Record. Using The Id

NOTE (for anyone else who comes across this):

$status = User::where('status', $xyz)->update(['status'=>null]);

Will update ALL users whose status is $xyz - not just the one being targeted.

Activity icon

Replied to Variable Constant

Normally, you set a constant in your model:

class ClassName extends Model
{
    const FIRSTNAME = "First";
    const SECONDNAME = "Second";
}

and then access them this way:

ClassName::FIRSTNAME

ClassName::SECONDNAME

ADDED: This answer is incorret

So, if your $variable equals `"FIRSTNAME" then you can access the constant with:

ClassName::$variable

and you'll get "First" returned. And so on...

Aug
31
1 month ago
Activity icon

Replied to How To Delete An Item In Database , Not The Record. Using The Id

If you run:

$status = User::where('status', $xyz);
$status ->delete();

It will delete all users whose status is $xyz (!)

What you need to do is an update query. i.e. find the user you're after and then update the field to the new value.

Activity icon

Awarded Best Reply on Resource Collection By User Id

@grunburg

Post::paginate(10)

Will just fetch 10 posts. You need to get the user's posts

Try:

return new PostCollection($user->posts->paginate(10));

Or similar.