ahmeddabak

ahmeddabak

CTO & Senior web applications developer at Meier AG

Member Since 3 Years Ago

Wesel

Experience Points
197,290
Total
Experience

2,710 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
1355
Lessons
Completed
Best Reply Awards
98
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 40
197,290 XP
Apr
06
1 day ago
Activity icon

Replied to Error Accessing (distant) BelongsToMany Relationship

You do not have a foreign key user_id in you departments table

Activity icon

Replied to Error Accessing (distant) BelongsToMany Relationship

Auth::user()->projects please read my previous replay, when a relation is called as a property it returns a collection

Activity icon

Replied to Error Accessing (distant) BelongsToMany Relationship

You need to define the hasManyThrough relation

public function projects() {
	return $this->hasManyThrough('App\Project', 'App\Department');
}

for more info read the laravel docs: Has Many Through

Activity icon

Replied to Ionrangeslider Is Not Displaying

make sure you are requiring require("ion-rangeslider"); before calling it. you can also try assigning the library to a global variable

window.ionRangeSlider = require("ion-rangeslider");

also make sure you are compiling the code and using the result js file.

Activity icon

Replied to Error Accessing (distant) BelongsToMany Relationship

First there is a diffirence between calling the relation like a method, or like a property.

when called as a method Auth::user()->departments() you get the relation it self, which in this case is a BelongsToMany relation. that allows you to extends the query or create new records

Auth::user()->departments()->create([
	//
]);

but when called as a property Auth::user()->departments you get the result of the relation, which in this case is a collection of many departments it is equivalent to Auth::user()->departments()->get().

now to resolve the error, you need to know that the projects relation is not on the collection of many items returned by departments but it is on the models inside of it.

so you can do the following on User you can use the hasManyThrough relation which let you query the projects directly from the user model

Auth::user()->projects

or you get the departments and for each of them you get the projects, which will result to a collection of collections.

Auth::user()->departments->map->projects
Apr
05
2 days ago
Activity icon

Awarded Best Reply on Only Display Data In Views If It Exists

Since it is a table you must echo the last column even if it was empty, you can use the optional helper to avoid throwing an error when updated by is not set.

 @foreach($tasks as $task)
            <tr>
                <td>{{$task->id}}</td>
                <td>{{$task->title}}</td>
                <td>{{$task->description}}</td>
                <td>{{$task->created_at}}</td>
           	<td>{{$task->createdBy->name}}</td>
                <td>{{optional($task->updatedBy)->name}}</td>
	</tr>
@endforeach
Activity icon

Replied to Array_key_exists(): Using Array_key_exists() On Objects Is Deprecated In Laravel 6 With PHP 7.4

The error is clear. in this file headerTwo.blade.php you are using array_key_exists() to check if an object has a specific property. which is now deprecated. so you instead use isset like this isset($object->property) of using property_exists like this property_exists($object,'property')

Activity icon

Replied to Only Display Data In Views If It Exists

Since it is a table you must echo the last column even if it was empty, you can use the optional helper to avoid throwing an error when updated by is not set.

 @foreach($tasks as $task)
            <tr>
                <td>{{$task->id}}</td>
                <td>{{$task->title}}</td>
                <td>{{$task->description}}</td>
                <td>{{$task->created_at}}</td>
           	<td>{{$task->createdBy->name}}</td>
                <td>{{optional($task->updatedBy)->name}}</td>
	</tr>
@endforeach
Mar
16
3 weeks ago
Activity icon

Replied to ERROR 404

can you please provide more info about the error, also please share any relevant code

Mar
13
3 weeks ago
Activity icon

Replied to Nested Categories, How To Fetch A Full Branch?

i have updated the code

Mar
12
3 weeks ago
Activity icon

Replied to How I Can Search Inside Multiple Websites

After scrapping the page, you can search the html for the words you need to find.

Activity icon

Replied to How I Can Search Inside Multiple Websites

it is not an easy task, but to know more you can learn about 'crawlers', there is a good one from spatie

Activity icon

Replied to Nested Categories, How To Fetch A Full Branch?

Yes, it is a little bit tricky but not that hard.

