rodrigo.pedra

rodrigo.pedra

Lead Developer at avaliadora.com.br

Member Since 5 Years Ago

São Carlos, Brazil

Experience Points
216,660
Total
Experience

3,340 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
1014
Lessons
Completed
Best Reply Awards
171
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 44
216,660 XP
Mar
27
6 days ago
Activity icon

Awarded Best Reply on Visual Math Editor

As the documentation says it manipulates a <textarea> I guess so. Just add a name attribute and a standard <form> would send it without a problem.

If you are fine with user inputting LaTeX syntax directly them you have more options. Check this wikipedia comparison table for many editors:

https://en.wikipedia.org/wiki/Formula_editor

There's a column for platform (check for web) and also a column for open source. Note that not being open source does not mean it is not free, although it is likely that most non-opensource options there are paid/licensed.

Mar
23
1 week ago
Activity icon

Replied to How To Login With Different Models In Laravel?

You're welcome =) Hope it helps.

Activity icon

Awarded Best Reply on How To Login With Different Models In Laravel?

Will both models access the same resources?

For example, both will have access to the same protected routes? (/homepage, etc.)

If yes, I guess you are better using a single model, at least for authentication. You can have a User model that holds auth related stuff (email and password) that relates to the Client and Admin models in a polymorphic relation (morphOne) where they hold other data exclusive to those models.

If no, clients and admin use different routes, then you can differentiate guarding those routes with auth:client or auth:admin depending on their requirements. I have this setup on a project where we had a legacy database structure that our client didn't want to change. It is an e-commerce solution, so the public facing routes requires a member guard, while the admin backend routes require an admin guard. Both with separate login pages. If both member and admin access is needed for the same user, they need to be registered on each table.

When you don't specify a guard for a route Laravel fallback to the default guard to check for the user. It doesn't loop for every guard available. Imagine if you have 10 guards defined, it wouldn't be very performant to make 10 DB queries before failing for every guarded route.

Also Laravel only keeps the auth identifier (generally the id column) value in the session. So without specifying the guard it has no way to tell from each guard you expect that id to come from.

Also how you do differentiate an admin with id = 1 from a client with id = 1? If you have a single user table, two users would not have the same id. You can differentiate clients from admin by adding a role column to the users table, or by using a RBAC (role-based access control) strategy, there are many packages that implements that, and as @jlrdw said, @JeffreyWay covered it so many times here in Laracasts' videos. One package I usually reach for that is this:

https://github.com/spatie/laravel-permission/

If by all means you need to have separated models, can't have a single table and the users from those models will have access to the same routes, you can write a custom User Provider that loops through both models. The official documentation has a section about it:

https://laravel.com/docs/7.x/authentication#adding-custom-user-providers

One tip is to override the getAuthIdentifier method on the Client and Admin models to prefix it with a reference (for example: client:1 and admin:1) so in the provider you can tell which model to query. Also the auth identifier is what is persisted into the session.

You can check the EloquentUserProvider implementation to know how to write your custom one.

Add that custom provider to the default guard and profit.

Activity icon

Replied to How To Login With Different Models In Laravel?

Will both models access the same resources?

For example, both will have access to the same protected routes? (/homepage, etc.)

If yes, I guess you are better using a single model, at least for authentication. You can have a User model that holds auth related stuff (email and password) that relates to the Client and Admin models in a polymorphic relation (morphOne) where they hold other data exclusive to those models.

If no, clients and admin use different routes, then you can differentiate guarding those routes with auth:client or auth:admin depending on their requirements. I have this setup on a project where we had a legacy database structure that our client didn't want to change. It is an e-commerce solution, so the public facing routes requires a member guard, while the admin backend routes require an admin guard. Both with separate login pages. If both member and admin access is needed for the same user, they need to be registered on each table.

When you don't specify a guard for a route Laravel fallback to the default guard to check for the user. It doesn't loop for every guard available. Imagine if you have 10 guards defined, it wouldn't be very performant to make 10 DB queries before failing for every guarded route.

Also Laravel only keeps the auth identifier (generally the id column) value in the session. So without specifying the guard it has no way to tell from each guard you expect that id to come from.

