selmonal

selmonal

Ulaanbaatar

Member Since 4 Years Ago

Experience Points 49,120
Experience
Level
Lessons Completed 527
Lessons
Completed
Best Reply Awards 3
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.

07 Nov
1 month ago

selmonal left a reply on How To Autologin Wordpress From Laravel, When User Log Into Laravel Application

Have you found a solution for it? I have a same problem too.

22 Apr
7 months ago

selmonal left a reply on Development Setup

linux, valet, sublime text sometimes phpstorm

31 Oct
1 year ago

selmonal left a reply on Set A Many To Many Relationship With Duplicate Values

Maybe you can create a extra model like AandB.

18 Jul
1 year ago

selmonal left a reply on How To Integrate Vuejs With Barryvdh/laravel-dompdf

I don't know. Just use blade or browser printing.

selmonal left a reply on How To Integrate Vuejs With Barryvdh/laravel-dompdf

Dompdf don't run your javsacript. Then it is impossible.

selmonal left a reply on Method Paginate Does Not Exist

What is listings? is it relation?

02 Apr
1 year ago

selmonal left a reply on Need Help For Naming Eloquent Relations

organizingEvents, participatingEvents

05 Feb
1 year ago

selmonal started a new conversation Forum Summery

I wish laracasts has forum summery notification feature like vuejs forum. That allows us to know what happened a day. Popular, Solved, Unsolved, Most favorited discussions etc ...

Do you have a plan for that @JeffreyWay ?

12 Dec
1 year ago

selmonal left a reply on Can't Use Bulma.css Responsiveness

I'm just trying to use bulma's responsiveness mixins but i can't.

+mobile +tablet etc ...

11 Dec
2 years ago
10 Dec
2 years ago

selmonal started a new conversation Can't Use Bulma.css Responsiveness

I have a code like below.

.post-title {
    text-align: left;

    +mobile {
        text-align: center;
    }
}

but it is not working. Does anyone know what the problem is?

26 Aug
2 years ago

selmonal left a reply on Make A BelongsToMany Relation With Unexpected Model?

I just want to fetch who should pay this fee?. I know there is a that relation. I don't want to access students through a batch.

The relation that i'm saying can do below!

$fees = Fee::latest()->withCount('students')->get(); // Very convenient, isn't it?

selmonal left a reply on Make A BelongsToMany Relation With Unexpected Model?

I don't agree with you @Hesto. I already followed that convention If you see the relation of batches and students.

Adding third model like Fee is very convenient to me. I can eager load, withCount('students') and other stuffs.

selmonal started a new conversation BelongsToMany Relation With Unexpected Model?

Can i make this relation? I have tables like below

students
    id
batches
    id
enrollments
    student_id
    batch_id
fees
    id
    batch_id

batches and students are have a belongsToMany relation ship. Now i want to make a relation fees with students? How can i make it? I've tested below but it doesn't work

public function students()
{
    return $this->belongsToMany(Student::class, 'enrollments', 'batch_id', 'student_id');
}

it running this query.

select `students`.*, `enrollments`.`batch_id` as `pivot_batch_id`, `enrollments`.`student_id` as `pivot_student_id` from `students` inner join `enrollments` on `students`.`id` = `enrollments`.`student_id` where `enrollments`.`batch_id` = '1' and `confirmed_at` is not null

Is it possible? or am i doing wrong? Thanks

25 Aug
2 years ago

selmonal left a reply on How Would You Refactor Multiple Catch Blocks For A Single Try Block When You Have To Catch Multiple Possible Exceptions?

I think catching the base exception is a strange idea, what would happen if unexpected exceptions has threw like SqlException or ValidationException etc ... That are handled by system handler.

selmonal left a reply on How Would You Refactor Multiple Catch Blocks For A Single Try Block When You Have To Catch Multiple Possible Exceptions?

You can write a handler class for that. See below

class ExampleJobExceptionHandler
{
    $expectedExceptions = [
        ClientException::class,
        RequestException::class,
        ConnectException::class,
        ServerException::class,
        Exception::class
    ];

    protected $exception;

    public function __construct(Exception $exception)
    {
        $this->exception = $exception;
    }

