omrakhurs

omrakhurs

Member Since 3 Years Ago

London, England

Experience Points 6,130
Experience Level 2

3,870 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 30
Lessons
Completed
Best Reply Awards 0
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]om 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.

13 Jun
2 years ago

omrakhurs started a new conversation How To Convert A Derived Table Query Into Eloquent Syntax?

How do I convert the following into Eloquent syntax? I know there is a derived table in there, so unsure what's the right syntax in Laravel for this?

    SELECT firstname
, CONCAT_WS
( ', '
, CASE WHEN years = 0 THEN NULL ELSE CONCAT(years,' years') END
, CASE WHEN months = 0 THEN NULL ELSE CONCAT(months, ' months') END
, CASE WHEN days = 0 THEN NULL ELSE CONCAT(days, ' days') END
) lengthOfService
FROM
( SELECT firstname
, FLOOR(DATEDIFF(CURDATE(),startdate)/365.2425) years
, FLOOR((DATEDIFF(CURDATE(),startdate)/365.2425 - FLOOR(DATEDIFF(CURDATE(),startdate)/365.2425))* 12) months
, CEILING((((DATEDIFF(CURDATE(),startdate)/365.2425 - FLOOR(DATEDIFF(CURDATE(),startdate)/365.2425))* 12)
- FLOOR((DATEDIFF(CURDATE(),startdate)/365.2425 - FLOOR(DATEDIFF(CURDATE(),startdate)/365.2425))* 12))* 30) days
FROM users
) x
02 Jun
2 years ago

omrakhurs left a reply on How To Make Two Inner Joins With A Count In Them?

This works, thank you! Could you please explain it?

omrakhurs started a new conversation How To Make Two Inner Joins With A Count In Them?

I have three tables:

  1. Users (id, dept_id)
  2. Departments (id, deptStringName)
  3. Absences (id, user_id)

I am trying to figure out Absences per Department. I know I need two inner joins, but at the moment I am confused about how to insert a count in two inner joins using the Laravel Query Builder syntax.

The eventual result could be like:

+-------+---+
| DeptA | 3 |
| DeptF | 7 |
| DeptH | 3 |
| DeptT | 7 |
| DeptZ | 5 |
+-------+---+
02 Mar
2 years ago

omrakhurs started a new conversation Integrating Moodle With Laravel

Has anyone here ever had experience integrating Moodle with their Laravel app? What steps did you take to integrate it and if you have any resource that I could read, please share. Thanks.

28 Feb
2 years ago

omrakhurs started a new conversation Laravel - Append Row Id To Form Name Attribute Inside Each Row Of A Dynamic Table

I send two variable to my view $abilities, and $users. $abilities is an array of key-value pairs containing data in the following format:

["1"=>"create_user","2"=>"delete_user","3"=>"ban_user"]

$users is an array in the following format:

["1"=>"John Doe","2"=>"Jane Doe"]

Both are taken from their respective databases abilities (columns: ID, name) and users (columns: ID, name).

In the view, I have a table which contains a multiple select for each row against the $user->id:

@foreach($users as $user)
<tr>
    <td>{{$user->id}}</td>
    <td>
       {{Form::select("takenabilities[]",$abilities, null, ['id'=>'system-abilities','multiple','class'=>'form-control' ])}}
   </td>
</tr>
@endforeach

Problem is that when I receive the request in my controller, I only see one takenabilities[] array, and I want to save data from each multiple select in each row generated dynamically

20 Feb
2 years ago

omrakhurs left a reply on How To Schedule A Yearly Cron Job For A Laravel App On Linux AMI?

@dtunes , how does adding nginx or www-data (or, /etc/crontab) change the access to app files? Asking as a newb here.

03 Feb
2 years ago

omrakhurs started a new conversation How To Pass Different Values For Pivot Data Table In Sync() Function

My form sends a $request->assets that I am able to sync using the following:

 $user->assets()->sync($request->assets === null ? [] : $syncData);

The problem arises when I try to retrieve values from a serial number array that is sent back as $request->serialnumber

I have set up the serial numbers in such a way that the serial number array index corresponds to my id column in the assets table. E.g. if Mobile has a value of 1 in the database, it is located in $request->serialnumber[1], and for something that would have an id of 2, would be placed in $request->serialnumber[2] and so on.