Also how you do differentiate an admin with id = 1 from a client with id = 1? If you have a single user table, two users would not have the same id. You can differentiate clients from admin by adding a role column to the users table, or by using a RBAC (role-based access control) strategy, there are many packages that implements that, and as @jlrdw said, @JeffreyWay covered it so many times here in Laracasts' videos. One package I usually reach for that is this:

https://github.com/spatie/laravel-permission/

If by all means you need to have separated models, can't have a single table and the users from those models will have access to the same routes, you can write a custom User Provider that loops through both models. The official documentation has a section about it:

https://laravel.com/docs/7.x/authentication#adding-custom-user-providers

One tip is to override the getAuthIdentifier method on the Client and Admin models to prefix it with a reference (for example: client:1 and admin:1) so in the provider you can tell which model to query. Also the auth identifier is what is persisted into the session.

You can check the EloquentUserProvider implementation to know how to write your custom one.

Add that custom provider to the default guard and profit.

Mar
22
1 week ago
Activity icon

Replied to HTTP Client Configuration

And I forgot to say on my last response: thanks for the update =)

Activity icon

Replied to HTTP Client Configuration

I looked into the Client source code.

When you call asForm internally it calls that method.

Activity icon

Awarded Best Reply on HTTP Client Configuration

Try this:

$response = Http::withToken('xxx')
    ->bodyFormat('none') // can be anything different of json, form_params or multipart
    ->withOptions(['body' => null]) // set guzzle options
    ->post('https://domain.com/api/account/1/get_stuff', []);
Activity icon

Replied to HTTP Client Configuration

I was thinking about it and maybe you don't need the withOptions(...), only setting bodyFormat(...) to something Guzzle doesn't expect as a body format shoudl suffice.

I tested locally and it should not send the body, but please test against your endpoint to see if it works:

$response = Http::withToken('xxx')
    ->bodyFormat('none')
    ->post('https://domain.com/api/account/1/get_stuff', []);
Activity icon

Awarded Best Reply on Route Model Binding In 7.x

Try this:

Route::resource('posts', 'PostController')->parameter('posts', 'post:slug');

internally resources use the route helpers (get, post, ...) to create the routes. the parameter method tells the resource how to replace the route placeholders

Activity icon

Replied to HTTP Client Configuration

Try this:

$response = Http::withToken('xxx')
    ->bodyFormat('none') // can be anything different of json, form_params or multipart
    ->withOptions(['body' => null]) // set guzzle options
    ->post('https://domain.com/api/account/1/get_stuff', []);
Mar
20
1 week ago
Activity icon

Replied to Visual Math Editor

As the documentation says it manipulates a <textarea> I guess so. Just add a name attribute and a standard <form> would send it without a problem.

If you are fine with user inputting LaTeX syntax directly them you have more options. Check this wikipedia comparison table for many editors:

https://en.wikipedia.org/wiki/Formula_editor

There's a column for platform (check for web) and also a column for open source. Note that not being open source does not mean it is not free, although it is likely that most non-opensource options there are paid/licensed.

Activity icon

Awarded Best Reply on Send The User Back If An Error Thrown

@tudosm take a look at this section on the docs:

https://laravel.com/docs/7.x/errors#the-exception-handler

There you can configure the behavior of your app when some exception is thrown.

Activity icon

Replied to Visual Math Editor

One site I used to solving equations has an online editor:

https://www.fxsolver.com/edit/formula/

so I checked the source to see what they were using:

http://mathdox.org/formulaeditor/

It seems very old and is not updated since 2008 (according to the linked sourceforge site), but it works and is free.

===

EDIT Found this one:

http://www.imatheq.com/corpsite/index.html

Seems more modern, but requires a subscription. Seems you can add to a website as long you have the correct license

Mar
18
2 weeks ago
Activity icon

Replied to Getting Laravel Sessions

You can use the Crypt facade:

$encryptedValue = Crypt::encrypt($value);

Where value would be your cookie's content

https://laravel.com/docs/7.x/encryption

Activity icon

Replied to Issue With Modulo Operator I Found On Stack Overflow

