Talinon

Experience

56,790

29 Best Reply Awards

  • Member Since 2 Years Ago
  • 396 Lessons Completed
  • 0 Favorites

13th January, 2018

Talinon left a reply on Select 2 Not Working After Adding Vue. • 4 days ago

Well, I'm still learning Vue myself, but I think your problem is that you're running your JQuery scripts first, then instantiating Vue, which will overwrite the DOM with its own greediness. If you move the Vue code outside of Jquery ready function, and load it first, it should work.

Using your fiddle:

new Vue({el: '#app'});

$(document).ready(function() {
    $(".asd").select2();
});

I think you still need to be careful at this point with mixing Jquery and Vue safely ... This web resource explains better than I can and goes into detail about how you can make Jquery and Vue play nicely together:

https://vuejsdevelopers.com/2017/05/20/vue-js-safely-jquery-plugin/

12th January, 2018

Talinon left a reply on Dependency Issues When Installing Laravel 5.0 On PHP 5.4.16 • 5 days ago

Right, but there is likely a package that is requiring the dependencies you just listed. Around the start of the error message it should state there is a problem with a package?

Talinon left a reply on Dependency Issues When Installing Laravel 5.0 On PHP 5.4.16 • 5 days ago

What dependencies are causing the errors?

Talinon left a reply on How To Make Sign In If The Username And Password Is Already Set • 5 days ago

Laravel has built-in scaffolding for sign in forms. You can auto-generate them with this artisan command:

php artisan make:auth

This will generate the forms and routes for the sign-in.

You'll be able to load the form at http://localhost/login

You also don't need to make a user table, as this is also made for you out-of-the-box. You just need to run your database migration.

For more info you can review these docs: https://laravel.com/docs/5.5/authentication#authentication-quickstart

Talinon left a reply on Dependency Issues • 5 days ago

PHP 7 is a requirement as of Laravel 5.5.

As to why, it's just the natural evolution of the framework to use new versions available.

If you can't upgrade to PHP 7, the next best would be Laravel 5.4, which only requires PHP 5.6.4

Talinon left a reply on PHPunit Tutorial • 5 days ago

That is a good series, but for the basics have you watched this series?

https://www.laracasts.com/series/phpunit-testing-in-laravel

Talinon left a reply on Problem On Some Devices: File_put_contents(): Failed To Open Stream: No Such File Or Directory • 5 days ago

Strange..

Even though this doesn't solve the problem, if you change your cache driver to something like Redis, you probably won't face any problems. It would be faster than file i/o, too.

I couple years back I had a similar problem with session files. Every couple weeks a session would just randomly expire for apparently no good reason. I tried everything, but never got to the bottom of it. Once I switched it Redis, it has never reared its ugly head since.

Talinon left a reply on Problem On Some Devices: File_put_contents(): Failed To Open Stream: No Such File Or Directory • 5 days ago

try these commands:

sudo chgrp www-data storage -R
sudo chmod ug+rwx storage -R

if still doesn't work try:
sudo setfacl -R -d -m g::rw storage

Talinon left a reply on Problem On Some Devices: File_put_contents(): Failed To Open Stream: No Such File Or Directory • 5 days ago

It still sounds like a permission issue. A new IP would create a new cache file, and the new file perhaps is being set to a default mask that can't be accessed.

When you connect with a new IP, check the cache directories for the new file.. what is its permission setting?

