Vilfago

Vilfago

Neuchâtel

Member Since 7 Months Ago

Experience Points 60,350
Experience
Level
Lessons Completed 51
Lessons
Completed
Best Reply Awards 78
Best Answer
Awards
  • Start Your Engines Achievement

    Start Your Engines

    Earned once you have completed your first Laracasts lesson.

  • First Thousand Achievement

    First Thousand

    Earned once you have earned your first 1000 experience points.

  • One Year Member Achievement

    One Year Member

    Earned when you have been with Laracasts for 1 year.

  • Two Year Member Achievement

    Two Year Member

    Earned when you have been with Laracasts for 2 years.

  • Three Year Member Achievement

    Three Year Member

    Earned when you have been with Laracasts for 3 years.

  • Four Year Member Achievement

    Four Year Member

    Earned when you have been with Laracasts for 4 years.

  • Five Year Member Achievement

    Five Year Member

    Earned when you have been with Laracasts for 5 years.

  • School In Session Achievement

    School In Session

    Earned when at least one Laracasts series has been fully completed.

  • Welcome To The Community Achievement

    Welcome To The Community

    Earned after your first post on the Laracasts forum.

  • Full Time Learner Achievement

    Full Time Learner

    Earned once 100 Laracasts lessons have been completed.

  • Pay It Forward Achievement

    Pay It Forward

    Earned once you receive your first "Best Reply" award on the Laracasts forum.

  • Subscriber Achievement

    Subscriber

    Earned if you are a paying Laracasts subscriber.

  • Lifer Achievement

    Lifer

    Earned if you have a lifetime subscription to Laracasts.

  • Laracasts Evangelist Achievement

    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 Achievement

    Chatty Cathy

    Earned once you have achieved 500 forum replies.

  • Laracasts Veteran Achievement

    Laracasts Veteran

    Earned once your experience points passes 100,000.

  • Ten Thousand Strong Achievement

    Ten Thousand Strong

    Earned once your experience points hits 10,000.

  • Laracasts Master Achievement

    Laracasts Master

    Earned once 1000 Laracasts lessons have been completed.

  • Laracasts Tutor Achievement

    Laracasts Tutor

    Earned once your "Best Reply" award count is 100 or more.

  • Laracasts Sensei Achievement

    Laracasts Sensei

    Earned once your experience points passes 1 million.

  • Top 50 Achievement

    Top 50

    Earned once your experience points ranks in the top 50 of all Laracasts users.

12 Nov
4 days ago

Vilfago left a reply on Why This Simple Email Validation Not Working?

is a query sent to the database ?

Vilfago left a reply on Laravel Method Delete Ajax Request

Add some validation, in order that a user cannot delete all your bookings :)

11 Nov
5 days ago

Vilfago left a reply on Can You Make This Scope Cleaner

I think you don't often want products without prices, so maybe a part of this scope could be transfered in a global scope

Vilfago left a reply on DB Performance Decline After SQL Command "optimize" On Table.

Do you still have all needed index on your table?

08 Nov
1 week ago

Vilfago left a reply on Joining Two Tables

You can read this, you will find all you want

https://laravel.com/docs/5.7/eloquent-relationships

06 Nov
1 week ago

Vilfago left a reply on Best Practices - Call On Custom Model Method

I never thought of chaining scope. It's a good idea, thanks !

Vilfago left a reply on Best Practices - Call On Custom Model Method

Ok, so it's better to let __callStatic from the Model class for the query builder, and have some real static method for our custom implementation ?

The real use case is for complex query that I let in the model, so it's look like

    public static function bar()
    {
        return static::where('... ...' )->get();
    }

and I thought it was cleaner with

    protected function bar()
    {
        return$this->where('... ...' )->get();
    }

Could I ask why you do not recommend the first option ? I'll remember things better when I understand them :)

Thank you !

Vilfago started a new conversation Best Practices - Call On Custom Model Method

Hi everyone,

I'm not professional, so I always have some question on "best practice". Below, three codes who are running well

Option 1 - Magic Method

class Foo extends Model
{
    protected function bar()
    {
        return 'bar';
    }
}

class FooController extends Controller
{
    public function index()
    {
        $bar = Foo::bar();
    }
}

Option 2 - Static call

class Foo extends Model
{
    public static function bar()
    {
        return 'bar';
    }
}

class FooController extends Controller
{
    public function index()
    {
        $bar = Foo::bar();
    }
}