I have done the following so far, in order to insert the correct serial numbers for the correct asset() relationship:

$serialData = [];
$pivotData = [];
$syncData = [];
           
//for every assigned asset, build an array of their serial numbers from the serial number array...
if(isset($request->assets))
{
   for($i = 0; $i<count($request->assets);$i++)
      $serialData[$i] = $request->serialnumber[$i];
}

//if some serials were set, use them for pivot data
if(count($serialData)>0)
{
   $filledArray = array_fill_keys($serialData,"serialnumber");
   $pivotData = array_flip($filledArray);
}

$syncData = array_combine($request->assets, $pivotData);

I know its something wrong and was wondering if there's a correct way to do this kind of thing?

01 Feb
2 years ago

omrakhurs started a new conversation Best Way To Test For Variables That Are Not Set Or Set To Null?

I'm trying to learn what is a best one-size-fits-all way in Laravel to detect if something is a)set to null and/or b) not set. There's isset(), is_null(), and others. But I'm looking to see how other developers do it.

22 Jan
2 years ago

omrakhurs left a reply on How To Hide Model Id's From Showing In The Browser Address Bar

Yes, even that would be helpful, but I don't know how to do that. Could you please elaborate?

omrakhurs started a new conversation How To Hide Model Id's From Showing In The Browser Address Bar

Are there any helper functions that would not let the user see id in the address bar when viewing or editing details of a model?

E.g. if I try to edit the details of user with id 1, the address in the browser says: myapp.dev/users/1/edit

I'd rather it showed up as myapp.dev/users/edit

Any idea how to go about this?

16 Jan
2 years ago

omrakhurs left a reply on Possible To Have A HasMany As Well As A HasOne Relationship With The Same Model?

@harran, you are suggesting something that's ultimately going to lead to cascading problems.

omrakhurs started a new conversation Possible To Have A HasMany As Well As A HasOne Relationship With The Same Model?

I've got a Company model in which I would like to define two relationships with the User model:

  public function users(){
     return $this->hasMany('App\User');
  }

  public function administrator(){
     return $this->hasOne('App\User', 'superuserid');
  }

I have a superuserid field in my companies table in the database, which is a foreign key to the id of the users table.

I just want to know if this is at all a good strategy or even possible?

07 Jan
2 years ago

omrakhurs started a new conversation Please Explain These Eloquent Events (creating, Created, Etc.)

Hi I'm trying to understand the events like created, saving etc. as the docs tell on this page here: https://laravel.com/docs/5.3/eloquent#events

Could someone please explain them in easy terms and what they are for? Or perhaps post some resource which could explain what they do?

Thanks!

31 Dec
2 years ago

omrakhurs left a reply on How To Schedule A Yearly Cron Job For A Laravel App On Linux AMI?

On my dev machine, it works perfectly with the same exact code, but not on AWS, even though there is a crontab for the user when do crontab -e.

The log on my dev machine gives the expected information. I will use your recommendation and put it all into a table once I've managed to fix the issue.

omrakhurs started a new conversation How To Schedule A Yearly Cron Job For A Laravel App On Linux AMI?

I'm trying to set up a cron job for the 1st of January on my AWS EC2 instance for ec2-user. When I do crontab -u ec2-user -l, it shows the following output:

* * * * * usr/bin/php /var/www/html/artisan schedule:run >> /dev/null 2>&1

But even though the following was set up in Kernel.php, the job never fired:

protected $commands = [
    // Commands\Inspire::class,
    Commands\TestYearlyJob::class,
];

protected function schedule(Schedule $schedule)
{
    $schedule->command('table:test-yearly-job')->cron('0 0 1 1 *')
       ->timezone('Europe/London')
       ->appendOutputTo('../taskscheduler.log');
}

The command itself runs from Artisan (I've double checked), so its logic is fine.

I'm wondering if there is a way to do it with the ->yearly()->at() scheduling option? Or perhaps with a closure truth test? But I'm not sure what to put in there for a when() statement. Please help.

29 Dec
2 years ago

omrakhurs started a new conversation Which Is The Right Service In Laravel For Irregular Future Tasks Scheduling?

I would like to know if Laravel has something like the .NET Timer class? Something like a Profiler sounds good but I'm not sure if that's what I need. I have studied Scheduling within Laravel but it seems like there's a cyclic pattern that it allows (e.g. weekly, daily, hourly etc.- I don't want that).