    public function handle()
    {
        if ($this->expected()) {

            $this->status('failed', $this->exception->getMessage())

            return redirect()->back();

        }

        throw new $this->exception;
    }

    public function expected()
    {
        return in_array($this->type(), $this->expectedExceptions);
    }

    public function type()
    {
        return get_class($this->exception);
    }
}

and use it on your controller like this.

try {
    dispatch(new ExampleJob())
} catch (Exception $exception) {
    return (new ExampleJobExceptionHandler($exception))->handle()
}
24 Aug
2 years ago

selmonal started a new conversation Mailable Builds Message From SimpleMessage?

Can i build a message for a Mailable using SimpleMessage? Like below, is it possible?

class Welcome extends Mailable
{
    /**
     * Build the message.
     *
     * @return $this
     */
    public function build()
    {
        return (new MailMessage)
                    ->subject('Welcome!') ->line('The introduction to the notification.')
                    ->line('Thank you for using our application!')
                    ->view();
    }
}
23 Aug
2 years ago

selmonal left a reply on Test Permissions?

Thank you! @bobbybouwmann. Do you have an example? I still don't get that.

Including permissions in my tests it doubles my test code. like: if the user is admin, go next or teacher stop the operation. Testing all those cases require so many tests. How can i avoid it?

selmonal started a new conversation Test Permissions?

I define my route with permission a middleware like

Route::group(['middleware' => 'permission:manage_students'], function () {
    Route::resource('students', 'StudentsController');

    Route::put('students/{student}/password', '[email protected]');
});

How can i test it in unit test if routes requires correct permission? Please help me?

16 Aug
2 years ago

selmonal left a reply on Retrieving Data Involving A Pivot Table

I think you should fetch from treatments. like this

$treatments = Treatment::where('status', 1)->with('magic')->get()->groupBy('magic_id');

dd($treatments);

selmonal left a reply on [Tip] My Favorite Dark Sublime Text 3 Theme