Reading the accepted answer from the stackoverflow link you posted, I guess that was a typo and the user who answered meant $myarray in the for loop.

There they loop an input array and showcase how to use the modulo.

As your use-case is to assign a color to a user, if your user's model primary key is an integer (which is the default) you can use the modulo array as the following:

public function getHexColorAttribute()
{
    $colors = ['#54323', '#504953', '#405949']; 
    $count = count($colors);

    return  $colors[$this->getKey() % $count];
}

->getKey() will return the model's primary key, in case you default to name it id you can replace $this->getKey() by $this->id if you prefer so.

EDIT fix accessor method name to match Laravel convention:

https://laravel.com/docs/7.x/eloquent-mutators#defining-an-accessor

You can use it like this:

$userColor = $user->hex_color;

Also, didn't see @snapey answer before posting mine, it is essentially the same thing.

Activity icon

Replied to Send The User Back If An Error Thrown

@tudosm take a look at this section on the docs:

https://laravel.com/docs/7.x/errors#the-exception-handler

There you can configure the behavior of your app when some exception is thrown.

Activity icon

Replied to Relationship Condition In Model

Well, your relationship is a hasOne it will only return one record.

If you want all the related supervisors, try changing it to a hasMany relation:

public function supervisor(){
    return $this->hasMany('App\EmployeeToSupervisor','emp_id','emp_id')
        ->whereExists(function ($query) {
            $query->selectRaw(1)
                ->from('pipdetails')
                ->whereColumn('pipdetails.emp_id', 'employee_to_supervisor.emp_id')
                ->whereRaw('pipdetails.pipdateofissue BETWEEN employee_to_supervisor.from_date AND employee_to_supervisor.to_date');
        });
}

EDIT fixed relation on snippet

Activity icon

Awarded Best Reply on Laravel Mysql Select All Except An Array Of Values ?

Can you use whereNotIn:

$data = Materiel::join('Types', 'Materiels.type_id', '=', 'Types.type_id')
    ->join('Users', 'Materiels.user_id', '=', 'Users.id')
    ->select('Materiels.id', 'Materiels.mat_code', 'Materiels.mat_designation', 'Materiels.mat_ns', 'Types.type_designation', 'Materiels.mat_description', 'Materiels.note', 'Users.username', 'Materiels.mat_date')
->whereNotIn('column', ['foo', 'bar', 'baz']);

In the example above replace column with the column name you want to filter, and the array with the values you don't want it to have.

Mar
17
2 weeks ago
Activity icon

Replied to Reload Page In Vue.js

You’re welcome =)

Activity icon

Awarded Best Reply on Reload Page In Vue.js

As user is passed as a prop its properties are not reactive, so Vue won't update the UI if you try to change them..

Similar to what you do to qr and qr_code you should copy that value to a data property on creating and updating that:

<template>
    <div class="text-center">
        <div class="checkbox">
            <label>
                <!-- CHANGED HERE -->
                <input type="checkbox" v-model="toggle" :disabled="google2fa_secret"> {{ toggletext }}
            </label>
        </div>

        <hr>
        <div v-if="toggle">
            <!-- CHANGED HERE -->
            <div v-if="google2fa_secret">
                <!-- CHANGED HERE -->
                <p v-if="google2fa_secret">Your 2FA Secret Key</p>
                <!-- CHANGED HERE -->
                <h3>{{ google2fa_secret }}</h3>

                <button class="md-button md-raised md-accent" @click="disable">{{ disabletext }}</button>

                <p>Instructions for first time setup:</p>
                <p>Please install the <a :href="google_link">Google Authenticator</a> first.</p>
                <p>
                    You can install it from the
                    <a href="https://play.google.com/store/apps/details?id=com.google.android.apps.authenticator2&hl=en">Google
                        Play</a> or
                    <a href="https://apps.apple.com/us/app/google-authenticator/id388497605">Apple Store</a>.
                </p>

                <p>Scan The QR code:</p>
                <img :src="qr_code" alt="qr_code"/>
                <br>

                <form action="/google2fa/authenticate" method="POST">
                    <input type="hidden" v-model="csrf" name="_token">
                    <input name="one_time_password" type="text">

                    <button type="submit">Authenticate</button>
                </form>


            </div>

            <div v-else>
                <button class="md-button md-raised md-accent" @click="generate">{{ generatetext }}</button>
            </div>
        </div>

        <div v-else>
            <p>You don't have the 2FA enabled.</p>
        </div>


    </div>