I'll explain below what I'm trying to achieve, so please bear with me:

My app creates tasks for future dates. I would like to have the app remind me of uncompleted tasks a week in advance of their due date. These tasks could happen at any random interval, and have no set recurring pattern - basically I create them and a weekly, monthly etc. pattern doesn't follow here.

It's similar to yearly timers that reset state at the start of a the year. I've no experience building this in Laravel prior to this, so any help is appreciated.

22 Dec
2 years ago

omrakhurs left a reply on Form::model Binding Within Bootstrap Modal Binds Wrong Row Of The Table

Thank you @bobbybouwmann It works. In the meantime I also tried something with basic JQuery, but it also brought up the data when I clicked on the delete button.

  var table = $('#datatable-table').DataTable();

    $('#datatable-table tbody').on( 'click', 'button', function () {
        var data = table.row( $(this).parents('tr') ).data();
        alert( data[0] +" "+ data[ 1 ] + " "+data[2]);
    } );

Could you please explain how you managed to have the code tied to the Edit button only?

omrakhurs started a new conversation Form::model Binding Within Bootstrap Modal Binds Wrong Row Of The Table

I am making a CRUD to-do list. Clicking on Edit launches a modal. Once I edit and submit something within the modal, everything updates correctly, i.e. the update() method works fine. However, as $task stores the value of the last item in the array, it always shows the value of that item no matter which row's edit button I click on. Could someone tell me if there's a JQuery way to do it? I'm not so familiar with JQuery.

The to-do table:

<div id="tasks-chart">
            <table id="datatable-table" class="table table-striped table-hover">
                <thead>
                <tr>
                    <th>Task</th>
                    <th style="width: 40%">Description</th>
                    <th>Status</th>
                    <th>Actions</th>
                </tr>
                </thead>
                <tbody>
                @foreach($tasks as $task)
                    <tr id="task{{$task->id}}">
                        <td>{{$task->task}}</td>
                        <td style="width: 40%">{{$task->description}}</td>
                        <td>@if($task->done) Completed @else Incomplete @endif</td>
                        <td>
                            <button class="btn btn-warning btn-sm btn-detail open-modal" value="{{$task->id}}"
                                    data-toggle="modal"
                                    data-target="#myModal2"
                                    data-backdrop="static"
                                    data-task ="{{$task->task}}"
                                    data-description ="{{$task->description}}"
                                    data-done ="{{ $task->iscomplete }}">Edit</button>
                            <button class="btn btn-danger btn-sm btn-delete delete-task" value="{{$task->id}}">Delete</button>
                        </td>
                    </tr>
                @endforeach
                </tbody>
            </table>
        </div>

The Modal that is launched once the Edit button is clicked is also very simple:

<div id="myModal2" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true" style="display: none;">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header">
                        <button type="button" class="close" data-dismiss="modal" aria-hidden="true" aria-label="Close">×</button>
                        <h4 class="modal-title" id="myModalLabel2">Edit Task</h4>
                    </div>
                    <div class="modal-body">
                        {{ Form::model($task, ['method' => 'PATCH', 'route' => ['tasks.update', $task->id], 'role' => 'form']) }}
                        <fieldset>
                            <label for="edit-name" class="control-label col-sm-4">Task</label>
                            <div class="col-md-8">
                                {{Form::text('task',null,['id'=>'edit-name','class'=>'form-control col-sm-8','required'=>'required'])}}
                                <p class="error text-center alert alert-danger hidden"></p>
                            </div>
                        <br><br>
                            <label for="edit-description" class="control-label col-sm-4">Description</label>
                            <div class="col-sm-8">
                                {{Form::textarea('description',null,['id'=>'edit-description','class'=>'form-control','rows'=>'5','cols'=>'45'])}}
                            </div>
                        <br><br>
                            <label for="edit-status" class="control-label col-sm-4">Status</label>
                            <div id="edit-status" class="col-sm-8">
                                {{Form::select('done', ['0'=>'Incomplete','1'=>'Completed'],null,
                                ['id'=>'edit-status','class'=>'selectpicker', 'data-style'=>'btn-success', 'data-width'=>'auto'])}}
                            </div>
                        </fieldset>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                        {{ Form::submit('Submit', ['class' => 'btn btn-success']) }}
                    </div>
                    {{ Form::close() }}
                </div><!-- /.modal-content -->
            </div><!-- /.modal-dialog -->
        </div>

