tykus

Full Stack PHP Developer at FordeCloud

Experience

337,510

534 Best Reply Awards

  • Member Since 3 Years Ago
  • 1152 Lessons Completed
  • 0 Favorites

16th October, 2017

tykus left a reply on POST Http://localhost:8000/users 500 (Internal Server Error) • 2 days ago

The error will be different in Postman because you are not using the framework, or React app to send the request; so this is likely a false positive.

If you have a 500 error, you should be able to get more information from the Response part of the Network tab in your browsers dev tools.

tykus left a reply on How Can I Make This Text Box • 2 days ago

Something like this integrates with Bootstrap

tykus left a reply on How To Install Laravel Again? • 2 days ago

Can you check that the PATH variable is correctly set; especially the part covered by $HOME?

$ echo $PATH

tykus left a reply on How To Install Laravel Again? • 2 days ago

Open a new shell session to ensure that the PATH change is in effect.

tykus left a reply on Class 'app\Location' Not Found • 2 days ago

Location class is in the App\Admin namespace

13th October, 2017

tykus left a reply on Laravel Eloquent Model - Validation In Model • 5 days ago

Mass assignment protection !== Validation

What are we missing here???

tykus left a reply on Show Message In Alert Box Wih Ajax And Json Laravel • 5 days ago

Seems that you are not preventing the default action (i.e. the form is being submitted over a normal POST request). Its a while since I've needed to jQuery, so maybe others will be better able to explain, but if you return false are the bottom of the event handler (after the AJAX stuff, instead of event.preventDefault() it will prevent the default action and stop propagation of the native event.

tykus left a reply on Laravel Validator • 5 days ago