</template>

<script>
    import axios from 'axios';

    export default {
        name: "TwoFactorAuth",
        props: {
            qr: {
                type: String,
                required: false,
                default: '',
            },
            user: {
                type: Object,
                required: true,
            },
            toggletext: {
                type: String,
                required: true,
            },
            generatetext: {
                type: String,
                required: true,
            },
            disabletext: {
                type: String,
                required: true,
            },
        },
        data() {
            return {
                toggle: !!this.user.google2fa_secret,
                google_link: 'https://www.google.com/landing/2step/',
                qr_code: this.qr,
                google2fa_secret: this.user.google2fa_secret, // ADDED HERE
                csrf: ''
            }
        },
        methods: {
            generate() {
                axios.post(`/api/user/${this.user.eid}/2fa`)
                    .then(res => {
                        this.google2fa_secret = res.data.secret;  // CHANGED HERE
                        this.qr_code = res.data.qr;


                    })
                    .catch(this.handleError);
            },
            disable() {
                axios.post(`/api/user/${this.user.eid}/2fa`, {disable: true})
                    .then(res => {
                        this.google2fa_secret = res.data.secret; // CHANGED HERE
                        this.qr_code = '';
                        this.toggle = false;
                    })
                    .catch(this.handleError);
            }
        },
        mounted() {
            this.csrf = document.head.querySelector('meta[name="csrf-token"]').content;

        }
    }
</script>

<style scoped>

</style>
Activity icon

Replied to Reload Page In Vue.js

Hi @kalimeromk sorry for the late response, had to leave for a while. If forgot to change a line inside the generate method.

I updated the snippet above and added a comment in the line.

Vue docs says you should avoid using $forceUpdate:

If you find yourself needing to force an update in Vue, in 99.99% of cases, you’ve made a mistake somewhere.

https://vuejs.org/v2/guide/components-edge-cases.html#Forcing-an-Update

If you try the updated solution and verify it works, please let me know.

Activity icon

Replied to Model::all() Returns Empty Though Records Exist In The Database

You're welcome =) Glad it worked out.

If you want please mark the thread as solved, so others who search for the same issue can find a solution.

Activity icon

Awarded Best Reply on Eloquent: How To Change The Display Of Data

Great it helped =)

But I find a bug on the markup generation, please update to this:

<tbody>
    @foreach($readers as $reader)
        <tr>
            <td rowspan="{{ $reader->books->count() }}">{{$reader->name}}</td>
            @foreach($reader->books as $book)
                {!! $loop->first ? '' : '</tr><tr>' !!}

                <td>{{$book->title}}</td>
                <td>{{$book->pivot->maxreturndate}}</td>
                <td>
                    <form action="{{ route('checkedouts.destroy', $book->pivot->id)}}" method="post">
                        @csrf
                        @method('DELETE')
                        <button class="btn btn-danger" type="submit">Buch zurückgebracht</button>
                    </form>
                </td>

                {!! $loop->last ? '' : '</tr>' !!}
            @endforeach
        </tr>
    @endforeach
</tbody>

On the second books iteration it will close the previous row before opening a new one.

In every books loop it will close the current row. The last one is skipped because we close it on the outer loop.

Activity icon

Replied to Reload Page In Vue.js

My code has some comments on the changes.

In the <template> look for these comment:

<!-- CHANGED HERE -->

The changes are below each of these comments

On the <script> look for this comments:

// ADDED HERE

 // CHANGED HERE

The changes are in the same line as the comments.

Activity icon

Replied to Eloquent: How To Change The Display Of Data

Great it helped =)

But I find a bug on the markup generation, please update to this:

<tbody>
    @foreach($readers as $reader)
        <tr>
            <td rowspan="{{ $reader->books->count() }}">{{$reader->name}}</td>
            @foreach($reader->books as $book)
                {!! $loop->first ? '' : '</tr><tr>' !!}

                <td>{{$book->title}}</td>
                <td>{{$book->pivot->maxreturndate}}</td>
                <td>
                    <form action="{{ route('checkedouts.destroy', $book->pivot->id)}}" method="post">
                        @csrf
                        @method('DELETE')
                        <button class="btn btn-danger" type="submit">Buch zurückgebracht</button>
                    </form>
                </td>

                {!! $loop->last ? '' : '</tr>' !!}
            @endforeach
        </tr>
    @endforeach
</tbody>

On the second books iteration it will close the previous row before opening a new one.

In every books loop it will close the current row. The last one is skipped because we close it on the outer loop.

Activity icon

Replied to Reload Page In Vue.js

As user is passed as a prop its properties are not reactive, so Vue won't update the UI if you try to change them..

Similar to what you do to qr and qr_code you should copy that value to a data property on creating and updating that:

<template>
    <div class="text-center">
        <div class="checkbox">
            <label>
                <!-- CHANGED HERE -->
                <input type="checkbox" v-model="toggle" :disabled="google2fa_secret"> {{ toggletext }}
            </label>
        </div>

        <hr>
        <div v-if="toggle">
            <!-- CHANGED HERE -->
            <div v-if="google2fa_secret">
                <!-- CHANGED HERE -->
                <p v-if="google2fa_secret">Your 2FA Secret Key</p>
                <!-- CHANGED HERE -->
                <h3>{{ google2fa_secret }}</h3>

                <button class="md-button md-raised md-accent" @click="disable">{{ disabletext }}</button>

                <p>Instructions for first time setup:</p>
                <p>Please install the <a :href="google_link">Google Authenticator</a> first.</p>
                <p>
                    You can install it from the
                    <a href="https://play.google.com/store/apps/details?id=com.google.android.apps.authenticator2&hl=en">Google
                        Play</a> or
                    <a href="https://apps.apple.com/us/app/google-authenticator/id388497605">Apple Store</a>.
                </p>

                <p>Scan The QR code:</p>
                <img :src="qr_code" alt="qr_code"/>
                <br>

                <form action="/google2fa/authenticate" method="POST">
                    <input type="hidden" v-model="csrf" name="_token">
                    <input name="one_time_password" type="text">

                    <button type="submit">Authenticate</button>
                </form>


            </div>

            <div v-else>
                <button class="md-button md-raised md-accent" @click="generate">{{ generatetext }}</button>
            </div>
        </div>

        <div v-else>
            <p>You don't have the 2FA enabled.</p>
        </div>


    </div>

</template>

<script>
    import axios from 'axios';

    export default {
        name: "TwoFactorAuth",
        props: {
            qr: {
                type: String,
                required: false,
                default: '',
            },
            user: {
                type: Object,
                required: true,
            },
            toggletext: {
                type: String,
                required: true,
            },
            generatetext: {
                type: String,
                required: true,
            },
            disabletext: {
                type: String,
                required: true,
            },
        },
        data() {
            return {
                toggle: !!this.user.google2fa_secret,
                google_link: 'https://www.google.com/landing/2step/',
                qr_code: this.qr,
                google2fa_secret: this.user.google2fa_secret, // ADDED HERE
                csrf: ''
            }
        },
        methods: {
            generate() {
                axios.post(`/api/user/${this.user.eid}/2fa`)
                    .then(res => {
                        this.google2fa_secret = res.data.secret;  // CHANGED HERE
                        this.qr_code = res.data.qr;


                    })
                    .catch(this.handleError);
            },
            disable() {
                axios.post(`/api/user/${this.user.eid}/2fa`, {disable: true})
                    .then(res => {
                        this.google2fa_secret = res.data.secret; // CHANGED HERE
                        this.qr_code = '';
                        this.toggle = false;
                    })
                    .catch(this.handleError);
            }
        },
        mounted() {
            this.csrf = document.head.querySelector('meta[name="csrf-token"]').content;

        }
    }
</script>

<style scoped>

</style>
Activity icon

Replied to Laravel Mysql Select All Except An Array Of Values ?