Option 3 - Instantiation

class Foo extends Model
{
    public function bar()
    {
        return 'bar';
    }
}

class FooController extends Controller
{
    public function index()
    {
        $foo = new Foo;     
        $bar= $foo->bar();
    }
}

From my perspective, they're all running, so they're all fine... But I heard that static call are not a good way of coding in POO, and rely on magic method (such as __callStatic() in the first example) could be dangerous.

I want to go with the first option, as it seems close to how Laravel work with Model, but it's rely on magic methods that seem to be decried.

Thank you for your input,

Regards,

Vilfago

02 Nov
2 weeks ago

Vilfago left a reply on Get Data From Middleware In Controllers? / Limit User To A Limited Resources.

if your user is logged and your middleware after this, you can add data to user model

Auth::user()->team = $team

And in your controller, you can retrieve it.

31 Oct
2 weeks ago

Vilfago left a reply on Cant Find The Problem In My Relationship

can we see how you organize your database ? Favourite and Article table ?

25 Oct
3 weeks ago

Vilfago left a reply on How Is The Textarea Here On Laravel Managed?

You have the source code via GitHub

Vilfago left a reply on How Is The Textarea Here On Laravel Managed?

You can parse the text with some regex to find some "http://" or "https://", and save them as link.

try : http://foo http://foo.bar https://foo https://foo.bar www.foo.bar

Vilfago left a reply on Calculation For Stock Expiry Date

It should be 2 days, but you can try it... and if not, you can just add +1.

But as your code is working, if you think it's better, just go with it. I just suggest you something else, but you don't have to use it :)

Vilfago left a reply on How Do You Guys Organize Your Assets?

You have two questions, one in the title of the thread, and one in your message.

Most of us read the message and forget the title :)

I put all files in a js folder in asset, and use viewComposer to load only what I need in the layout.blade.php This way I load only the plugin I need, for the ones I don't often use.

Vilfago left a reply on Calculation For Stock Expiry Date

You're right, sorry. It's missing the 2nd argument

$manufacture_date = "2018-10-21";
$shelf_life =  7;
$expiry_date = Carbon::parse($manufacture_date)->addDays(($shelf_life - 1));


$diff_day = Carbon::now()->diffInDays($expiry_date, false);

Vilfago left a reply on Calculation For Stock Expiry Date

It should work, but I think you could do thing faster using Carbon API.

And if you don't print/echo the date, don't waste time formating it.

$manufacture_date = "2018-10-21";
$shelf_life =  7;
$expiry_date = Carbon::parse($manufacture_date)->addDays(($shelf_life - 1));


$diff_day = Carbon::now()->diffInDays($expiry_date);
24 Oct
3 weeks ago

Vilfago left a reply on Trying To Get All Products With The Category_id

//Controller 

 public function category(Request $request)
  {
    $category = Category::with('products')->find($request->get('category_id'));
    dd($category); //Add this line
    return view('shop.1', compact('category'));
  }

What do you get ?

Vilfago left a reply on Trying To Get All Products With The Category_id

sorry, I missed a character.

I update my message above

Vilfago left a reply on Trying To Get All Products With The Category_id

If your view is shop.index you don't have products variable.

If your view is shop.1 you get too many rows if you want only category 1.

I guess it's "category 1" so, I suggest the following :

  • more abstraction
  • less charge on DB
//Controller 

 public function category(Request $request)
  {
    $category = Category::with('products')-find($request->get('category_id'));
    return view('shop.1', compact('category'));
  }


//view
@extends('layouts.app')

@section('content')
    <div class="container">
        <h1>Categoriën:</h1>
        @foreach ($category->products as $product)
                <li>{{ $product->id }} {{ $product->name }}</li>
            @endif
        @endforeach
    </div>
@endsection

It's a first step, you can do better in passing an argument in the route, and use this one instead of $request->get('category_id')

23 Oct
3 weeks ago

Vilfago left a reply on Resource Not Found!! Laravel 5.7

Maybe trying like the doc : https://laravel.com/docs/5.7/routing#route-groups

Route::middleware(['isAdmin'])->group(function () {
   Route::get('admin/transactions', ['as' => 'admin.transactions', 'uses' => '[email protected]']);
});

Vilfago left a reply on Model Class Not Found Error

Yes, I know... but inside the anonymous function of your second whereHas, you don't set that you will use them.