routes.php:

Route::resource('tasks','TaskController');

There's only one method implemented in Controller:

 public function update(Request $request, $id)
{
    $user = Auth::user();
    
    
    // validation of the request
    $rules = array(

        'task' => 'required|string',
        'description'=>'string'

    );
    $validator = Validator::make(Input::all(), $rules);

    // return to the creation page if the request is invalid
    if ($validator->fails()) {
        return Redirect::to('/')
            ->withErrors($validator)
            ->withInput();
    }
    else{
        $task                = Task::findOrFail($id);
      
        $task->task          = Input::get('task');
        if(Input::get('description'))
        {
            $task->description = Input::get('description');
        }
        $task->done          = Input::get('done');
        $task->save();

        \Session::flash('flash_message','Task succesfully updated!');
        // redirect
        return redirect('/');
    }
}
26 Oct
2 years ago

omrakhurs left a reply on Receiving SES 403 Error When Sending Mail From Laravel 5.2 App

@cuonghuynh , from within AWS, click on your account name on the top right corner, and go to Security Credentials. From there, go into Access Keys. It will allow you to create a new Access Key. Store that somewhere safe. Although I have since begun to access SES via my IAM roles, this worked for me initially. Using the Access Keys isn't a recommended way as they allow complete access to your AWS (much like a chmod 777 in Linux allows complete control over files).

25 Oct
2 years ago

omrakhurs started a new conversation Thybag/php-sharepoint-lists Error Undefined Constant SOAP_1_1 - Assumed 'SOAP_1_1'

I have the following in my controller to access my sharepoint online account. I have a list of documents on SharePoint and I would like to only read them. I am using the PHP-Sharepoint API from here.

$sp = new SharePointAPI('<my account>', '<password>', 'resources\Lists.asmx.xml','SPONLINE');

print_r($sp); 

Then I get the following error:

ErrorException in KnowledgeBase.php line 21:
Use of undefined constant SOAP_1_1 - assumed 'SOAP_1_1'
in KnowledgeBase.php line 21
at HandleExceptions->handleError('8', 'Use of undefined constant SOAP_1_1 - assumed 'SOAP_1_1'', '<path>\KnowledgeBase.php', '21', array('listName' => 'Knowledge Base Documents')) in KnowledgeBase.php line 21
at KnowledgeBase::getSharepointDocuments() in KnowledgeBaseController.php line 41
at KnowledgeBaseController->index()
at call_user_func_array(array(object(KnowledgeBaseController), 'index'), array()) in Controller.php line 80
at Controller->callAction('index', array()) in ControllerDispatcher.php line 146
at ControllerDispatcher->call(object(KnowledgeBaseController), object(Route), 'index') in ControllerDispatcher.php line 94
at ControllerDispatcher->Illuminate\Routing\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 52
at Pipeline->Illuminate\Routing\{closure}(object(Request)) in Authenticate.php line 28
at Authenticate->handle(object(Request), object(Closure))
at call_user_func_array(array(object(Authenticate), 'handle'), array(object(Request), object(Closure))) in Pipeline.php line 136
at Pipeline->Illuminate\Pipeline\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 32
at Pipeline->Illuminate\Routing\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 103
at Pipeline->then(object(Closure)) in ControllerDispatcher.php line 96
at ControllerDispatcher->callWithinStack(object(KnowledgeBaseController), object(Route), object(Request), 'index') in ControllerDispatcher.php line 54
at ControllerDispatcher->dispatch(object(Route), object(Request), 'App\Http\Controllers\KnowledgeBaseController', 'index') in Route.php line 174
at Route->runController(object(Request)) in Route.php line 140
at Route->run(object(Request)) in Router.php line 724
at Router->Illuminate\Routing\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 52
at Pipeline->Illuminate\Routing\{closure}(object(Request)) in VerifyCsrfToken.php line 64
at VerifyCsrfToken->handle(object(Request), object(Closure))
at call_user_func_array(array(object(VerifyCsrfToken), 'handle'), array(object(Request), object(Closure))) in Pipeline.php line 136
at Pipeline->Illuminate\Pipeline\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 32
at Pipeline->Illuminate\Routing\{closure}(object(Request)) in ShareErrorsFromSession.php line 49
at ShareErrorsFromSession->handle(object(Request), object(Closure))
at call_user_func_array(array(object(ShareErrorsFromSession), 'handle'), array(object(Request), object(Closure))) in Pipeline.php line 136
at Pipeline->Illuminate\Pipeline\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 32
at Pipeline->Illuminate\Routing\{closure}(object(Request)) in StartSession.php line 64
at StartSession->handle(object(Request), object(Closure))
at call_user_func_array(array(object(StartSession), 'handle'), array(object(Request), object(Closure))) in Pipeline.php line 136
at Pipeline->Illuminate\Pipeline\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 32
at Pipeline->Illuminate\Routing\{closure}(object(Request)) in AddQueuedCookiesToResponse.php line 37
at AddQueuedCookiesToResponse->handle(object(Request), object(Closure))
at call_user_func_array(array(object(AddQueuedCookiesToResponse), 'handle'), array(object(Request), object(Closure))) in Pipeline.php line 136
at Pipeline->Illuminate\Pipeline\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 32
at Pipeline->Illuminate\Routing\{closure}(object(Request)) in EncryptCookies.php line 59
at EncryptCookies->handle(object(Request), object(Closure))
at call_user_func_array(array(object(EncryptCookies), 'handle'), array(object(Request), object(Closure))) in Pipeline.php line 136
at Pipeline->Illuminate\Pipeline\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 32
at Pipeline->Illuminate\Routing\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 103
at Pipeline->then(object(Closure)) in Router.php line 726
at Router->runRouteWithinStack(object(Route), object(Request)) in Router.php line 699
at Router->dispatchToRoute(object(Request)) in Router.php line 675
at Router->dispatch(object(Request)) in Kernel.php line 246
at Kernel->Illuminate\Foundation\Http\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 52
at Pipeline->Illuminate\Routing\{closure}(object(Request)) in CheckForMaintenanceMode.php line 44
at CheckForMaintenanceMode->handle(object(Request), object(Closure))
at call_user_func_array(array(object(CheckForMaintenanceMode), 'handle'), array(object(Request), object(Closure))) in Pipeline.php line 136
at Pipeline->Illuminate\Pipeline\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 32
at Pipeline->Illuminate\Routing\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 103
at Pipeline->then(object(Closure)) in Kernel.php line 132
at Kernel->sendRequestThroughRouter(object(Request)) in Kernel.php line 99
at Kernel->handle(object(Request)) in index.php line 54

I've tracked it down to PHP's is_soap_fault function, where it says define ('SOAP_1_1', 1);

How do I fix this?

24 Oct
2 years ago

omrakhurs started a new conversation Trying To Connect To SharePoint Via Thybag/PHP-Sharepoint-Lists-API

Could someone please explain the following code, which connects a PHP app to a SharePoint account to access documents on that Sharepoint account. I know that it's not done this way in Laravel, so if someone could also tell if there would be some issues if it is used in Laravel?

    public function get_sharepoint_documents()
    {
        
        $listName = 'Knowledge Base Documents';
    
        if(!$cache_data = $this->cache->get('cache_sharepoint'))
        {
            $sp = new SharePointAPI('[email protected]', 'password', '\resources\Lists.asmx.xml','SPONLINE');
            $listContents = $sp->read($listName, NULL, NULL);
            $this->cache->save('cache_sharepoint',$listContents, 86400);
            $cache_data = $listContents;
        }
        //return $listContents;
        return $cache_data;
    }
27 Sep
2 years ago

omrakhurs left a reply on Retrieve Matching Rows From Same Table Using Foreign Key To Same Table

@InaniELHoussain , yes that does print the first name of the manager. But since it does only for one row, how do I now return manager names against each employee in a full table?

omrakhurs left a reply on Retrieve Matching Rows From Same Table Using Foreign Key To Same Table