In Laravel 5.5, you can write a custom validation rule, e.g. using `php artisan make:rule IsSuperAdminRule

// controller / form request

$rules = [
    'email' => ['required', 'email', new IsSuperAdminRule]
];

use Illuminate\Contracts\Validation\Rule;

class IsSuperAdminRule implements Rule
{
    public function passes($attribute, $value)
    {
    $user = User::where('email', $value)->first();

    if (! user) return false; // no user found
    
        return $user->role == 'super admin'; // or however you determine that the user has the role
    }

    public function message()
    {
        return ':attribute should be a super admin.';
    }
}

12th October, 2017

tykus left a reply on Multiple Foreign Keys • 6 days ago

Each foreign key is its own relationship even if they are pointing to the same related class:

public function creator()
{
    return $this->belongsTo(User::class, 'user_id');
}

public function assignee()
{
    return $this->belongsTo(User::class, assigned_to');
}

tykus left a reply on Laravel Return Modified Array Into View • 6 days ago

Why not simply

Book::where('author_id', '=', $uid)->pluck('score');

tykus left a reply on Laravel Api Post Request Redirect Back To External Url • 6 days ago

You are not redirecting; can you use the back() helper to redirect

tykus left a reply on Laravel Transformers • 6 days ago

Depends on your implementation, e.g. if you are using Fractal, then you have the option of defaultIncludes, e.g.

class ClubTransformer extends TransformerAbstract
{
    protected $defaultIncludes = [
        'sporslevels'
    ];

    public function transform(Club $club)
    {
        return [
            'id' => $club->id,
            'name' => $club->name,
    
        ];
    }

    public function includeSporslevels(Club $club)
    {
        return $this->collection($club->sporslevels, new SporsLevelTransformer);
    }

tykus left a reply on Laravel Transformers • 6 days ago

Most transformer implementations will return an array, so this solution should work in the typical transform($club) method:

return [
    'id' => $club->id,
    'name' => $club->name,
    'sporslevels' => $club->sporslevels->map(function ($sporslevel) {
        return [
            'sports_club' => $sporslevel->sports_club,
            'level_club' => "$sporslevel->level_club
        ];
    })
];

You could make an argument for separate collection transformer for the sporslevels and children, but it depends on your needs.

tykus left a reply on How Much Or If Any Business Logic On Eloquent Model? • 6 days ago

If you're not going to need a Repository, then don't implement one. It comes down to your personal/team's preference - for me, I will look to avoid a repository until the code forces me in that direction.

If scopes solved this for you, then mark it as the accepted answer ;)

tykus left a reply on Submit Form With Multiple Values • 6 days ago

So... answer[0] with list_id[0] with section_id[0] with question_id[0], right?

foreach($request as $key => $response) {
    $answer = new Answer;
    $answer->answer = $response->answer;
    $answer->list_id = $request->list_id[$key];
    $answer->section_id = $request->section_id[$key];
    $answer->question_id = $request->question_id[$key];
    $answer->save();
}

tykus left a reply on Submit Form With Multiple Values • 6 days ago

You have the array [] notation on the answer field, but not on the hidden fields.

tykus left a reply on Php Artisan Migrate Command Giving Error • 6 days ago

Can you post each of the migrations here?

tykus left a reply on QueryException SQLSTATE[42S02]: Base Table Or View Not Found • 6 days ago

@kamran186 do you mean your database table name is Post rather than post? Database, table, and column names are typically not case sensitive in my experience (but this might not always be the case).

Are you validating against the Post table, or paginating results somewhere? Off the top of my head, these would be typical situations which result in that particular query.

tykus left a reply on Php Artisan Migrate Command Giving Error • 6 days ago

The migrate:status command compares the migration files with the migrations table in your database, and tells you whether each migration has been run, so it is telling you that none of your migrations have run. This might be correct but depends on when you check the migrations status.

Back to the problem... if you are getting a table already exists failure, can you check that you are not trying to Schema::create('users', ... a second time. Perhaps you were trying to modify a table Schema::table('users', ... and used create by mistake????

tykus left a reply on How Much Or If Any Business Logic On Eloquent Model? • 6 days ago

The question is, what would a repository give you that the solution above does not?

The query scope may give you more flexibility in the future since it can be chained with other Builder methods - what it means to the locked is limited to one method only, which is good for future maintenance.

tykus left a reply on Php Artisan Migrate Command Giving Error • 6 days ago

It seems that your migrations table is out of sync with your schema; although your comment so no tables in the database too suggests that maybe you are connecting to a different database than the one you are looking at.

If you can tolerate losing all data in your existing tables, drop each table in turn and re-run migrations

tykus left a reply on QueryException SQLSTATE[42S02]: Base Table Or View Not Found • 6 days ago

The error is pretty clear that the post table does not exist; re-run your migrations.

This query is possibly as a result of a unique validation albeit not necessarily correctly implemented; if this is familiar to your app, then double-check your validation also.

tykus left a reply on Cleaning Up Dummy Data • 6 days ago

You can drop all data and reset the primary key without dropping the table using truncate() method, for example within php artisan tinker

Car::truncate();

tykus left a reply on What Does ::with Means? • 6 days ago

Correct.

tykus left a reply on What Does ::with Means? • 6 days ago

Eager loading a relationship

tykus left a reply on Cleaning Up Dummy Data • 6 days ago

Without context it is difficult to help.

If you are in development, and you are happy to clear everything from your database, then php artisan migrate:fresh will drop all your tables (and data) and re-run migrations - everything will be lost!

tykus left a reply on How Much Or If Any Business Logic On Eloquent Model? • 6 days ago

Query scopes

    public function scopeLocked() {
        return $query->where('is_finished', true);
    }
$themes = Theme::locked()->pluck('name', 'id');

tykus left a reply on If Authenticated User Has Post? • 6 days ago

@tisuchi how does that work then? If the collection is empty what is $post??

@msyaukat you need to check the collection before the loop:

@if($posts->isEmpty()) // assumes $posts is already a collection
    <p>Add a post</p>
@endif  
@foreach($posts as $post)
    {{ $post->post_title }}
@endforeach 

tykus left a reply on Strange Behavior After Migration • 6 days ago

There are a large number of nouns that have irregular plural forms that defy the usual convention of simply adding s to the end of the regular singular form; person is an extra special case, since people is one of two possible plural forms.

Laravel uses the Doctrine/Common/Inflector/Inflector class to map these irregular nouns to their plural form (and back again). If you have changed the table name to persons in the migration then this breaks Laravel's convention and requires you to specify the table name in the Model.

10th October, 2017

tykus left a reply on Vue.common.js?e881:478 [Vue Warn]: Failed To Mount Component: Template Or Render Function Not Defined • 1 week ago

Delete the node_modules directory and the package-lock.json file and re-run npm install

tykus left a reply on Vue.common.js?e881:478 [Vue Warn]: Failed To Mount Component: Template Or Render Function Not Defined • 1 week ago

I don't know why this is happening, but just wondering why you have laravel elixir and laravel mix installed?

Can you remove the Laravel Elixir dependencies from package.json; and only use Laravel Mix? For a default installation, you should not need to modify a webpack config.

tykus left a reply on Class 'App\Http\Controllers\Auth\Role' Not Found • 1 week ago

You need to import the fully Roles class in your controller, e.g.

<?php

namespace App\Http\Controllers\Auth;

use App\Role; // add this or appropriately namespaced to your domain

class Regist....

tykus left a reply on Trying To Get Non Property Object • 1 week ago

The problem probably is that the user does not have a profile (that's the non-object). There is an optional helper method in Laravel 5.5 to mitigate these issues:

<a href="https://www.facebook.com{{optional($user->profile)->facebook_username}}" class="fa fa-facebook" aria-hidden="true"></a>

tykus left a reply on Vue.common.js?e881:478 [Vue Warn]: Failed To Mount Component: Template Or Render Function Not Defined • 1 week ago

That looks okay, so maybe the problem is you have a runtime-only version of vue.js; which cannot compile templates. Is Vue working correctly otherwise?

tykus left a reply on Vue.common.js?e881:478 [Vue Warn]: Failed To Mount Component: Template Or Render Function Not Defined • 1 week ago

Can you share the VideoUpload component?

tykus left a reply on Models Directory • 1 week ago

Where Is The Models Directory?

When getting started with Laravel, many developers are confused by the lack of a models directory. However, the lack of such a directory is intentional. We find the word "models" ambiguous since it means many different things to many different people. Some developers refer to an application's "model" as the totality of all of its business logic, while others refer to "models" as classes that interact with a relational database.

For this reason, we choose to place Eloquent models in the app directory by default, and allow the developer to place them somewhere else if they choose.

https://laravel.com/docs/5.5/structure#introduction

tykus left a reply on Vue.common.js?e881:478 [Vue Warn]: Failed To Mount Component: Template Or Render Function Not Defined • 1 week ago

Do you have <template> tags surrounding your HTML in the VideoUpload Vue component - it is difficult to see from your OP

tykus left a reply on Search Laravel • 1 week ago

You have a couple of obvious issues (i) if either $search_title or $search_category are null then that query will be executed but probably not return any results (ii) your $search_from probably should be >= not = to `created_at.