class Category extends Model
{
    public function categories()
    {
        return $this->hasMany(static::class, 'parent_id');
    }

    public function nestedCategories()
    {
        return $this->categories()->with('nestedCategories');
    }


    /**
     * Return a collection with all the nested categories
     *
     * @return \Illuminate\Support\Collection
     */
    public function categoryTree()
    {
        return $this->getNestedCategories($this);
    }

    /**
     * Internal recursive call function
     *
     * @param $category
     * @return \Illuminate\Support\Collection
     */
    private function getNestedCategories($category)
    {
        $tree = collect([]);

        foreach ($category->nestedCategories as $category) {
            $tree->push($category);

            $sub_tree = $category->getNestedCategories($category);
            if ($sub_tree->isNotEmpty()) {
                $tree->push($sub_tree);
            }
        }

        return $tree;
    }

}

so now you can call the following code, it lets you get all ids for the category with id 1 and all sub categories, and using the nested relation, you would do one or two queries for the whole branch


$ids = Category::with('nestedCategories')->where('id',1)->get()->categoryTree()->flatten()->pluck('id');
Activity icon

Replied to WhereRaw Doesnt Respect To The Global Scope

Your are right, this subject was discussed on stackoverflow, here is the little hack they used to fix it

Mar
05
1 month ago
Activity icon

Awarded Best Reply on Date Interval Between Using Where

You are checking if the start_date bigger then both dateInStart and dateInStart

and the end_date smaller then both dateInStart and dateInEnd

are you sure this is what you want?

Feb
26
1 month ago
Activity icon

Awarded Best Reply on Laravel Eloquent Conditional BelongsTo Relationship

the foreign key customer_id on the users table an be null, when a user selects a customer, then you change the value to the customer->id, if the user changed the customer again you just need to update the customer_id to the new customer->id

Feb
22
1 month ago
Activity icon

Awarded Best Reply on Create Fake Pdf Or Image In Laravel Seeder At The Time Of Migration And Store The Record In Database

$file = \Illuminate\Http\UploadedFile::fake()->create('test.pdf')->store('pdfs')
Activity icon

Replied to MS SQL Error When Running A Laravel Seeder

runphp artisan db:seed -v and post the full stack

Activity icon

Replied to Using Vue In Laravel - Router Or Not When Passing Ids?

Since it is not an spa, i would let laravel do the work of passing the data to the view and handling the logic

Feb
17
1 month ago
Activity icon

Replied to Phpunit THE ERROR HANDLER HAS CHANGED!

if you have phpunit globally installed just run phpunit --self-update on linux or mac or vendor\bin\phpunit --self-update on windows. it should Update PHPUnit to the latest version.

otherwise try to upgrade it using composer.

Activity icon

Replied to If I Leave Login Page Opened, Notify Token Expired

The easiest solution would be to update the page in order to refresh the token. but the csrf token is used on multiple pages, say for example you have a long form. and the user start filling it and you reload the page while the user is still working on it.

So you can either change the session lifetime in config/session.php, as the csrf token if not changed stay valid as long as the session is valid.

'lifetime' => //how long should the session be valid

or you can update it using an ajax call

//in your web.php
Route::get('update-csrf', function(){
    return csrf_token();
});
<meta name="csrf_token" content="{{ csrf_token() }}">
<script>
            function updateToken(){
                $.get('update-csrf').done(function(data){
                    $('[name="csrf_token"]').attr('content', data);
                });
            }

            setInterval(updateToken, 1000 * 60 * 5); 

</script>

Feb
13
1 month ago
Activity icon

Awarded Best Reply on Laravel Jquery Not Working

Check which errors you have in the developer tools

Feb
12
1 month ago
Activity icon

Replied to Get Posts With User, Where User

Try this

Post::with(['users'=> function($query) {
        $query->where('age','>', 18);
    }])->get();
Activity icon

Awarded Best Reply on Laravel TCP/IP Connections

@lukegalea16

https://github.com/ahmeddabak/laravel-tcp-sockets

So i just did what the article said, you can run it on your local machine

to start listening i created a console command php artisan test it will listen to any tcp connection on port 31337