There's only this in there:

$employees = Employee::all();
return view('employees.index')->with('employees', $employees);

omrakhurs left a reply on Retrieve Matching Rows From Same Table Using Foreign Key To Same Table

I can't understand how to write the code above in the index() function. My index() at the moment has this line: $employees = Employee::all();

Then I want to pass the $employees variable to my view.

Sorry to confuse you, I'm just not good at this :)

omrakhurs left a reply on Retrieve Matching Rows From Same Table Using Foreign Key To Same Table

@InaniELHoussain , That doesn't work either.... I think I know now what's going wrong. Due to me unable to explain it at first, you thought that managername is in the database. Therefore, I think that Laravel assumes from the name of the function getManagerNameAttribute() that there is a managerName attribute in the Employee model. In fact there is no such attribute there. I have firstname and lastname there and I'm trying to construct $managername in controller and then send it to view.

omrakhurs left a reply on Retrieve Matching Rows From Same Table Using Foreign Key To Same Table

@InaniELHoussain , @vinodrajput , sorry guys now it says:

ErrorException in Employee.php line 49: Trying to get property of non-object

omrakhurs left a reply on Retrieve Matching Rows From Same Table Using Foreign Key To Same Table

@InaniELHoussain this:

Collection {#322 ▼
#items: array:1 [▼
    0 => Employee {#323 ▶}
]
}

omrakhurs left a reply on Retrieve Matching Rows From Same Table Using Foreign Key To Same Table

@InaniELHoussain , it's not working. It gives the error:

ErrorException in Employee.php line 48: Undefined property: Illuminate\Database\Eloquent\Collection::$firstname

omrakhurs left a reply on Retrieve Matching Rows From Same Table Using Foreign Key To Same Table

@InaniELHoussain , thanks for the quick response. Is that a self join that you are doing up there with a self::where ? I'm not familiar with how that works in Laravel

omrakhurs started a new conversation Retrieve Matching Rows From Same Table Using Foreign Key To Same Table

I am trying to build a query, but cannot get my head around it because it's being done on the same table. The table is called employees, for which I have the resource controller EmployeeController. Inside the controller, there is the index() function which has to display the following three pieces of info:

  • First name (in the database as firstname)
  • Last name (in the database as 'lastname')
  • Manager name ( this is not in the database, but there is a manager_id in every row. This row points to the id of the employees table, which means that the manager is also an employee and thus has an id of their own.)

The table shown by the index() function would return $employees->firstname, $employees->lastname and $employees->managername.

The problem is that I can't understand how to construct $managername for every row returned.

07 Sep
2 years ago

omrakhurs started a new conversation How To Use The Password Reset Form For Logged In User In Laravel 5.2?

I am trying to use the auth\passwords\reset blade from the auth() scaffold package to let a user change their password once they are logged in. At the moment, this page does not show up as it's not added to the proper middleware route as discussed here

I'm trying to develop a simple form with a password and confirm password field, which the user could use to change their password to set a new password.

06 Sep
2 years ago

omrakhurs started a new conversation Query To Retrieve Details Through One-to-One Relationship

I have two Models (with snake case tables in MySQL behind them):

User and Employee

The first one is the standard Laravel User model, and the latter is simply a profile model for the users who have registered onto the system. The method defined in User is as follows:

public function employee()
    {
        return $this->hasOne('App\Employee','userid');
    }

The methods defined in Employee are as follows:

public function user()
    {
        return $this->belongsTo('App\User','userid');
    }

    public function manager(){
        return $this->belongsTo('App\User','manager');
    }

The idea here is that every User has only one profile and also only one manager. The employees table thus has four fields:

-userid
-manager
-first_name
-last_name

The first two fields are foreign keys on users table, which has the following fields:

-id
-email
-password

I want to have a query that looks up the Employee model using the manager field, finds the row with a matching userid and returns the first_name and last_name as a string.

02 Sep
2 years ago

omrakhurs started a new conversation Gracefully Redirecting User After Session Expires

I would like to know if there's a way to bring a user to the login page if the session is about to expire? I'm using laravel 5.2 and the only way I know if the session is expired is to wait for the number of minutes defined in config/session.php and then click on a link, upon which it shows me a lot of ErrorExceptions with the message "Trying to get property of non-object (View:...blah dee blah". Once I click refresh after this error page appears, it then takes me to the login screen.