You could also try running this command to determine the default umask: ** getfacl storage/framework/* **

Talinon left a reply on Upload Large Csv File To Mysql With Laravel • 5 days ago

Another option you can look into is this package: https://github.com/Maatwebsite/Laravel-Excel

Let's say you are using a form to upload the csv, you could do something like:

Excel::load($request->file('import'))->chunk(250, function ($data) {

    $inserts = [];

    foreach ($data as $row) {

        $record = new \App\MyModel;

        $record->fill($data->toArray());

        $inserts[] = $record;

    }

    // insert into db

});

This way, you can harness the power of Laravel's Model class and set all your mutators and whatever else. This package will also automatically use Laravel's queue system for all the chunked data.

I don't know about this being a "better" solution when it comes to performance, but just throwing this out there as another option for flexibility.

11th January, 2018

Talinon left a reply on Is There A Way To Kind Of Dd() On An Event Listener? • 6 days ago

Log::info(print_r($event, true));

Talinon left a reply on Dropdown Select() Dusk Not Working • 6 days ago

I'm not sure. Just to see if it makes a difference, try a dusk selector?

<select dusk='something'>
.....
</select>


->select('@something','Rempla├žant')

Talinon left a reply on Is There A Way To Kind Of Dd() On An Event Listener? • 6 days ago

For me, the output is quite similar to the browser. Colour coded and fully expanded. I'm using a Linux system - not sure how it would be formatted on other platforms.

Talinon left a reply on Is There A Way To Kind Of Dd() On An Event Listener? • 6 days ago

Sort of... One way I can think of is to run the artisan queue worker from the command line without forking it into the background. The dd() will output to your terminal window:

php artisan queue:work

Talinon left a reply on Problem On Some Devices: File_put_contents(): Failed To Open Stream: No Such File Or Directory • 6 days ago

Did you set the permission of the storage directory recursively? (when using chmod, use the -R option)

Talinon left a reply on Some Js Package Is Not Functioning After Compiling To One File • 6 days ago

Most likely you need some cache busting.

What tool are you using to minify your js into a single file? Tools like Gulp or Webpack/Mix have methods to version your files to bust the browser cache.

8th January, 2018

Talinon left a reply on Why Would A Cloned Request Cause Downstream Issues? • 1 week ago

I think the problem is something along these lines:

CloneRequest gets ran as Before Middleware before anything else. When you run $request->duplicate(), at this moment, there is no session store on the request object. (I think even if there was, this still would fail, because diving into the code shows that the session is not cloned using the duplicate() method).

You then pass the $clone into the next() method which makes its way thru the middleware stack. When it reaches StartSession, it sets a singleton session store on your clone, but the "original" Request object doesn't get set.

Then when you hit your login form, the old() helper within the login.blade.php looks for a session, which doesn't exist on your main Request object (because it is set on your clone), and everything blows up.

This test confirms my theory:

class CloneRequest
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {

        $clone = $request->duplicate();

        $clone->testAttribute = 1;

        \App::bind('test', function() use ($clone) { return $clone; });

        return $next($clone);
    }
}

Then within login.blade.php:

Original Request: {{ dump(\Request::hasSession()) }}
Clone Request: {{ dd(resolve('test')->hasSession() ) }}

// results in

// Original Request:
// false
// Clone Request:
// true


Talinon left a reply on Why Would A Cloned Request Cause Downstream Issues? • 1 week ago

How are you assigning the middleware? I'm guessing it has absolutely nothing to do with the cloned request object.

If you register your CloneRequest middleware before the StartSession middleware (within Kernel.php), you will get the "page has expired" error message. If you turn on debug mode, you'll find the underlying error being that the request object does not have a session store. You will get this if you register it within the application's global middleware stack, or within the 'web' route middleware BEFORE the StartSession class.

Instead, if you assign it within your route file, and wrap your routes within a middleware group, this should work for you.

Route file

Route::middleware(['clone'])->group(function () {
    Auth::routes();

});

app/Kernel.php

protected $routeMiddleware = [
...
  'clone' =>  \App\Http\Middleware\CloneRequest::class,
...
];

Talinon left a reply on Why Would A Cloned Request Cause Authentication Issues? • 1 week ago

When you say it works fine until the authentication middleware, what happens exactly? An error? or do you mean that the object passed into the authentication middleware is the original Request Object and not your clone?

In the case of the latter, have you made any changes to the authentication middleware that refers to the request() helper instead of the passed object?

Talinon left a reply on Create An Or In Laravel Validation At Controller • 1 week ago

I don't think there is any way of doing this using the available validation rules.

This thread is similar to your question and shows an example of using a custom validation rule: https://stackoverflow.com/questions/32006092/laravel-5-1-date-format-validation-allow-two-formats

More information on custom validation rules: https://laravel.com/docs/5.5/validation#custom-validation-rules

5th January, 2018

Talinon left a reply on What Does This Part In The Controller Do? • 1 week ago

The comments above the index method is known as a DocBlock. It is a completely optional form of documentation - but it is a good idea to get into the habit of including them with as many functions as possible. The part that is highlighted (@return) is known as a DocBlock Tag. These tags inform the developer of all the meta-information regarding the method/function. Along with return, another popular tag you'll see is @param, which describes what type of data the function expects to receive for each parameter.

Again, even though DocBlocks are optional, many IDE editors parse this information and use it to improve the lives of the developer. When calling upon a function from a remote file, many editors will offer a popup of the DocBlock to remind the developer what the function they are referencing is expecting, and to what the function will ultimately return when it finishes.

In addition to all this, there are some tools that also parse DocBlocks for functional reasons, such as PHPUnit, which looks for DocBlocks starting with @test to include in its execute of its test suite.

Feel free to google for "PHP DocBlock" and you'll find lots more information.

Talinon left a reply on How To Prevent Ambigous On Eloquent Based Query? • 1 week ago

On your Article model, update the lang() query scope to be explicit.

public funtion scopeLang($query)
{

    return $query->where($this->getTable() . '.lang',  'value');

}

Talinon left a reply on Implicit Model Binding Before Middleware • 1 week ago

If I understand correctly.. If you look into app/Kernel.php, I think this is because the SubstituteBindings middleware is being ran before your (jwt) middleware.

I'm unfamiliar with jwt, so I don't know if there is a way of configuring to run as BeforeMiddleware so it'll execute first before the application's middleware.

Another solution might be to create a new middleware group (or edit the 'api' group) and add the jwt middleware BEFORE the 'bindings' middleware is loaded.

'api' => [
    'throttle:60,1',
    'jwt.middleware',
    'bindings',
    ],
    

Talinon left a reply on Pass Data To Modal From View And Populate After Blade Input Element Has Been Generated • 1 week ago

I may be wrong, but my suspicion is that the javascript is being loaded before the blade file containing your modal is rendered.

I think if you wrap your script in the ready() method - which will execute after the DOM is fully loaded - this might solve your problem.

Give this a try:

$(document).ready(function() {
    $('.modal').on('show.bs.modal', function () {

        // Get the Add User button's data-id attribute
        var id = $('.show_modal').data('id');
        console.log("id = " + id); // this shows that I have the id

        $("#m_id").val( id ); // but this does not occur
    });
});

4th January, 2018

Talinon left a reply on View Composers: Class App\Support\Request Does Not Exist • 1 week ago

@martinbean You're right. I didn't notice the namespace - good eye. For some reason I was thinking it was due to a custom class not being privy to automatic injection.

Talinon left a reply on View Composers: Class App\Support\Request Does Not Exist • 1 week ago

Remove the constructor and just use the request() helper

class CartService { 

    public function totalProducts(){
    return count($request()->cookie('cart'));
    }

Talinon left a reply on Form For Create And Update - Duplication • 1 week ago

I updated my answer above to provide an alternative approach using conditionals and old(), which a lot of developers are gravitating towards.

Using old() is the key.. if old input exists, it'll populate the field with it. If the old input doesn't exist, but the model does, it'll use the model data as the default to populate the field.

old('title', $model->title)

Talinon left a reply on Form For Create And Update - Duplication • 1 week ago

Laravel Collective along with Blade partials makes this is quite easy.

Make 2 files: create.blade.php & update.blade.php As you stated, the form actions are different, so place the respective form tags into each file. Then, paste all your repetitive markup into a "partial" which both blade files can include.

create.blade.php

{!! Form::open(['url' => 'create']) !!}
   @include ('_formBody.blade.php')
{!! Form::close() !!}

update.blade.php


// use form model binding to populate the form
{!! Form::model($model, [method' => 'POST', 'url' => 'update']) !!}
   @include ('_formBody.blade.php')
{!! Form::close() !!}

_formBody.blade.php

// second parameter as null will default to data bound from model
{!! Form::text('title', null, ['class' => 'form-control', 'placeholder' => 'Title required', 'required']) !!}


// whatever else in your form

You can read more about it here: https://laravelcollective.com/docs/5.4/html#form-model-binding

Talinon left a reply on Dusk - Browser Not Popping Up • 1 week ago

Is there some reason why you want the browser to pop up? Running a headless driver provides a fast way of testing. From my limited experience with Dusk, I found the tests assertions passed just fine with no visible browser. The only time the browser would pop up was if the test failed. At the time of a failed test, it opened the browser to take a screenshot, and even this was open for just a split second and then automatically closed.

3rd January, 2018

Talinon left a reply on What Is PHP Artisan? • 2 weeks ago

You can read all about it here:

https://laravel.com/docs/5.5/artisan

Talinon left a reply on No Error In Log, No Email Being Sent. Why? • 2 weeks ago

Try changing your mail driver to log, and see if it creates the mail within your log file. If it logs, your code is fine and it has something to do with your mail configuration. Otherwise, it is probably something within the code - most likely the logic within the UserController that is preventing the call.

MAIL_DRIVER=log

Talinon left a reply on No Error In Log, No Email Being Sent. Why? • 2 weeks ago

If you expect people to take time out of their day to voluntarily assist you, put a little effort into your question.

Have you set up your mail configuration? We don't know. What are you trying to do? Where is your code?

Talinon left a reply on No Error In Log, No Email Being Sent. Why? • 2 weeks ago

Hold on while I consult my crystal ball to retrieve the information you think I have.

Talinon left a reply on Export All Search Results • 2 weeks ago

Store the date when the search criteria is provided in the get request:

public function index(Request $request){

    \Session::put('cases_fromDate', $request->get('from'));
    \Session::put('cases_toDate', $request->get('to'));

    $cases = Case::whereDate('created_at','>=',$request->get('from'))
          ->whereDate('created_at','<=',$request->get('to'))->paginate(6);
    return view('case.index',compact('cases'));
}

Within the export() function:

    $from = Session::get('cases_fromDate', '2018-01-01');
    $to = Session::get('cases_toDate', '2018-01-03');

Session::get() will retrieve the stored value. If none exists, the second parameter is returned instead. You have a few options here...

You could just make them null, and have your query scope ignore them - which is essentially making the default export unfiltered all-time records.

Session::get('cases_fromDate', null);

Another option would be to use a Carbon instance to use the current date as the default

Session::get('cases_fromDate', \Carbon\Carbon::parse());

Or a third option would to check if the session values do not exist, and handle it in any way you wish, such as a redirect with errors.

FYI - You can remove the Request $request type-hint from the export function.

Talinon left a reply on Export All Search Results • 2 weeks ago

Well, since HTTP is a stateless protocol, I think your best bet would be to persist the search criteria to session variables. If a user wishes to export the values, have your controller retrieve the last session values, and run the query.

Something like:

 public function export(Request $request){
       
    $from = Session::get('cases_fromDate', '2018-01-01');  // or null as a default
    $to = Session::get('cases_fromDate', '2018-01-03');

    $items = Case::whereDate('created_at','>=',' $from)
        ->whereDate('created_at','<=', $to)->get();

      \Excel::create('items', function($excel) use($items) {
          $excel->sheet('ExportFile', function($sheet) use($items) {
              $sheet->fromArray($items);
          });
      })->export('xls');
    }

Or better yet, do a bit of refactoring by adding a custom query scope on your Cases model so you could do something cleaner in both your index() and export() methods:

   $items = Case::from($from)->to($to);

22nd December, 2017

Talinon left a reply on Paginate Constrained Eager Load? • 3 weeks ago

I don't think you can paginate eager loaded constraints like this.

I speak about something similar here: https://www.laracasts.com/discuss/channels/laravel/how-to-use-paginate-when-filter-is-used

There may be a better way, but this would give you the result you're after. It may not be the most efficient or prettiest, but you should be able to use this to map over posts and convert them to the LengthAwarePaginator class.

Something like:

    $forumsWithPaginatedPosts = $u->map(function($forum) {

        return $forum->threads->map(function ($thread) {

            $thread->paginatedPosts = paginate($thread->posts);

            return $thread;

        });

    });

Taking your blade code, you could then access your paginated posts via

foreach ($forums as $forum) {
    dd($forum->threads->first()->paginatedPosts);
}

21st December, 2017

Talinon left a reply on Can't Find App.js In Laravel Using Webpackmix.js On Fresh Installation • 3 weeks ago

Actually, that likely isn't the problem unless you're versioning your files. What does the path show in your source when you visit the page?

Talinon left a reply on Can't Find App.js In Laravel Using Webpackmix.js On Fresh Installation • 3 weeks ago

Try changing the asset() helper to mix()

Talinon left a reply on How To Write Code With Laravel Form Style? • 3 weeks ago

{!! Form::select('categorys', $maincatg, null, ['class' => 'form-control']) !!}

Talinon left a reply on Count Through Two Models • 3 weeks ago

Give this a try:

$count = Settlement::where('town_id', Auth::user()->town_id)
    ->with('members', 'ciphers')
    ->where('reon_id', '1')
    ->get()
    ->sum(function ($settlements) {
        return count($settlements->members) +
        $settlements->ciphers->where('cipher', '=', 0)->count();
    });

Talinon left a reply on Count Through Two Models • 3 weeks ago

Give this a try:

$count = Settlement::where('town_id', Auth::user()->town_id)
    ->with('members', 'ciphers')
    ->where('reon_id', '1')
    ->get()
    ->sum(function ($settlements) {
        return count($settlements->members) + count($settlements->ciphers);
    });

Talinon left a reply on Create Table Migration With Inserted Data • 3 weeks ago

You can set default values for your table fields, such as:

$table->string('level')->default('novice');

But, I think what you're really looking for is database seeding:

https://laravel.com/docs/5.5/seeding

20th December, 2017

Talinon left a reply on Getting Data, Grouped, With A Sum()... • 4 weeks ago

Sure.. to retrieve the for_user relationship, you should define that in your Note model and eager load that as well:

$notes = Note::with('user', 'for_user')
    ->where('user_id', 1)
    ->get()
    ->groupBy('for_user_id')
    ->map(function($group) {
        $group->feedback_total = $group->sum('feedback_value');
        $group->user = $group->first()->user;
        $group->for_user = $group->first()->for_user;
        return $group;
});

Then to loop in blade:

@foreach ($notes as $group)

    User: {{ $group->user->name }}
    For User: {{ $group->for_user->name }}

    @foreach ($group as $note)
        {{ dump($note) }}
    @endforeach

@endforeach

Talinon left a reply on What Are Some Alternatives To PhpStorm? • 4 weeks ago

Laravel is still very much the "new kid on the block".. options are somewhat limited.

Talinon left a reply on Getting Data, Grouped, With A Sum()... • 4 weeks ago

Assuming you have a belongsTo relationship on your Notes model, try this:

$notes = Note::with('user')
    ->where('user_id', 1)
    ->get()
    ->groupBy('for_user_id')
    ->map(function($group) {
        $group->feedback_total = $group->sum('feedback_value');
        $group->user = $group->first()->user;
        return $group;
});

For the sake of a simple example, I'll just refer to the first group in the collection...

Access user details:

$notes->first()->user;

Access sum:

$notes->first()->feedback_total;

Talinon left a reply on Time Formate • 4 weeks ago

It is pretty difficult to guide you when you provide so little information. I would suggest putting a little more effort into your questions if you expect people to help.

Taking a stab in the dark, I would say you most likely want to take a look at Carbon:

http://carbon.nesbot.com/docs/

Talinon left a reply on What Are Some Alternatives To PhpStorm? • 4 weeks ago

If Vim key bindings and navigation are a primary concern, most modern editors have this mode, or there are extensions available. These are the two main editors I've been using of late:

Sublime has a built-in Vintage mode: https://www.sublimetext.com/

Microsoft's Visual Code is gaining a lot of attention lately, and also has an extension for Vim emulation: https://code.visualstudio.com/

With both alternatives, you will notice a significant improvement in speed with various tasks, such as file searching.

Talinon left a reply on Attaching Generated PDF To Mailable (Laravel Snappy) • 4 weeks ago

First, I would suggest making the temporary PDF filename unique. This could be as simple as adding a hash or including the id in the filename:

$this->path = 'temp/freightbill_' . $shipment->pro_number . '.pdf';

This way, multiple simultaneous (or near simultaneous) requests won't overwrite your file.

As for cleaning up, there are a few ways I can think of going about it. One way would be just to have a scheduled task (cron job) that executes a script that clears out the temporary directory each night.

Another option would be to run a delayed process that deletes the file after so much time has past. You could harness Symphony's Process Component to execute a script that could delete the file.

http://symfony.com/doc/current/components/process.html

Or, you could create a delayed Job that could be responsible for deleting the file:

https://laravel.com/docs/5.5/queues#delayed-dispatching

19th December, 2017

Talinon left a reply on Attaching Generated PDF To Mailable (Laravel Snappy) • 4 weeks ago

It also looks like loadFile() only takes 1 argument, where loadView() accept an additional argument for view data.. which makes sense. This could be another reason why you were getting the 'page not found' error as it would of only been hitting "/shipments/show"

Edit Your Profile
Update

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