You can optionally add where clauses using the query builder's when method, this would give you flexibility to include search parameters (or not) e.g.

$search_title = $request->get('title', null);
$search_category = $request->get('category_id', null);
$search_from = $request->get('date_from', null);

if($search_title || $search_category) 
{
    $articles = Article::when($search_title, function ($query) use ($search_title) {
         return $query->where('title', 'LIKE', '%'.$search_title.'%');
    })->when($search_category, function ($query) use ($search_category) {
         return $query->where('category_id',  '=',  $search_category);
    })->when($search_from, function ($query) use ($search_from) {
         return $query->where('created_at',  '=',  $search_from);
    })->paginate(10);
} else {}
    $articles = Article::latest()->paginate(10);
}

tykus left a reply on How Can I Use Faker For Generate Details According To Registered User? • 1 week ago

You could have the profile factory create the user:

$factory->define(App\Profile::class, function (Faker $faker) {
    return [
        'user_id' => function () {
            return factory(App\User::class)->create()->id;
        },
            'city' => $faker->city,
        'country' => $faker->country,
        'about' => $faker->paragraph(10),
        'remember_token' => str_random(10),
    ];
});

tykus left a reply on Route And Middleware • 1 week ago

All routes except the login route which should be available to guests.

9th October, 2017

tykus left a reply on Possibility To Send In Email My Html Code • 1 week ago

