selmonal

Experience

46,610

3 Best Reply Awards

  • Member Since 4 Years Ago
  • 503 Lessons Completed
  • 16 Favorites

22nd April, 2018

selmonal left a reply on Development Setup • 3 months ago

linux, valet, sublime text sometimes phpstorm

31st October, 2017

selmonal left a reply on Set A Many To Many Relationship With Duplicate Values • 9 months ago

Maybe you can create a extra model like AandB.

18th July, 2017

selmonal left a reply on How To Integrate Vuejs With Barryvdh/laravel-dompdf • 1 year ago

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

selmonal left a reply on How To Integrate Vuejs With Barryvdh/laravel-dompdf • 1 year ago

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

selmonal left a reply on Method Paginate Does Not Exist • 1 year ago

What is listings? is it relation?

2nd April, 2017

selmonal left a reply on Need Help For Naming Eloquent Relations • 1 year ago

organizingEvents, participatingEvents

5th February, 2017

selmonal started a new conversation Forum Summery • 1 year ago

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 ?

12th December, 2016

selmonal left a reply on Can't Use Bulma.css Responsiveness • 1 year ago

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

+mobile +tablet etc ...

11th December, 2016

selmonal left a reply on Can't Use Bulma.css Responsiveness • 1 year ago

Yeap

10th December, 2016

selmonal started a new conversation Can't Use Bulma.css Responsiveness • 1 year ago

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?

26th August, 2016

selmonal left a reply on Make A BelongsToMany Relation With Unexpected Model? • 1 year ago

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? • 1 year ago

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? • 1 year ago

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

25th August, 2016

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? • 1 year ago

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? • 1 year ago

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

24th August, 2016

selmonal started a new conversation Mailable Builds Message From SimpleMessage? • 1 year ago

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

23rd August, 2016

selmonal left a reply on Test Permissions? • 1 year ago

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? • 1 year ago

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?

16th August, 2016

selmonal left a reply on Retrieving Data Involving A Pivot Table • 2 years ago

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 • 2 years ago

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 • 2 years ago

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>

11th August, 2016

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

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

9th August, 2016

selmonal left a reply on Form With Delete Button Vs Span Element • 2 years ago

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 • 2 years ago

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>

8th August, 2016

selmonal left a reply on Only CRUD....always Best? • 2 years ago

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

selmonal left a reply on MacBook For Low Budget Dev • 2 years ago

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? • 2 years ago

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

selmonal left a reply on Can't Mock My Repository In Acceptance Test! • 2 years ago

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! • 2 years ago

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! • 2 years ago

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('/');
    }
}

2nd August, 2016

selmonal left a reply on Where Are You All From? • 2 years ago

Ulaanbaatar, Mongolia

selmonal left a reply on Date Field Shown As -0001-11-30 00:00:00 • 2 years ago

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

1st August, 2016

selmonal left a reply on Problem With AssertRedirectedToRoute() • 2 years ago

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

31st July, 2016

selmonal left a reply on Requiring The Same Component More Than Once • 2 years ago

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?

27th July, 2016

selmonal left a reply on Attach Uploaded Image To A User • 2 years ago

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 • 2 years ago

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

26th July, 2016

selmonal left a reply on Laravel Task Scheduling From Database • 2 years ago

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 • 2 years ago

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 • 2 years ago

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 Form Containing Php Captcha Validation In Laravel • 2 years ago

You should mock Session facade

selmonal left a reply on How To Test If Relationship Has Successfully Created? • 2 years ago

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? • 2 years ago

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

21st June, 2016

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

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

15th December, 2015

selmonal left a reply on Artisan Migrate:refesh Not Working On Homestead... • 2 years ago

Both of them are fine

selmonal left a reply on Artisan Migrate:refesh Not Working On Homestead... • 2 years ago

You should run composer dump-autoload.

3rd December, 2015

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

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!

Edit Your Profile
Update

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