Can you use whereNotIn:

$data = Materiel::join('Types', 'Materiels.type_id', '=', 'Types.type_id')
    ->join('Users', 'Materiels.user_id', '=', 'Users.id')
    ->select('Materiels.id', 'Materiels.mat_code', 'Materiels.mat_designation', 'Materiels.mat_ns', 'Types.type_designation', 'Materiels.mat_description', 'Materiels.note', 'Users.username', 'Materiels.mat_date')
->whereNotIn('column', ['foo', 'bar', 'baz']);

In the example above replace column with the column name you want to filter, and the array with the values you don't want it to have.

Activity icon

Replied to Count And Sum Db Query

They will be available for every date on the bookings table, for example:

  • In Day 1 there were 1 localbook order and no selfbook orders: there will be a record for day 1
  • In Day 2 there were 1 localbook order and 1 selfbook order: there will be a record for day 2
  • In Day 3 there were no localbook orders and 1 selfbook order: there will be a record for day 3
  • In Day 4 there were no localbook orders and no selfbook order: there won't be a record for day 4

If you need to have all days regardless of days with no orders from both sellers you can do it in the DB query (kind of hard, but doable), but my suggestion is handling this on the PHP side.

Regarding any reading material on SQL, unfortunately I don't have any material to recommend. Laracasts has a series on SQL, very good one, but it doesn't cover this kind of subject (aggregating over values or handling missing records).

Activity icon

Awarded Best Reply on Count And Sum Db Query

Ok, we can do it both in the DB query or in the collection.

I find doing in the DB easier:

$bookings = DB::table('bookings')
    ->select([
        'org_id',
        DB::raw('CAST(created_at AS DATE) as day'),
        DB::raw("SUM(CASE WHEN payment_gateway = 'LocalBook' THEN 1 ELSE 0 END) AS bookings_localbook_per_day"),
        DB::raw("SUM(CASE WHEN payment_gateway = 'LocalBook' THEN commison ELSE 0 END) AS commison_localbook_per_day"),
        DB::raw("SUM(CASE WHEN payment_gateway = 'selfBook' THEN 1 ELSE 0 END) AS bookings_selfbook_per_day"),
        DB::raw("SUM(CASE WHEN payment_gateway = 'selfBook' THEN commison ELSE 0 END) AS commison_selfbook_per_day"),
    ])
    ->where('pay', '>', 0)
    ->groupBy(['org_id', DB::raw('CAST(created_at AS DATE)')])
    ->get()
    ->toArray();
Activity icon

Awarded Best Reply on How To "translate" This SQL Query In Laravel Controller

Yes, but in your case I guess this would work:

$data = DB::table(DB::raw('video_categories AS t1'))
    ->join(DB::raw('video_categories AS t2'), 't1.id', '=', 't2.parent_id')
    ->get();

And if not you can always execute a raw SQL:

$data = DB::select('SELECT t1.* , t2.name as sub_category from video_categories t1 INNER JOIN video_categories t2 on t1.id = t2.parent_id');
Activity icon

Replied to Count And Sum Db Query

Ok, we can do it both in the DB query or in the collection.

I find doing in the DB easier:

$bookings = DB::table('bookings')
    ->select([
        'org_id',
        DB::raw('CAST(created_at AS DATE) as day'),
        DB::raw("SUM(CASE WHEN payment_gateway = 'LocalBook' THEN 1 ELSE 0 END) AS bookings_localbook_per_day"),
        DB::raw("SUM(CASE WHEN payment_gateway = 'LocalBook' THEN commison ELSE 0 END) AS commison_localbook_per_day"),
        DB::raw("SUM(CASE WHEN payment_gateway = 'selfBook' THEN 1 ELSE 0 END) AS bookings_selfbook_per_day"),
        DB::raw("SUM(CASE WHEN payment_gateway = 'selfBook' THEN commison ELSE 0 END) AS commison_selfbook_per_day"),
    ])
    ->where('pay', '>', 0)
    ->groupBy(['org_id', DB::raw('CAST(created_at AS DATE)')])
    ->get()
    ->toArray();
Activity icon