I'm open to any and all techniques here about how others have handled this.

31 Aug
2 years ago

omrakhurs left a reply on Cannot Upload Image With Intervention Image

Okay, accidental solution found. I deleted the entire blade file. Made a new form in the new blade file and stored it with a different name. Now when I dd, it says that there is a file. I also did a view:clear on artisan.

omrakhurs left a reply on Cannot Upload Image With Intervention Image

@JoeDawson , sorry about that mate, thought I'd put the new form code above as well:

{{Form::open(['method'=>'POST','route' => 'users.store', 'files' => true, 'role'=> 'form']) }}
    {{Form::label('file', 'Update image') }}
    {{Form::file('avatar',null)}}
    {{Form::submit('Update',['class' => 'pull-left btn btn-sm btn-primary']) }}
    {{Form::close() }}

omrakhurs left a reply on Cannot Upload Image With Intervention Image

It's just a file selection button, and a submit button.

omrakhurs left a reply on Cannot Upload Image With Intervention Image

However, when I do a

if($request->hasFile('avatar')){
    die('there is a file');
}
else
    die('theres no file');

it says that theres no file.

omrakhurs left a reply on Cannot Upload Image With Intervention Image

@JoeDawson :

I did that and I think the problem was as follows:

The UserController is in fact a resource controller I made with artisan. Now it already has its own CRUD methods, plus in the routes file I also have a Route::resource('users','UserController');

Now inside of this controller, I had created the updateAvatar function and given it a route of

Route::post('profile', '[email protected]');

What I did then was do a dd on the request while it was being sent to updateAvatar. Got no response, just a blank page. Then I put the dd in the [email protected] method, and in the form set the

``route`=>`users.store`` 

Now it successfully shows the following:

array:2 [▼
    "_token" => "of2rLg73Yzdj8pbM8nmqlUPSxSbHdSrRoPzTBQoI"
    "avatar" => "089253d.jpg"
]

omrakhurs left a reply on Cannot Upload Image File Using Form Facade In 5.2

It produces an infinite loop of null arrays. Then the browser crashes. From what I am able to read, it is going through all the routes.

omrakhurs left a reply on Cannot Upload Image With Intervention Image

@tomi , now it gives a huge feedback, but before I could copy it, the page crashes. I could see a lot of null arrays though

omrakhurs left a reply on Cannot Upload Image File Using Form Facade In 5.2

@tomi , nothing has improved even with that.

omrakhurs left a reply on Cannot Upload Image File Using Form Facade In 5.2

@tomi No, still the same problem. But the facade implicitly adds the post method unless specified, already:

https://laravelcollective.com/docs/5.3/html#opening-a-form

omrakhurs started a new conversation Cannot Upload Image File Using Form Facade In 5.2

I have been struggling to upload an image in a simple form. Every time I upload the file, it says there is no file, as the functionality I've set up in the controller. Here is the code so far:

The blade form:

 <div class="text-align-center">
    {{Form::open(['url' => 'profile', 'files' => true]) }}
    {{Form::file('avatar')}}
    {{Form::submit('Update',['class' => 'pull-left btn btn-sm btn-primary']) }}
    {{Form::close() }}
</div>

The routes file:

Route::get('profile', '[email protected]');
Route::post('profile', '[email protected]');
Route::resource('users','UserController');

The UserController:

public function profile(){

            return view('profile', array('user' => Auth::user()));
    }   

    public function avatar(Request $request){

        if($request->hasFile('avatar')){
                var_dump($request);
        }
        else
                die('there is no file here!');
}

The User model:

protected $fillable = [
        'username', 'email', 'avatar'
    ];

My php.ini has maximum file size limits of 8M, the file I'm trying to upload is only a few KB.

omrakhurs left a reply on Cannot Upload Image With Intervention Image

@JoeDawson , I did a var_dump on the request object, and the result was NULL. Does that mean there's something wrong with the routes or blade?

omrakhurs left a reply on Cannot Upload Image With Intervention Image