from windows connect to the computer ip and port 31337 using a telnet client ex. MobaXterm usingth command telnet SERVER_IP 31337

The tcp socket will great you and ask you to enter a string, when you hit enter the server will show you the string reversed and ask you for a new one. it is a simple app but should help you understand tcp sockets.

Credit to Akram Wahid and his article PHP and Laravel Receiving GPS Tracker Data to Specific TCP/IP Port

Activity icon

Replied to Laravel TCP/IP Connections

Please mark this as solved

Feb
11
1 month ago
Activity icon

Replied to Laravel TCP/IP Connections

@lukegalea16

https://github.com/ahmeddabak/laravel-tcp-sockets

So i just did what the article said, you can run it on your local machine

to start listening i created a console command php artisan test it will listen to any tcp connection on port 31337

from windows connect to the computer ip and port 31337 using a telnet client ex. MobaXterm usingth command telnet SERVER_IP 31337

The tcp socket will great you and ask you to enter a string, when you hit enter the server will show you the string reversed and ask you for a new one. it is a simple app but should help you understand tcp sockets.

Credit to Akram Wahid and his article PHP and Laravel Receiving GPS Tracker Data to Specific TCP/IP Port

Activity icon

Replied to User Relationships With Different Results Based On User Role

Area::query() is not a relation, so you can not do relation stuff with it, there are many solutions

1- move the if statement to the controller and there you can create a new query or use the relation

2- if you think you will be needing this in many locations, just create a repository to get the data for you

Activity icon

Replied to How To Get Soft Deleted Records From Eager Loading And Lazy Eager Loading ?

Just add the withTrashed to your relation on the fly.

  $assetDetails = $assetDetails->with([
            'assetDocuments' => function ($query) {
                $query->withTrashed()->select('id', 'assetId', 'assetUsage', 'volume', 'amount', 'documentType', 'links', 'link', 'userId', 'uploadTime', 'expiryDate', 'coordinate')->orderBy('assetdocument.uploadTime', 'desc')->get();
            },
            'assetDocuments.userDetails:id,firstName,lastName,middleName',
        ]);
Activity icon

Replied to User And Profile - Different Tables And Relationship

use Polymorphic Relationships

create both StaffProfile and CustomerProfile models and in your users table add profile_type and profile_id

    $table->morphs('profile');

then in the User model add

public function profile()
    {
        return $this->morphTo();
    }
Activity icon

Awarded Best Reply on Filtering An Array Of Objects

filteredSubcategories: function() { 
    return this.subcategories.filter((item) => item.category_id == this.form.category_id);
}
Activity icon

Replied to Filtering An Array Of Objects

filteredSubcategories: function() { 
    return this.subcategories.filter((item) => item.category_id == this.form.category_id);
}
Activity icon

Replied to Prevent Going Back After Logout (based On Session)

If the problem is solved, please mark this as solved

Activity icon

Awarded Best Reply on Count Records By Field

Just use

Installation::select(DB::raw('COUNT(*) as count'), 'type')->groupBy('type')->pluck('count', 'type');

It should give the exact result you want.

Activity icon

Replied to Prevent Going Back After Logout (based On Session)

That is not a problem, it is only a cached version of the page in the browser. The user will be logged out and will not be able to do anything

Activity icon

Replied to Count Records By Field

Please mark this as solved

Activity icon

Replied to Count Records By Field

Just use

Installation::select(DB::raw('COUNT(*) as count'), 'type')->groupBy('type')->pluck('count', 'type');

It should give the exact result you want.

Activity icon

Replied to Prevent Going Back After Logout (based On Session)

The method is there, but it is hidden in a trait.

Just add the code i gave you to the LoginController

Activity icon

Replied to Prevent Going Back After Logout (based On Session)

In your App\Http\Controllers\Auth\LoginController you can override the logout method to prevent redirecting back, here you can send the user where ever you want