Replied to How To "translate" This SQL Query In Laravel Controller

Yes, but in your case I guess this would work:

$data = DB::table(DB::raw('video_categories AS t1'))
    ->join(DB::raw('video_categories AS t2'), 't1.id', '=', 't2.parent_id')
    ->get();

And if not you can always execute a raw SQL:

$data = DB::select('SELECT t1.* , t2.name as sub_category from video_categories t1 INNER JOIN video_categories t2 on t1.id = t2.parent_id');
Activity icon

Replied to Push To An Existing Code To An Existing Repository: Bitcucket

That message says your you have nothing to commit.

Do you have any git history in this new repo?

If not try this:

$ rm -rf ,git
$ git init
$ git add --all
$ git commit -m 'initial commit'
$ git remote add origin https://[email protected]/xxxxx/rental.git
$ git branch --set-upstream-to origin/master
$ git push --force

Line per line explanation:

  1. will remove any git history or repository from this folder
  2. Will create a new local git repository on this folder
  3. Will stage all files
  4. Will commit staged files
  5. Will add a new remote called origin
  6. Will set that remote as the default remote when pushing/pulling
  7. Will push the commits to remote forcing the remote history to be overwritten
Activity icon

Replied to How To "translate" This SQL Query In Laravel Controller

Try this:

$data = DB::table('video_categories', 't1')
    ->join(DB::raw('video_categories AS t2'), 't1.id', '=', 't2.parent_id')
    ->get();

the table method supports to an alias parameter was added in some Laravel 6 patch.

Activity icon

Awarded Best Reply on Laravel Mix Is Not Complying Font Awesome Properly

Weird, the fonts path should be resolved by the sass compiler.

As a workaround add this line to your webpack.mix.js file:

mix.copyDirectory('node_modules/@fortawesome/fontawesome-free/webfonts', 'public/webfonts');
Activity icon

Replied to Laravel Mix Is Not Complying Font Awesome Properly

No, unfotunately.

I tried locally, my webpack,mix.js is like this:

const mix = require('laravel-mix');

mix.sass('resources/assets/sass/app.scss', 'public/css');

and app.scss is:

// [email protected]

@import '[email protected]/fontawesome-free/scss/fontawesome.scss';
@import '[email protected]/fontawesome-free/scss/solid.scss';
@import '[email protected]/fontawesome-free/scss/regular.scss';
@import '[email protected]/fontawesome-free/scss/brands.scss';

An paths are translated correctly, for example:


@font-face {
  font-family: 'Font Awesome 5 Free';
  font-style: normal;
  font-weight: 900;
  font-display: auto;
  src: url(/fonts/vendor/@fortawesome/fontawesome-free/webfa-solid-900.eot?89e02bae13c9131c7468b1e729339ac1);
  src: url(/fonts/vendor/@fortawesome/fontawesome-free/webfa-solid-900.eot?89e02bae13c9131c7468b1e729339ac1) format("embedded-opentype"), url(/fonts/vendor/@fortawesome/fontawesome-free/webfa-solid-900.woff2?55eb2a60e8181f0e68b558c991973bf0) format("woff2"), url(/fonts/vendor/@fortawesome/fontawesome-free/webfa-solid-900.woff?cdfec5cf5e9840889790bcf2c4042583) format("woff"), url(/fonts/vendor/@fortawesome/fontawesome-free/webfa-solid-900.ttf?75f38a159982b6bd1704891332d95fa7) format("truetype"), url(/fonts/vendor/@fortawesome/fontawesome-free/webfa-solid-900.svg?0724bb8b89ab6b8b9b7df917b17be0b7) format("svg");
}

maybe it is the mix version, I am using version5.

But don't worry. If in a later update the paths start to be resolved mix will copy the fonts automatically to the ./public/fonts/vendor folder and your app won't break.

Activity icon

Replied to Count And Sum Db Query

Well, there are tow records because the payment_gateway is different for each record.

Do you still want to group it? How do you want to handle fields with the same name?

One options is to group by org_id and date after retrieval from database in another array inside that record.

Tell me if you still want to do it

Activity icon

Replied to Laravel Mix Is Not Complying Font Awesome Properly