@JoeDawson , made it fillable in the User model. Still not working. I'm still unsure about some of the parts in the lines below due to my limited knowledge of Laravel. I don't know if some of those functions like public_path and Image::make() are working right

    $filename = time() . '.' . $avatar->getClientOriginalExtension();
        Image::make($avatar)->resize(200, 200)->save( public_path('/uploads/avatars/' . $filename ) );

omrakhurs left a reply on Cannot Upload Image With Intervention Image

@JoeDawson , my bad. That was not supposed to be there. I have updated the question. avatar isn't fillable at the moment.

omrakhurs started a new conversation Cannot Upload Image With Intervention Image

I am trying to upload an image using the tutorial here. I have followed the instructions exactly as in the video, but once I click on the submit button, it brings me back to the profile page, and the image is unchanged, nothing has changed in the database or uploaded to the folder designated. I am using Laravel 5.2.

Here is my routes.php:

Route::get('profile', '[email protected]');
Route::post('profile', '[email protected]');

Here is the blade file:

<div class="row">
   <div class="col-sm-4">
       <div class="text-align-center">
           <img class="img-circle" src="/uploads/avatars/{{ Auth::user()->avatar }}" alt="64x64" style="height: 112px; border-radius:50%;">
       </div>
       <br>
       <br>
       <div class="text-align-center">
          <form enctype="multipart/form-data" action="{{ url('/profile') }}" method="POST">
          <h5>Update Profile Image</h5>
          <input type="file" name="avatar">
          <input type="hidden" name="_token" value="{{ csrf_token() }}"> <br>          
          <input type="submit" class="pull-left btn btn-sm btn-primary">
          </form>
       </div>
</div>

Here is the controller:

 public function showProfile(){

        return view('profile', array('user' => Auth::user()));
    }

    public function updateAvatar(Request $request){
        //Handle the user upload of avatar
        if($request->hasFile('avatar')){
            $avatar = $request->file('avatar');
            $filename = time() . '.' . $avatar->getClientOriginalExtension();
            Image::make($avatar)->resize(200, 200)->save( public_path('/uploads/avatars/' . $filename ) );
            $user = Auth::user();
            $user->avatar = $filename;

            $user->save();
        }

        return view('profile', array('user' => Auth::user()));
    }

I have added a field avatar to the users table.

26 Aug
2 years ago

omrakhurs left a reply on How To Redirect To Login Page In Laravel 5.2 On Session Timeout?

not working. Here is my config/session :

return [

/*
|--------------------------------------------------------------------------
| Default Session Driver
|--------------------------------------------------------------------------

| Supported: "file", "cookie", "database", "apc",
|            "memcached", "redis", "array"
|
*/

'driver' => env('SESSION_DRIVER', 'file'),

/*
|--------------------------------------------------------------------------
| Session Lifetime
|--------------------------------------------------------------------------

*/

'lifetime' => 1,

'expire_on_close' => true,

/*
|--------------------------------------------------------------------------
| Session Encryption
|--------------------------------------------------------------------------

*/

'encrypt' => false,

/*
|--------------------------------------------------------------------------
| Session File Location
|--------------------------------------------------------------------------

*/

'files' => storage_path('framework/sessions'),

/*
|--------------------------------------------------------------------------
| Session Database Connection
|--------------------------------------------------------------------------

*/

'connection' => null,

/*
|--------------------------------------------------------------------------
| Session Database Table
|--------------------------------------------------------------------------

*/

'table' => 'sessions',

/*
|--------------------------------------------------------------------------
| Session Sweeping Lottery
|--------------------------------------------------------------------------

*/

'lottery' => [2, 100],

/*
|--------------------------------------------------------------------------
| Session Cookie Name
|--------------------------------------------------------------------------

*/

'cookie' => 'laravel_session',

/*
|--------------------------------------------------------------------------
| Session Cookie Path
|--------------------------------------------------------------------------

*/

'path' => '/',

/*
|--------------------------------------------------------------------------
| Session Cookie Domain
|--------------------------------------------------------------------------

*/

'domain' => null,

/*
|--------------------------------------------------------------------------
| HTTPS Only Cookies
|--------------------------------------------------------------------------

*/

'secure' => false,

/*
|--------------------------------------------------------------------------
| HTTP Access Only
|--------------------------------------------------------------------------
*/

'http_only' => true,

];