tykus

Full Stack PHP Developer at FordeHRCloud

Experience

575,140

874 Best Reply Awards

  • Member Since 3 Years Ago
  • 1302 Lessons Completed
  • 2 Favorites

23rd July, 2018

tykus left a reply on Time • 7 hours ago

Timestamps are Carbon instances by default, so you can chain the format method:

$model->created_at->format('d F Y');

21st July, 2018

tykus left a reply on HasOne Could Not Be Converted To String In File • 1 day ago

You would use the Builder if you wanted to constrain the relation query.

tykus left a reply on HasOne Could Not Be Converted To String In File • 1 day ago

This will return a Builder instance:

Printer::find($printerId)->runSize();

whereas this will return the object instance:

Printer::find($printerId)->runSize;

So, your code should look like:

public function imposition($printerId)
{
    return Printer::find($printerId)->runSize;
}

20th July, 2018

tykus left a reply on How To Add Bearer Token In Request Header Using Laravel Controller Or Middleware • 2 days ago

What are you actually trying to do?

19th July, 2018

tykus left a reply on How To Clear The Users Browser Cache So That The Newest Vue Deploy Loads? • 3 days ago

Asset versioning should be solving this issue for you... can you use the mix() helper rather than asset()

18th July, 2018

tykus left a reply on How To Categorizes Data By Month Of Birth • 5 days ago

Use the groupBy collection method, e.g.:

return $users->groupBy(function ($user) {
    return $user->birthday->month; // assuming birthday is a Carbon instance
});

17th July, 2018