In PHP, you must pass variables from the parent scope into the closure using the use keyword:

Mail::raw($email_content, function ($message) use ($to, $email_title) {
    $message->from('[email protected]', 'Laravel');
    $message->to( $to )->cc('[email protected]');
    $message->subject($email_title);
});

6th October, 2017

tykus left a reply on Class 'App\MyClass' Not Found • 1 week ago

What do you mean create by artisan a new class called Client?

Is the Client class located at {PROJECT_ROOT}/app/Client.php and in the App namespace - i.e.

<?php

namespace App;

class Client
{
    //
}

tykus left a reply on Eloquent API - Resources Doesnt Work Anymore • 1 week ago

Your code doesn't make much sense - _find me a Post with the given $id, if you find one, then get me all active posts?

public function show($id)
{
    $query = Post::find($id);
    // returns either a Post instance or null
        
    if (!empty($query)) {
        // you're here because a Post instance was returned, but now you want a collection of all active posts???
            $data = $query->where('active', '1')->with('category')->with('comments')->get();
    } else {
        // you are here because no Post was found matching `id`
        
            $data = collect();
    }
    
    return BlogPostResource::collection($data);
}

4th October, 2017

tykus left a reply on Users Password Is Not Matching In Production • 2 weeks ago

Are you double bcrypting? Do not bcrypt in the password reset method; it goes through the mutator anyway.

3rd October, 2017

tykus left a reply on Trying To Use Collect.js In Contoller • 2 weeks ago

You are trying to use Javascript inside a PHP controller; it is not supposed to be like this.

$users = User::all(); // this already returns a Laravel Collection

dd($collection->sortBy('first_name'));

tykus left a reply on Route Error In Blade Page Using Laravel 5.5 (Re-post) • 2 weeks ago

If you have a custom name for a resource route, you need to specify the names as an array:

Route::resource('/admin/users', 'AdminUsersController', [
    'names' => [
        'edit' => 'admin.users.edit'
    ]
]);

https://laravel.com/docs/5.1/controllers#restful-naming-resource-routes

29th September, 2017

tykus left a reply on Groupby Error • 2 weeks ago

I think you need the Collection groupBy rather than the native SQL one.

$packages = Package::where('type','domestic')->with('images')->get()->groupBy('state');

tykus left a reply on Passing A Variable From One Method To The Other Within The Same Controller • 2 weeks ago

Don't blame you, this is confusing:

    // ...
    if (!$process->isSuccessful()) {
        return view('errors.testError', ['error' => $process->getOutput()]);
        $test_result = "Test Failed"; // you have already returned, not executed!
    } elseif ($process->isSuccessful()) {
        return view('success.testSuccess', [
            'success' => $process->getOutput()
        ]);
        $test_result = "Test Passed"; // you have already returned, not executed!
        } else {
        echo "System error: issue with getting the test results";
        }

        testresult($test_result);      
       
}

public function testresult($test_result){
    echo $test_result;
}
// ...

isSuccessful() will either evaluate as true or false so this part

        } else {
        echo "System error: issue with getting the test results";
        }

will never get execute, because one of the previous blocks will have.

Once you return early from a function, you're done - nothing else gets executed. You already have returned views in if and elseif blocks, so you do not assign to $test_resultor ever call testresult()

Edit Your Profile
Update

Want to change your profile photo? We pull from gravatar.com.