Mine is [[https://s4.postimg.org/qwl9jyoa5/My_Sublime.png|alt=Selmonal]]

{
    "always_show_minimap_viewport": true,
    "color_scheme": "Packages/colour-schemes/Espresso Soda.tmTheme",
    "font_size": 14,
    "line_numbers": false,
    "line_padding_bottom": 8,
    "line_padding_top": 8,
    "margin": 0,
    "soda_folder_icons": false,
    "theme": "Lanzhou.sublime-theme"
}

selmonal left a reply on Retrieving Data Involving A Pivot Table

No need to group just loop through hospitals.

<ul class="list-unstyled">
    @foreach(Hospital::with('treatments')->get() as $hospital)
        <li>
            <h4>{{ $hospital->name }}</h4>
            <ul class="list-unstyled treatments-group">
                @foreach($hospital->treatments as $treatment)
                    <li>
                        <a href="#">
                            <h5>
                                <i class="fa fa-file-text-o"></i>
                                {{ $treatment->name }}
                            </h5>
                            <p>{{ $treatment->friendly_name }}</p>
                        </a>
                    </li>
                @endforeach
            </ul>
        </li>
    @endforeach
</ul>
11 Aug
2 years ago

selmonal left a reply on Best Way To Schedule Task As Per User's Timezone

select * from users where HOUR(DATE_ADD(UTC_TIMESTAMP, INTERVAL -3 HOUR)) = 8

I think it will solve your problem. -3 is your user's timezone. 8 is the schedule hour.

or add user's timezone column

select * from users where HOUR(DATE_ADD(UTC_TIMESTAMP, INTERVAL users.timezone HOUR)) = 8
09 Aug
2 years ago

selmonal left a reply on Form With Delete Button Vs Span Element

Yeah @ohffs right, i think, deletion of most important data should have a specific deletion page. /warning, side effects etc.../

selmonal left a reply on Form With Delete Button Vs Span Element

I've created a directive for that. It is very convenient to use.

Here is the directive:

import swal from 'sweetalert';

module.exports = {
    isLiteral: true,

    bind: function () {
        var _this = this;

        this.el.addEventListener('click', function (e) {
            e.preventDefault();
            
            swal({
                title: "Are you sure?",
                text: "You're deleting a data!",
                type: "warning",
                showCancelButton: true,
                confirmButtonColor: "#DD6B55",
                confirmButtonText: "Yes, Go",
                cancelButtonText: "Cancel",
                closeOnConfirm: false 
            }, function () {
                $('<form method="POST" action="'+ _this.expression +'"><input type="hidden" name="_method" value="DELETE" /><input type="hidden" name="_token" value="'+ App.csrfToken +'" /></form>')
                    .submit();
            });

        }.bind(this));
    }
}

And use it on your view like this

<a v-safe-delete="{{ url()->route('route-to-destroy') }}" class="btn btn-danger">Delete</a>
08 Aug
2 years ago

selmonal left a reply on Only CRUD....always Best?

I would create [email protected][create, store, send, accept, decline].

selmonal left a reply on MacBook For Low Budget Dev

I've been using Macbook air 13 for 2 years for laravel projects development. There is no problem here. But you can't use it for graphical gaming like dota2 it's gonna be very hot. Otherwise it's very convenient to carrying.

selmonal started a new conversation How Can I Use Scheduler (cron) As A Queue Driver?

Is it possible? or is there any driver for this?

selmonal left a reply on Can't Mock My Repository In Acceptance Test!

i've already tested that method at the unit test level. If i choose to hit the database then i should provide 10300 students. It slows down my tests.

selmonal left a reply on Can't Mock My Repository In Acceptance Test!

Sorry it was completely my bad. I forgot to sign in an employee.

selmonal started a new conversation Can't Mock My Repository In Acceptance Test!

Please see the code below. The getUnconfirmedStudentsCount mocked method doesn't call. My tests are fail.

<?php

use Mockery as m;
use App\Models\Student;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Illuminate\Foundation\Testing\WithoutMiddleware;

class DashboardStatsTest extends TestCase
{
    use DatabaseTransactions;

    /** @test */
    public function an_employee_sees_the_count_of_unconfirmed_students_count()
    {
        $this->instance(
            'App\Contracts\Repositories\StudentRepository', 
            $studentRepository = m::mock('App\Contracts\Repositories\StudentRepository')
        );

        $studentRepository->shouldReceive('getUnconfirmedStudentsCount')->once()->andReturn(10300);

        $this->visit('/');
    }
}
02 Aug
2 years ago

selmonal left a reply on Where Are You All From?

Ulaanbaatar, Mongolia

selmonal left a reply on Date Field Shown As -0001-11-30 00:00:00

I think you should set the date column to be nullable! Then it will be fine.

01 Aug
2 years ago

selmonal left a reply on Problem With AssertRedirectedToRoute()

How do you define routes? school.{school}.teacher.index i don't think its a route.

Check your routes with following command:

php artisan route:list

see the Name column

31 Jul
2 years ago

selmonal left a reply on Requiring The Same Component More Than Once

You can check it by yourself. Require a dependency for 2 times then compile it. After that check your compiled js, Is that the dependency js doubled?

27 Jul
2 years ago

selmonal left a reply on Attach Uploaded Image To A User

Sorry. I was too lazy

First one should be in your [email protected]

public function updateProfileImage(User $user, Request $request)
{
    // Validate the uploading image here.
    
    $user->uploadNewProfileImage($request->file('image'));

    // Return a redirector, fire events or do something here.
}

Last one should be in your User model.

const PROFILE_IMAGES_DIR = 'profile_images';

public function profileImages() 
{
    return $this->hasMany('App\ProfileImage', 'id');
}

public function uploadNewProfileImage(UploadedFile $file)
{
    $name = time() . $file->getClientOriginalName();
    
    $file->move(self::PROFILE_IMAGES_DIR, $name);

    $this->profile_image_path = self::PROFILE_IMAGES_DIR . '/' . $name;

    $this->save();

    $this->profileImages()->save(new ProfileImage(['path' => $this->profile_image_path]));
}

Use your profile image like this:

<img src="{{ asset($user->profile_image_path) }} />

Or display all of your profile images

@foreach($user->profileImages as $image)
    <img src="{{ asset($image->path) }} />
@endforeach 

selmonal left a reply on Attach Uploaded Image To A User

$this->user->uploadProfileImage($request->file('image'));
public function uploadProfileImage(UploadedFile $file)
{
    $name = time() . $file->getClientOriginalName();
    
    $file->move(self::PROFILE_IMAGES_DIR, $name);

    $this->profile_image = self::PROFILE_IMAGES_DIR . '/' . $name;

    return $this;
}
26 Jul
2 years ago

selmonal left a reply on Laravel Task Scheduling From Database

If i understand your problem correctly, Try this:

protected function schedule(Schedule $schedule)
{
    $schedule->call(function () {
        
        $schedules = UserFetchSchedule::whereRaw('DATE_ADD(last_fetched_at, INTERVAL waiting_minutes MINUTE) < now()')->get();
        
        foreach($schedules as $schedule) {
            // Do your api stuffs here.
        }
    })->daily();
}

selmonal left a reply on Read-only Filter With V-model

I think you should do like this:

<input type="number" v-model="quantity"  />

or present only

<input type="number" value="{{ quantity | currency }}" />

selmonal left a reply on Laravel Task Scheduling From Database

Does your client call your api every specific minutes right? I don't thinks its no need to use schedule service. I thinks, It's just be a simple javascript loop with setTimeout().

selmonal left a reply on How To Test If Relationship Has Successfully Created?

I would do like this:

/** @test */
public function a_teacher_can_teach_for_multiple_schools()
{
    $teacher = factory(Teacher::class)->create();
    $school1 = factory(School::class)->create();
    $school2 = factory(School::class)->create();

    $school1->addTeacher($teacher);
    $school2->addTeacher($teacher);

    $this->assertCount(2, $teacher->schools);
    $this->assertTrue($teacher->teachesFor($school1));
    $this->assertTrue($teacher->teachesFor($school2));
}

selmonal left a reply on How To Test If Relationship Has Successfully Created?

I would do like this:

/** @test */
    public function a_teacher_can_teach_for_multiple_schools()
    {
        $teacher = factory(Teacher::class)->create();
        $school1 = factory(School::class)->create();
        $school2 = factory(School::class)->create();

        $school1->addTeacher($teacher);
        $school2->addTeacher($teacher);

        $this->assertCount(2, $teacher->schools);
        $this->assertContains($school1->id, $teacher->schools->pluck('id'));
        $this->assertContains($school2->id, $teacher->schools->pluck('id'));
    }
21 Jun
2 years ago

selmonal left a reply on [L5.1] Route-Model Binding For A Nested Resource?

I think it can be a middleware. CheckBarIsInBar, CheckArticleIsPostedByUser ...

    public function handle($request, Closure $next)
    {
        if(! $request->route()->getParameter('article')->isPostedBy($request->route()->getParameter('user')) {
            return abort(404, 'Article was not found');
        }
        
        return $next($request);
    }
15 Dec
2 years ago

selmonal left a reply on Artisan Migrate:refesh Not Working On Homestead...

You should run composer dump-autoload.

03 Dec
3 years ago

selmonal started a new conversation Is This Right Way Of Using Command Bus With Database Transaction

I've been using extended version of Laravel Dispatcher class. That overrides dispatchNow method it provides a database transasction if the command implements ShouldUseDatabaseTransactionInterface.

Please see the code below.

Command should implement this interface:

interface ShouldUseDatabaseTransaction
{
}

Here is the Dispatcher class.

class Dispatcher extends LaravelDispatcher
{
    /**
     * @param mixed $command
     * @param Closure|null $afterResolving
     * @return mixed
     */
    public function dispatchNow($command, Closure $afterResolving = null)
    {
        if(! $this->commandShouldUseDatabaseTransaction($command)) {
            return parent::dispatchNow($command, $afterResolving);
        }

        return DB::transaction(function() use($command, $afterResolving) {
            return parent::dispatchNow($command, $afterResolving);
        });
    }

    /**
     * @param $command
     * @return bool
     */
    private function commandShouldUseDatabaseTransaction($command)
    {
        return ($command instanceof ShouldUseDatabaseTransaction);
    }
}

It works fine for me but Is this right way of doing it? If it is not what is the best and short way? please help me!