selmonal

selmonal

Member Since 5 Years Ago

Ulaanbaatar

Experience Points 56,730
Experience Level 12

3,270 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 602
Lessons
Completed
Best Reply Awards 3
Best Reply
Awards
  • start-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-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-token Created with Sketch.

    Subscriber

    Earned if you are a paying Laracasts subscriber.

  • lifer-token Created with Sketch.

    Lifer

    Earned if you have a lifetime subscription to Laracasts.

  • lara-evanghelist 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.

18 Aug
3 days ago

selmonal commented on One-to-Many

Yeah I think so

07 Nov
9 months 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
1 year 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
2 years ago

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

I don't know. I's better to use blade or browser printing.

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

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

selmonal left a reply on Method Paginate Does Not Exist

What is listings? is it a relation?

If it is. Try it $category->listings()->where('published', '=', 2)->paginate(20);

02 Apr
2 years ago

selmonal left a reply on Need Help For Naming Eloquent Relations

organizingEvents, participatingEvents

05 Feb
2 years 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
2 years ago

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

@jlrdw I'm just trying to use bulma's responsiveness mixins but i can't. Search on google did not found.

+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 Third Model?

@hesto 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 Third 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 it's very convenient to me. It'll allow me I can eager load, use withCount('students') and other stuffs.

selmonal started a new conversation Make A BelongsToMany Relation With Third Model?

How 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's running this query.

select *, (select count(*) from `students` inner join `enrollments` on `students`.`id` = `enrollments`.`student_id` where `enrollments`.`batch_id` = `fees`.`id` and `confirmed_at` is not null) as `students_count` from `fees` limit 1

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

as i see enrollments.batch_id matches with fees.id. It should matches with fees.batch_id as i expect.

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
    ];

    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; // rethrow for unexpected exceptions
    }

    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 Can I Build A Message For A Mailable Using SimpleMessage Instead Creating A View? [laravel53]

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 testing code. like: if the user is admin, go next or if it is teacher or something 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 routes with a permission middleware like

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

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

Route::group(['middleware' => 'permission:manage_courses'], function () {
    //
});

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

16 Aug
3 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 Retrieving Data Involving A Pivot Table

No need to group, just loop through the 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
3 years ago

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

@concentrico Your can select users by their current hour.

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
3 years ago

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

I've created a directive for that. It is very easy to use. If the delete button was clicked it's gonna ask confirmation then submit a delete form with csrf token.

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));
    }
}

----------

Vue.directive('safe-delete', require('path-to-directive'));

And use it wherever you want like this

<a v-safe-delete="{{ url()->route('route-to-destroy') }}" class="btn btn-danger">Delete</a>
08 Aug
3 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 2013 for 2 years for laravel projects development /valet, homestead, gulp tasks, mysql, phpstorm, sublime text 3 etc/. 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!

Thanks!

i really agree with you guys. But i've already tested that method at the unit test level. I thought, If i choose to hit the database then i should provide 10300 or more students. It slows down my tests.

Refactored version:

/** @test */
public function an_employee_sees_the_count_of_unconfirmed_students()
{
    $this->mock('App\Contracts\Repositories\StudentRepository')
        ->shouldReceive('countUnconfirmed')
        ->once()
        ->andReturn(10300);

    $this->actingAsEmployee()
        ->visit('/')
        ->see('Unconfirmed Students')
        ->see(10300);
}

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

Problem solved. 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()
    {
        $this->instance(
            'App\Contracts\Repositories\StudentRepository', 
            $studentRepository = m::mock('App\Contracts\Repositories\StudentRepository')
        );

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

        $this->visit('/')->see(10300);
    }
}
02 Aug
3 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
3 years ago

selmonal left a reply on Problem With AssertRedirectedToRoute()

How do you define routes? school.{school}.teacher.index i don't think its the route. Maybe it is school.teacher.index

Check your routes with following command:

php artisan route:list

see the Name column

31 Jul
3 years ago

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

I think 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
3 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(Request $request)
{
    // Validate the uploading image here.
    
    $this->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]));
}

Notice that the profileImages relation should be hasMant. Because the user has many old profile images.

Use your profile image in your view 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 

I hope you get my idea!

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
3 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 wait_minutes MINUTE) > now()')->get();
        
        foreach($schedules as $schedule) {
            // Do your api stuffs here.
        }
    })->everyMinutes();
}

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 think its no need to use laravel schedule service. I think 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));
}

And teachesFor methods would be

public function teachesFor(School $school)
{
    if ($this->relationLoaded('schools')) {
        return $this->schools->contains($school);
    }

    return $this->schools()
        ->wherePivot('school_id', $school->id)
        ->exists();
}

And i think you no need to test the delete operation that using SoftDeletes. That already tested by the core developers.

21 Jun
3 years ago

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

I think it can be a simple middleware like below. Example: CheckBarIsInFoo, 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
3 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 A Right Way Of Using The Command Bus With A 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 ShouldUseDatabaseTransaction.

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!