Take a look at my code above, it should work.

Vilfago left a reply on Resource Not Found!! Laravel 5.7

Did you try to remove the middleware from this route, just to see ?

Vilfago left a reply on Model Class Not Found Error

When you call a function, you have to mention that you will use some variable inside it.

    $result1 = Wp_woocommerce_order_item::where('order_item_type' ,'line_item')
        ->whereHas('wp_item_meta', function ($query){
            return $query->where('meta_key','pa_tipo')
                //->where('meta_key', 'Recipient Message')
                ->where('meta_value','gift-pack');})

        ->whereHas('wp_post', function($query1) use($d1, $d2) {
            return  $query1->where('post_type', '=' , 'shop_order' )
                            ->whereBetween('post_date', [$d1,$d2]);
        })
        ->get();

Vilfago left a reply on Resource Not Found!! Laravel 5.7

Do you have any routes like admin/{anything} above in your web.php file ?

Vilfago left a reply on Dynamic

Could you provide us an example on which we can help you ?

But you can still have a read : https://laravel.com/docs/5.7/eloquent-relationships#the-save-method Or watch some video here on Laracasts

Vilfago left a reply on Auto Refreshing Some PHP Code After 1.5 Seconds

If you want to check if it's an integer and it's equal to one, use :

if ($payStat->status ===  1 ) {
                return 'true';
}

http://php.net/manual/en/language.operators.comparison.php

Vilfago left a reply on Model Class Not Found Error

Shouldn't be $result1 = \App\Wp_woocommerce_order_item::where('order_item_type' ,'line_item')... (with a backlsash at the beginning).

Or

<?php
namespace App\Http\Controllers;

use App\Wp_woocommerce_order_item; 


class SomeController extends Controller
{
  public function datePicker(Request $request)
    {
        $format = 'Y-m-d';
        $date = explode(' - ',$request['date']);
        $date1 = $date[0];
        $date2 = $date[1];

        //Convert String Date format to mysql date format
        $tempDate = date_create($date1);
        $d1 = date_format($tempDate, $format);

        $tempDate = date_create($date2);
        $d2 = date_format($tempDate, $format);
    
    $result1 = Wp_woocommerce_order_item::where('order_item_type' ,'line_item')
        ->whereHas('wp_item_meta', function ($query){
            return $query->where('meta_key','pa_tipo')
                //->where('meta_key', 'Recipient Message')
                ->where('meta_value','gift-pack');})

        ->whereHas('wp_post', function($query1){
            return  $query1->where('post_type', '=' , 'shop_order' )
                            ->whereBetween('post_date', [$d1,$d2]);
        })
        ->get();
    foreach ($result1 as $d){
        $array = array();
        $post = App\Wp_postmeta::where('post_id',$d->order_id)->get();
        foreach ($post as $p){
            array_push($array,$p);
        }

        dump($d);

        }
      

    }
}

Vilfago left a reply on Resource Not Found!! Laravel 5.7

public function postLogin(Request $request){
  //some logic
  return redirect('admin/transactions');
}

Vilfago left a reply on For Each Loop

  • Set the relations between user and products,
  • fetch the data (products linked to the auth user)
  • pass the data to the view
  • loop the data using @foreach and @endforeach

But maybe you have to be more specific on your issue :)

22 Oct
3 weeks ago

Vilfago left a reply on Looping Though Object

You have a lot of information in the Request, if you want only your data, you have to use $request->all();

You can try :

public function testing(Request $request) {
        $products = $request->all();

        foreach ($products as $product) {
            print "$product->name";
        }
    }

You can use DebugBar to show your $request to be sure your data is properly build.

Vilfago left a reply on Must Not Open Url Out Of The Loop In Laravel

@tykus : I think it will, it's only regex.

So

  • [a-z]+ will not limit to 1
  • [a-z] should limit to 1
  • [a-z]{2} - should be 2 characters

But I haven't tested, so I will try soon to be sure of that :)

@Sonix : you can use global constraints if needed : https://laravel.com/docs/5.7/routing#parameters-regular-expression-constraints

You set some name for when you want only one letter, or a full name, or a number, etc. and you set it as a global constraint to use it and control the string in every route.

Vilfago left a reply on Must Not Open Url Out Of The Loop In Laravel

Or check that directly in the route : https://laravel.com/docs/5.7/routing#parameters-regular-expression-constraints