tykus left a reply on SQLSTATE[23000]: Integrity Constraint Violation: 1048 Column 'name' Cannot Be Null (SQL: Insert Into `users` (`name`, `email`, `password`, `updated_at`, `created_at`) Values (, , $2y$10$sFHcGna6Q7vofl9.yIqNBOkQ7NzBVKnY3QoNLFUTkezRrqiIE9wRO, 2018-07-17 11: • 6 days ago

Makes a case for validating your request @mian :

$user=User::create($request->validate([
    'name'=>'required',
    'email'=>'required|unique:users,email,
    'password'=>required
]);

You will get validation error rather than a QueryException.

As @lostdreamer_nl says, there probably is no fields called name and email in the form since both values are empty in the SQL above. Remember that an input must have a name attribute in order to be submitted.

15th July, 2018

tykus left a reply on Can You Provide Me A Simple Concept Of Authentication With JWT? • 1 week ago

Presuming you are authenticating for an API, then there is no session (otherwise, what's the point...). You can save the token you receive back from the authentication step in local storage on your browser, and send it in a Authorization header with each request that requires authentication (group these routes in the 'auth:api' middleware)

tykus left a reply on Display Exception Message In A Secure And Proper Way • 1 week ago

Whether it is your own Exception class or something from inside the framework, you can check for the type and return your preferred response/view:

// app/Exceptions/Handler.php
public function render($request, Exception $exception)
{
    if ($exception instanceof \Some\Exception::class) {
        return view(
            'error.view', // your custom view 
            ['message' => $exception->getMessage()], // any data you want to send to the view
            $e->getCode() // exception code
        );
    }

    return parent::render($request, $exception);
}

If you find that you are checking for a lot of custom exceptions inside Handler.php, then you could choose to define a render method inside your own custom class, and return the response from there:

// app/Exceptions/YourCustomException.php
public function render($request, Exception $exception)
{
    return view(
        'error.view', // your custom view 
        ['message' => $exception->getMessage()], // any data you want to send to the view
        $e->getCode() // exception code
    );
}

https://laravel.com/docs/5.6/errors#render-method

12th July, 2018

tykus left a reply on WithCount Not Working With Cache::remember • 1 week ago

No reason that it should not work; are you sure you are not seeing an earlier cached result set; or are you using the tags key for another cached query result?

tykus left a reply on Am I Testing The Logout Correctly. • 1 week ago

You should not need to validate that there is a token provided in every action that requires authentication (such as the getAuthUser method); just make sure that the route has the jwt-auth middleware applied; it will authenticate the user whether there is a token in the query string, or an Authorization header.

If you are using the 1.x version of the package, then the auth()->user() helper will be available to you whenever you properly setup the config/auth.php settings.

tykus left a reply on Why The Query Shows "Property [certificate] Does Not Exist On This Collection Instance."? • 1 week ago

By default, find() should return a single model instance or null unless $sendTo is an array??

tykus left a reply on Why The Query Shows "Property [certificate] Does Not Exist On This Collection Instance."? • 1 week ago

Did you override Model's find method in the RegistrationType model?

tykus left a reply on Why The Query Shows "Property [certificate] Does Not Exist On This Collection Instance."? • 1 week ago

Are you sure that is where the error is coming from? This should return only a single instance, and chaining certificate would be valid;

RegistrationType::find($sendTo)

If you were doing something like the following, then you would have a Collection:

RegistrationType::get()

// or

RegistrationType::all()

tykus left a reply on Undefined Variable • 1 week ago

It appears you have written into your migration

$message->string('message'); 

rather than

$table->string('message'); 

tykus left a reply on Display Exception Message In A Secure And Proper Way • 1 week ago

user friendly to whom; the developer or the end user?

tykus left a reply on Display Exception Message In A Secure And Proper Way • 1 week ago

Set APP_DEBUG=false in your .env file.

tykus left a reply on Controller Logic Issue • 1 week ago

$poId will be assigned only if it is not null, so it could have the same value on the next iteration if $jobitem->po_id is null. Are you missing braces around the block of code that follows the if statements should nothing be created if there is no po_id?

Also, where is $id coming from here?

$records = JobItem::where('job_id', $id)->where('vendor_id', $vendorId);

Lastly, the query above is never executed, it needs a ->get()

tykus left a reply on AssertJson Isn't Seeing The Json That Is Being Returned • 1 week ago

Ah, yes, of course the messages for each field will be an array of values... :facepalm:!

tykus left a reply on AssertJson Isn't Seeing The Json That Is Being Returned • 1 week ago

Your expected JSON is inside an errors key, so you would need to include that:

// ...
->assertJson([
    'errors' => [
        'name' => 'The name field is required.',
        'email' => 'The email field is required.',
        'password' => 'The password field is required.',
    ]
]);

or, if you prefer to find only a fragment of the JSON:

// ...
->assertJsonFragment([
    'name' => 'The name field is required.',
    'email' => 'The email field is required.',
    'password' => 'The password field is required.',
]);

tykus left a reply on Phpunit Testing Not Firing? • 1 week ago

Is PHPUnit already a dependency of your project?

composer require phpunit/phpunit --dev

You can then alias phpunit command to the command that is located inside ./vendor/bin directory; i.e. inside .bashrc or .zshrc:

alias phpunit="./vendor/bin/phpunit"

Now, inside any project that has PHPUnit as a dependency, you can run phpunit from the commandline

11th July, 2018

tykus left a reply on Get Only Hours From Hours And Minutes • 1 week ago

new Date().getHours()

9th July, 2018

tykus left a reply on Error After Git Clone • 1 week ago

Are your php-cli and php-fpm version >7.0?

The php version being used by the webserver can be a different version to the command line

tykus left a reply on How To Render Vue Js In HTML File • 2 weeks ago

You need to assign the result of the Axios request to a property on your Vue data:

data () {
    return {
        your_property: ‘’
    }
}
methods:{
    getData () {
         axios.get().then(({data}) => this.your_property = data)
    }
}

8th July, 2018

tykus left a reply on How To Render Vue Js In HTML File • 2 weeks ago

You can use v-html directive:

<p v-html="your_property"></p>

tykus left a reply on Set Class Element In V-for Loop • 2 weeks ago

What class are you trying to apply and to which element?

Your checkUploadedDocuments() method is going to return a truthy value no matter what... empty objects and arrays are truthy, so you need to return a count of the results of filter (0 is falsey), e.g.

checkUploadedDocuments(id) {
    return this.documentsData.filter(item => item.id === id).length;
}

tykus left a reply on Set Class Element In V-for Loop • 2 weeks ago

A snippet of your relevant code would help greatly!! In general, you need the class binding syntax, <div v-bind:class="{ active: isActive }"></div> where isActive would be a method or property whose truthiness will determine if the active class is applied to the element (div in this case).

tykus left a reply on Provide Error-pages For PDO-Exceptions • 2 weeks ago

Catch the exception in the app/Exceptions/Handler.php by namespaced class:

// app/Exception/Handler.php

class Handler extends ExceptionHandler
{
    // ...
    
    public function render($request, Exception $exception)
    {
        if ($exception instanceof Namespaced/PDO/Exception::class) {
                    // return your custom view
        }
        return parent::render($request, $exception);
    }

    // ...

tykus left a reply on Laravel 5.6: Using Spatie Laravel-permission, Change Names "role" And "permission" • 2 weeks ago

Why are you changing the key and value in the config? You need to leave the keys as their original values, and update the values as you prefer, for example:

   'table_names' => [
       'roles' => 'acciones',
       'permissions' => 'perfiles',
    // ...
]

tykus left a reply on Can I Use Grab Data Using Two Controllers In One Model? • 2 weeks ago

You have plenty of options regarding how this might be structured; for example, you could have [email protected] to return all projects at /projects URI, and a [email protected]which would be scoped to the current user at/users/{user}/projects`

5th July, 2018

tykus left a reply on Get The Message In ValidationException • 2 weeks ago

It is not a MessageBag then..., try $e->errors()['body'][0] as it is probably an array.

tykus left a reply on Get The Message In ValidationException • 2 weeks ago

The ValidationException instance has an errors() method which is an instance of MessageBag, so this should work:

$e->errors()->first('body');

tykus left a reply on Laravel Vue Authentication • 2 weeks ago

You can use JWTAuth to authenticate your user, storing the token returned from login in the client and passing it with every request as a query string or Authorization header.

4th July, 2018

tykus left a reply on Form Request Validation Messages Required Per Field, But Not On Top Of The Page. • 2 weeks ago

I want validation error messages per form field only.

That is what is showed you. You can use the name of the field to get the validation error message using $errors->first('company_name') where $errors is a variable that is available to every view.

tykus left a reply on Form Request Validation Messages Required Per Field, But Not On Top Of The Page. • 2 weeks ago

You can get the error for the specific field from the MessageBag:

<div class="form-group {{ $errors->has('company_name') ? 'has-error' : ''}}">
    <label for="company_name" class="col-sm-3 control-label">Name: </label>
    <div class="col-sm-6">
        <input class="form-control" required="required" name="company_name" type="text" id="company_name">
        {!! $errors->first('company_name', '<p class="text-small text-danger">:message</p>') !!}
    </div>
</div>

tykus left a reply on How To Get Models Of A "hasMany" Relationship • 2 weeks ago

Check out the (HasManyThrough](https://laravel.com/docs/5.6/eloquent-relationships#has-many-through relationship:

// User.php

public function appointments()
{
    return $this->hasManyThrough(Calendar::class, Appointment::class);
}

3rd July, 2018

tykus left a reply on Action [email protected] Not Defined • 2 weeks ago

Does the Form Builder know that you are using a non-conventional namespace for the route? Possibly you need:

{{ Form::open(['action' => 'Vanguard\Http\Controllers\[email protected]']) }}

tykus left a reply on How To Correctly Add A Review Page To My Url • 2 weeks ago

It is not related to the page not found issue, but I would expect this should be a belongsTo, i.e. the foreign key post_id is in the post_reviews table.

How are you browsing to the page, using a Post id, for example/posts/123/reviews, or using a slug, i.e./posts/post-slug/reviews? The first way will use implicit Route Model Binding to find a Post instance with and id123`. In the second case, you would need to change the route key name on the Post model:

// Post.php
public function getRouteKeyName()
{
    return 'slug'; // where 'slug' is a column on the posts table.
}

tykus left a reply on How To Correctly Add A Review Page To My Url • 2 weeks ago

You have a nested controller, so all of the actions should receive the parent:

public function index(Post $post)
{
        $postreviews = $post->reviews()->latest();

    return view('ratings.index', compact('postreviews','posts'));
}

This assumes you have a reviews relation on the Post model

28th June, 2018

tykus left a reply on Error Message Saying Non-object • 3 weeks ago

The first() method is retuning null... use firstOrFail()

24th June, 2018

tykus left a reply on Laravel Type Error: Too Few Arguments To Function • 4 weeks ago

Why do you need two instances of the same EntityRepository class; can you use one instance of that class to get the two datasets required by the view?

22nd June, 2018

tykus left a reply on Method Categories Does Not Exist. • 1 month ago

Your relation is on Article, not Request:

// ...

$article =  auth()->user()->article()->create(array_merge($request->all(), ['images' => $imagesUrl]));
$article->categories()->attach(request('category'));

// ...

tykus left a reply on Call To A Member Function Article() On Null • 1 month ago

So auth()->user() is null, i.e. you are not logged in. Add the auth middleware to the route

21st June, 2018

tykus left a reply on Protect Route For Model State • 1 month ago

Ok, that changes things alright. There are two approaches I would immediately consider; the first would make the original solution more complex, while the second would be simpler in the longer term.

I prefer the second option; which would simply require you to abandon route-model binding for the public Controller method - remove the typehinting and make the query yourself in the controller:

// 'Public' Controller
public function show($slug)
{
    $book = Book::when(auth()->guest(), function ($query) {
            $query->where('published', true);
        })->where('slug', $slug)->firstOrFail();
    
    // return view or whatever
}

You can continue to use the route model binding for the admin controller using the Book typehint in the relevant method, just remove the custom binding in RouteServiceProvider.

tykus left a reply on Protect Route For Model State • 1 month ago

Rather than setting the getRouteKeyName() method in the Model, use it in the Route binding.

Route::bind('book', function ($value) {
    return \App\Book::when(auth()->guest(), function ($query) {
        $query->where('published', true);
    })->where('slug', $value)->firstOrFail();
});

tykus left a reply on Protect Route For Model State • 1 month ago

You could override the Route binding to check if there is an authorized user:

// app/Providers/RouteServiceProvider.php

public function boot()
{
        Route::bind('book', function ($value) {
            return \App\Book::when(auth()->guest(), function ($query) {
                $query->where('published', true);
            })->findOrFail($value);
        });

    parent::boot()
}

tykus left a reply on Extend Auth ResetsPassword Trait? • 1 month ago

You can override any method in the trait with your own implementation of that method in the ResetPasswordController.

Or... you could listen for the PasswordReset event which is fired by Laravel and update the 'password_changed_at' column in the listener.

tykus left a reply on How To Join One To Many And Get All • 1 month ago

You are trying to use the cities relation on the Collection of State instance, not on an individual State instance.; I specifically said that each State instance in the Collection would have the cities property. You must iterate of the $states collection:

foreach($states as $state) {
    // do something with:
    $state->cities;
}

tykus left a reply on How To Join One To Many And Get All • 1 month ago

Add a cities relation to the State model:

public function cities()
{
    return $this->hasMany(City::class)
}

... and eager load cities with teh states:

$states = State::with('cities'')->get();
Edit Your Profile
Update

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