Webpack should resolve the sass url imports to local paths. Somehow it is not working.

My last answer tells mix to copy that folder for you so you won't have to remember doing it.

It should keep working, even if later your sass compilation starts working as expected.

Activity icon

Replied to Laravel Mix Is Not Complying Font Awesome Properly

Weird, the fonts path should be resolved by the sass compiler.

As a workaround add this line to your webpack.mix.js file:

mix.copyDirectory('node_modules/@fortawesome/fontawesome-free/webfonts', 'public/webfonts');
Activity icon

Replied to Eloquent: How To Change The Display Of Data

Not quite sure I understood, but try changing your table tbody to this:

<tbody>
    @foreach($readers as $reader)
        <tr>
            <td rowspan="{{ $reader->books->count() }}">{{$reader->name}}</td>
            @foreach($reader->books as $book)
                {!! $loop->first ? '' : '<tr>' !!}

                <td>{{$book->title}}</td>
                <td>{{$book->pivot->maxreturndate}}</td>
                <td>
                    <form action="{{ route('checkedouts.destroy', $book->pivot->id)}}" method="post">
                        @csrf
                        @method('DELETE')
                        <button class="btn btn-danger" type="submit">Buch zurückgebracht</button>
                    </form>
                </td>

                {!! $loop->first ? '' : '</tr>' !!}
            @endforeach
        </tr>
    @endforeach
</tbody>

This will create a new row for each reader's book. On the first book we don't need to create a new row because we are already in the reader's name row. The rowspan attribute will make sure the reader's name span through all theirs books rows.

You can read more about the loop variable in the docs:

https://laravel.com/docs/7.x/blade#the-loop-variable

EDIT fixed html output

Activity icon

Awarded Best Reply on 'v-for' With 'v-if' Vuejs/laravel

There as a missing < before the first </td>.

Looking at your table structure it seems you will end up with more cells in a row than the table defined column headers.

Do you need those columns to be filtered or ordered by the table rows?

If not, try just outputting to each cell:

<td> 
  <span v-for="Book in Books.filter((Book) => Stock.book_id === Book.id)"
    :key="Book.id" style="margin-right: 0.5em">
    {{ Book.name }}
  </span>
</td>
<td> 
  <span v-for="sh in Shells.filter((sh)=>Stock.shell_id === sh.id)"
    :key="sh.id" style="margin-right: 0.5em">
    {{ sh.name }}
  </span>
</td>
<td> 
  <span v-for="prbo in Purchased.filter((prbo)=>Stock.purchase_id === prbo.id)"
    :key="prbo.id" style="margin-right: 0.5em">
    {{ prbo.name }}
  </span>
</td>

Or simple concatenating:

<td> 
  {{ Books.filter((Book) => Stock.book_id === Book.id).map((Book) => Book.name).join(', ') || 'no books' }}
</td>
<td> 
  {{ Shells.filter((sh)=>Stock.shell_id === sh.id).map((Stock) => Stock.name).join(', ') || 'no shells' }}
</td>
<td> 
  {{ Purchased.filter((prbo)=>Stock.purchase_id === prbo.id).map((prbo) => prbo.name).join(', ') || 'no purchases' }}
</td>
Activity icon

Replied to Laravel Mix Is Not Complying Font Awesome Properly

Does removing (or commenting) this line:

$fa-font-path: "../webfonts";

change the situation?

Also can you open your generated css, must be in './public/css/app.scss, search for any @font-face` and post that rule here?

Activity icon

Replied to 'v-for' With 'v-if' Vuejs/laravel

You're welcome =) Glad to help

Activity icon

Replied to Relationship Condition In Model

Give this a try:

public function supervisor(){
    return $this->hasOne('App\EmployeeToSupervisor','emp_id','emp_id')
        ->whereExists(function ($query) {
            $query->selectRaw(1)
                ->from('pipdetails')
                ->whereColumn('pipdetails.emp_id', 'employee_to_supervisor.emp_id')
                ->whereRaw('pipdetails.pipdateofissue BETWEEN employee_to_supervisor.from_date AND employee_to_supervisor.to_date');
        });
}