Route::get('students/{prefix}', function ($prefix) {
    //
})->where('prefix', '[a-z]');
21 Oct
3 weeks ago

Vilfago left a reply on How To Find A Database Row That Matches A String?

Of course it slow...

You extract 100k records... then for each of the 100k record you check if it exist in your sentence...

So your code after the huge extraction is running 200k time.

It's maybe better to search directly in the db, maybe forcing user to use a @ before the username in order you can find them easier. Like @MartinZeltin

19 Oct
4 weeks ago

Vilfago left a reply on How To Change Variable Value After Asyn Page Load

Could you share a bit of code to make your question more understandable please?

18 Oct
4 weeks ago

Vilfago left a reply on I Can Not Bring The Relationship

It seems that your relation is not properly set in your models.

Vilfago left a reply on I Can Not Bring The Relationship

public function index()
    {
        $propostas = $this->proposition->getByCompanyId();
        $propostas->load('programs.company');
        if (!$propostas) {
            return response()->json(['message' => 'Sem Propostas Cadastradas'], 404);
        }

        return response()->json($propostas, 200);
    }

Vilfago left a reply on What Am I Doing Wrong? Arrrgggh Trying To Get Property Of Non-object

Ok, can you please translate this response below for me (User {#217...)?

I can try, probably not exact, but maybe someone will add information.

As you requested the db for only one row (or Laravel automatically did it behind the scene), you get a model instance (https://laravel.com/docs/5.7/eloquent#retrieving-single-models), in the contrary of multiple rows, when you get a Collection instance (https://laravel.com/docs/5.7/eloquent#collections).

So in the response, you find all attributes of the model (which column is fillable, or hidden, which one is primary key, the standard number of item per page for paginate, etc.)

You have two information usefull, which is #original and #attributes.

First #original shows you data which is in the database. #attributes shows the data after modification or use of a Mutator/Accessor (https://laravel.com/docs/5.7/eloquent-mutators).

When you type $user->id laravel know that you want to access $user->attributes['id'], so it's automatically resolved. (this last statement will not work, it's just to show "what is looks like" behind the scene).

If you want to access the original property, you have to write $user->getOriginal('id'), which will be resolved by something like $user->original['id']

I hope it helps

Vilfago left a reply on What Am I Doing Wrong? Arrrgggh Trying To Get Property Of Non-object

in your view, $user is not an array, so you can loop it.

view

<p>This is user {{ $user->id }}</p>
16 Oct
1 month ago

Vilfago left a reply on Use GroupBy With Paginate Is This Possible?

Why ?

What is the parent_id ?

Vilfago left a reply on Use GroupBy With Paginate Is This Possible?

I think your first try was a good start :

  $article = Article::FindOrFail($id);

//$article->load('comments.user', 'comments.votes');

$comments = Comment::Where('article_id', $article->id)->with('user', 'votes')->paginate(100);

//$comments = $article->comments->groupBy('parent_id'); // Cant use paginate here

//$comments['root'] = $comments[''];

//unset($comments['']);

return view('pages.article.single-article', compact('article', 'comments'));

Why that is not suit your need ?

Vilfago left a reply on Only Process Jobs One At A Time

with --once, your worker will proceed only one job.

By default, your worker will proceed jobs chronologically, unless you set a priority. If you have only one worker running, you will have only one job running at time.

Vilfago left a reply on Use GroupBy With Paginate Is This Possible?

You have several articles on the same page, with the comments linked to each article on the same page ?

Or is it one page with only one article, and the related comment ?

09 Oct
1 month ago

Vilfago left a reply on Relation Issue Between Orders Quantity And Products Inventory

How did you organize your database ?

Do you have an "ordered_product" table with a many to many relations ?

For what I see, you have the quantity on the order, so if a user need 3 different products, he needs to make 3 orders ?

08 Oct
1 month ago

Vilfago left a reply on Ajax Request

any error or more information on what's going on ?

Vilfago left a reply on Ajax Request

var url = 'http://site/change/like';
    $.ajax({
        data: "id=111",
        type: "POST",
        headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
        url: url,
        cache: false,
        contentType: false,
        processData: false,
        success: function(data) {
            console.log(data);   // in answer i received NULL
        }
    });
04 Oct
1 month ago

Vilfago left a reply on How To Change Weekstart To Friday And Weekend To Thursday Sitewide?

Did you add a use Illuminate\Support\Carbon; at the top of AppServiceProvider ?