/**
     * Log the user out of the application.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function logout(Request $request)
    {
        $this->guard()->logout();

        $request->session()->invalidate();

        return $this->loggedOut($request) ?: redirect('/login'); //redirect to login
    }
Activity icon

Awarded Best Reply on How To Implement Search In Controller

department is a foreign key as shown in the model. It has department_id that is derived from OrgDepartment.

I do not know how your database or models are built, the code i submitted should give you an idea how to solve the problem. just change $employees->where('employees',$request->get('department')); to what ever works for you.

How do I display each of the search fields and the submit button in the view.

return view('hr.employees.index')->with([
    'employees' => $employees->paginate(6),
    'department' => $request->get('department'),
    'employee_code' => $request->get('employee_code')
]);

then in the view

<input type="text" name="department" value="{{old('department', isset($department) ? $department : null )}}" />
<input type="text" name="employee_code" value="{{old('employee_code', isset($employee_code) ? $employee_code : null )}}" />

Activity icon

Replied to How To Implement Search In Controller

 if($request->has('full_name')) {
        $employees->whereRaw("CONCAT(first_name, ' ', other_name, ' ', last_name) LIKE ?", ['%'.$request->get('full_name').'%']);
    }
Activity icon

Replied to TCPDF Password Protected Using Auth::user()->password

Auth::user()->password is encrypted, so you can not read the original password and therefore it can not be used to protected a pdf.

Activity icon

Awarded Best Reply on Return Redirect Specific Tab Not Working

<div class="tab-content">

    <div class="tab-pane{{old('tab') == 'kt_tabs_7_4' ? ' active' : null}}" id="kt_tabs_7_4" role="tabpanel">
        //
    </div>

    <div class="tab-pane{{old('tab') == 'kt_tabs_7_5' ? ' active' : null}}" id="kt_tabs_7_5" role="tabpanel">
        //
    </div>

    <div class="tab-pane{{old('tab') == 'kt_tabs_7_1' ? ' active' : null}}" id="kt_tabs_7_1" role="tabpanel">
        //
    </div>

</div>
Activity icon

Replied to Return Redirect Specific Tab Not Working

<div class="tab-content">

    <div class="tab-pane{{old('tab') == 'kt_tabs_7_4' ? ' active' : null}}" id="kt_tabs_7_4" role="tabpanel">
        //
    </div>

    <div class="tab-pane{{old('tab') == 'kt_tabs_7_5' ? ' active' : null}}" id="kt_tabs_7_5" role="tabpanel">
        //
    </div>

    <div class="tab-pane{{old('tab') == 'kt_tabs_7_1' ? ' active' : null}}" id="kt_tabs_7_1" role="tabpanel">
        //
    </div>

</div>
Activity icon

Replied to Method Not Recognized

Are you sure that both methods are in the right controller SingleproductController

Activity icon

Replied to How To Implement Search In Controller

department is a foreign key as shown in the model. It has department_id that is derived from OrgDepartment.

I do not know how your database or models are built, the code i submitted should give you an idea how to solve the problem. just change $employees->where('employees',$request->get('department')); to what ever works for you.

How do I display each of the search fields and the submit button in the view.

return view('hr.employees.index')->with([
    'employees' => $employees->paginate(6),
    'department' => $request->get('department'),
    'employee_code' => $request->get('employee_code')
]);

then in the view

<input type="text" name="department" value="{{old('department', isset($department) ? $department : null )}}" />
<input type="text" name="employee_code" value="{{old('employee_code', isset($employee_code) ? $employee_code : null )}}" />

Activity icon

Replied to Laravel TCP/IP Connections

I am happy to do a demo project tonight and upload it on git for you.

Activity icon

Replied to How To Implement Search In Controller

This code should do the trick, and only display to each user what he has the right to see.

class HrEmployeesController extends Controller
{
 public function index(Request $request)
 {
    $userCompany = Auth::user()->company_id;

    if (Auth::user()->hasRole('Super Admin')) {
        $employees = HrEmployee::query();
    } else {
        $employees = HrEmployee::where('company_id', $userCompany);
    }

    if($request->has('department')) {
        $employees->where('employees',$request->get('department '));
    }

    if($request->has('employee_code')) {
        $employees->where('employee_code',$request->get('employee_code '));
    }


    return view('hr.employees.index')->with('employees', $employees->paginate(6));
 }
}