Tangaye

Experience

3,090

0 Best Reply Awards

  • Member Since 5 Months Ago
  • 25 Lessons Completed
  • 0 Favorites

19th July, 2017

Tangaye left a reply on How To Format Or Rearrange Inner Join Query Results In Laravel View Or Controller • 6 days ago

@hondl I need the a student(siafa) score for subject(math) for first period(90) second period(99) and third period(88). What do you mean by asking if I need the periods to be dynamic? Please note that I'm actually working on a School Management System for secondary schools in my country. Now, normally there are eight terms six of them are periods and two of them are exams time. Since I'm planning on this being a saas application I can't specify the amount of terms a school may have. For more information on the design please take a look at this thread: https://stackoverflow.com/questions/45170192/how-to-rearrange-results-returned-by-inner-join-query

Tangaye started a new conversation How To Format Or Rearrange Inner Join Query Results In Laravel View Or Controller • 1 week ago

I have five table students, grades, subjects, terms, and scores. I'm performing an inner join on thes table to return results. This how my schema looks:

Students table:

students
--------
id *
name
class_id (fk)

Subjects table:

subjects
--------
id *
name

Class table:

classes
--------
id *
name

Term table:

terms
--------
id *
name

Scores Table:

scores
---------------
id *
student_id (fk)
subject_id (fk)
class_id (fk)
term_id (fk)
score

My laravel query:

$scores = \DB::table('scores')
        ->join('students', 'students.id', '=', 'scores.student_id')
        ->join('subjects', 'subjects.id', '=', 'scores.subject_id')
        ->join('grades', 'grades.id', '=', 'scores.grade_id')
        ->join('terms', 'terms.id', '=', 'scores.term_id')
        ->select('students.first_name', 'students.surname', 'subjects.name as subject', 'grades.name as grade', 'terms.name as term', 'score')
        ->where('students.id', 1)
        ->whereBetween('scores.term_id', [1, 3])
        ->get();

result return by the query when I die and dump it:

enter image description here

Without doubt the query is returning the right result, but the problem is I want the result to appear in my html table like this:

enter image description here

This is how it is displaying based on the code I now have in my controller and view.

controller:

public function index()
{
    //
    $scores = \DB::table('scores')
        ->join('students', 'students.id', '=', 'scores.student_id')
        ->join('subjects', 'subjects.id', '=', 'scores.subject_id')
        ->join('grades', 'grades.id', '=', 'scores.grade_id')
        ->join('terms', 'terms.id', '=', 'scores.term_id')
        ->select('students.first_name', 'students.surname', 'subjects.name as subject', 'grades.name as grade', 'terms.name as term', 'score')
        ->where('students.id', 1)
        ->whereBetween('scores.term_id', [1, 3])
        ->get();


    // finding details of the student based on id pased
    $student = Student::findOrFail(1);

    // getting the name of the student
    $name = $student->first_name.' '.$student->surname;

    // getting the class or grade of the student (grade 12 or grade 11)
    $grade = $student->grade->name;

    // getting the current date
    $date = Score::date();

    return view('scores.home', compact('scores', 'name', 'date', 'grade'));

view:

<table class="table table-bordered table-condensed table-striped">
    <thead>
        <tr>
            <th scope="row">Name</th>
            <td colspan="4">{{$name}}</td>
        </tr>
        <tr>
            <th scope="row">Class</th>
            <td colspan="2">{{$grade}}</td>

            <th scope="row">Date</th>
            <td>{{$date->toFormattedDateString()}}</td>
        </tr>
        <tr>
            <th class="text-center">Subject</th>
            @foreach($scores as $score)
                <th class="text-center">{{$score->term}}</th>
            @endforeach
        </tr>
    </thead>
    <tbody>
        @foreach($scores as $score)
            <tr>
                <td>{{$score->subject}}</td>
                <td>{{$score->score}}</td>
            </tr>
        @endforeach
    </tbody>
</table>

result:

enter image description here

As seen in the result above the term name 1st Period is being repeated, how do I avoid that? How do I refactor my query or code in view or controller to get the desire results that I want?

18th July, 2017

Tangaye left a reply on PUT Won't Work, But POST Does Instead • 1 week ago

@martinbean should my route be post?

Tangaye started a new conversation PUT Won't Work, But POST Does Instead • 1 week ago

I trying to update records in my table, and following the laravel's documentation I learned that such a request should be a PUT request.

Route:

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

Controller:

public function update(Request $request, $id)
{
    //
    // make validation
    $rules = [
        'surname' => 'bail|required|max:50|min:1|regex:/^[a-z ,.\'-]+$/i'
    ];

    $validator = Validator::make($request->all(), $rules);

    if ($validator->fails ()) {
        return back()->withInput();
    } else {
        // find student
        $student = Student::findOrFail($id);

        //update student record
        $student->update(request([
            'surname'
        ]));

        // send a message to the session that greets/ thank user
        session()->flash('message', $student->first_name." ".$student->surname);

        return redirect('/students');
    }
}

form:

<form method="put" action="/students/update/{{$student->id}}">

    {{csrf_field()}}
   <input type="hidden" name="_method" value="PUT">

    <input type="text" name="surname">
</form>

This is throw this error:

MethodNotAllowedHttpException

route list:

+--------+----------+-----------------------+------+--------------------------------------------------+--------------+
| Domain | Method   | URI                   | Name | Action                                           | Middleware   |
+--------+----------+-----------------------+------+--------------------------------------------------+--------------+
|        | GET|HEAD | /                     |      | Closure                                          | web          |
|        | GET|HEAD | api/user              |      | Closure                                          | api,auth:api |
|        | GET|HEAD | divisions             |      | App\Http\Controllers\[email protected]   | web          |
|        | POST     | divisions             |      | App\Http\Controllers\[email protected]   | web          |
|        | DELETE   | divisions/delete/{id} |      | App\Http\Controllers\[email protected] | web          |
|        | PUT      | divisions/update/{id} |      | App\Http\Controllers\[email protected]  | web          |
|        | POST     | grades                |      | App\Http\Controllers\[email protected]      | web          |
|        | GET|HEAD | grades                |      | App\Http\Controllers\[email protected]      | web          |
|        | DELETE   | grades/delete/{id}    |      | App\Http\Controllers\[email protected]    | web          |
|        | GET|HEAD | grades/edit/{id}      |      | App\Http\Controllers\[email protected]       | web          |
|        | PUT      | grades/update/{id}    |      | App\Http\Controllers\[email protected]     | web          |
|        | GET|HEAD | students              |      | App\Http\Controllers\[email protected]    | web          |
|        | POST     | students              |      | App\Http\Controllers\[email protected]    | web          |
|        | GET|HEAD | students/create       |      | App\Http\Controllers\[email protected]   | web          |
|        | PUT      | students/update/{id}  |      | App\Http\Controllers\[email protected]   | web          |
|        | DELETE   | students/{id}/delete  |      | App\Http\Controllers\[email protected]  | web          |
|        | GET|HEAD | students/{id}/edit    |      | App\Http\Controllers\[email protected]     | web          |
|        | POST     | subjects              |      | App\Http\Controllers\[email protected]    | web          |
|        | GET|HEAD | subjects              |      | App\Http\Controllers\[email protected]    | web          |
|        | DELETE   | subjects/delete/{id}  |      | App\Http\Controllers\[email protected]  | web          |
|        | GET|HEAD | subjects/edit/{id}    |      | App\Http\Controllers\[email protected]     | web          |
|        | PUT      | subjects/update/{id}  |      | App\Http\Controllers\[email protected]   | web          |
+--------+----------+-----------------------+------+--------------------------------------------------+--------------+

What am I getting wrong here?

Tangaye left a reply on Get Selected Values From Database In Checkboxes (Laravel) • 1 week ago

@sobhanattar that's right! Am I going about it the right way?

17th July, 2017

Tangaye left a reply on Get Selected Values From Database In Checkboxes (Laravel) • 1 week ago

@sobhanattar I don't selectedDivision in order to get that I had to make an ajax request. Please know that I'm using a pop up bootstrap model for editing, which means I'm not loading out another view to edit the record. After I have send the id to the edit method and have gotten the values I want returned. I return a partial view with those values (subjects,selectedDivisios.divisions`) into my modal for editing. Hope this gives understanding. Please let me know if there's a better of cleaner way to do it. Thanks so much for the effort.

14th July, 2017

Tangaye left a reply on How To Add Custom Javascripts To Application • 1 week ago

@tykus it is stored in the public directory if that what you're asking.

Tangaye left a reply on How To Add Custom Javascripts To Application • 1 week ago

@tykus it is now working, but I'm getting $.notify is not a function

Tangaye left a reply on How To Add Custom Javascripts To Application • 1 week ago

@tykus I did require it in resources/assets/js/app.js but sorry that I failed to mentioned or show that file. How can I accomplish what you're suggesting, can you show me some practical examples?

Tangaye started a new conversation How To Add Custom Javascripts To Application • 1 week ago

Hi guys in my laravel project I have some javascript helpers function that utilizes jquery I want to extract to a separate place that all parts of the application can use. These are the function stored in helper.js :

// bootbox function to delete records
// it utitlizes the bootbox library
function bootbox_delete(message, route, row) {
    // body...
    bootbox.dialog({
        message: message,
        title: "<i class='glyphicon glyphicon-trash'></i> Delete !",
        buttons: {
            success: {
                label: "No",
                className: "btn-success",
                callback: function callback() {
                    $('.bootbox').modal('hide');
                }
            },
            danger: {
                label: "Delete!",
                className: "btn-danger",
                callback: function callback() {

                    $.ajax({
                        type: 'DELETE',
                        url: route
                    }).done(function (data) {
                        bootbox.alert('<b>' + data.name + '</b> successfully deleted');
                        //removing the row that have been deleted
                        jQuery(row).fadeOut('slow');
                    }).fail(function () {
                        bootbox.alert('Something Went Wrong .... Please contact administrator');
                    });
                }
            }
        }
    });
}


// function that displays notification
function notify(message) {
    // body...
    $.notify({
        icon: 'fa fa-check',
        message: message
    }, {
        type: 'success',
        timer: 4000,
        offset: 20,
        spacing: 10,
        z_index: 1031,
        delay: 5000,
        placement: {
            from: "top",
            align: "right"
        },

        animate: {
            enter: 'animated fadeInDown',
            exit: 'animated fadeOutUp'
        }
    });
}

What I have done is that I added helper.js to resources/assets/js and compile to public/js/app.js with npm run dev but whenever I tried to see if things are working I get these errors:

notify is not defined bootbox_delete is not defined

13th July, 2017

Tangaye left a reply on Get Selected Values From Database In Checkboxes (Laravel) • 1 week ago

@sobhanattar thanks I got it working now. But I used ajax to to fetch the $selectedDivisionOfThisSubject and passed that to my view. Also I utilize the in_array() method you suggested in your first answer which lead me to returned the selected divisions like this $selectedDivisionOfThisSubject->toArray(). :heart_eyes: :kissing_closed_eyes: :wink:

11th July, 2017

Tangaye left a reply on Get Selected Values From Database In Checkboxes (Laravel) • 2 weeks ago

@sobhanattar Thanks for being a bit explicit. This is what I have in my controller to display records in my table:

public function index(Subject $subject)
{
    //
    $subjects = Subject::all();
   
    return view('subjects.show', compact('subjects'));
}

If it is best practice and is advisible I can refactor to this:

 $subject = Subject::with('divisions')->get();

The reason I didn't do it that way is that I realize that the page loads a bit slower when I do that. Like it's loading all the subjects and divisions at once. But anyway if it's best practice as I sad I will go along.

concerning the checked values

You said I should do this:

{{ in_array($division->id, $array_of_values_you_fetched_from_database_as_seleted_items) ? 'checked' : '' }}

But I'm thinking if I should make an ajax call to get the divisions assigned to the subjects. If the divisions are many, how do I pass the array of divisions returned to the method you suggested. Will appreciate some practical examples.

Tangaye left a reply on Get Selected Values From Database In Checkboxes (Laravel) • 2 weeks ago

@bunnypro I'm not that good with javascript and have not the slightly idea on how you want me to accomplish this. Can you please be a little bit practical? Also know that I want the list of all the divisions and the ones assigned to the subject to be edited should be checked.

Tangaye left a reply on Get Selected Values From Database In Checkboxes (Laravel) • 2 weeks ago

@fransiskusbenny I get this error when I do the second solution suggested, because I don't seem to understand the first.

Undefined variable: subject

Tangaye started a new conversation Get Selected Values From Database In Checkboxes (Laravel) • 2 weeks ago

    <label for="division">Level</label>
    <p class="text-muted">Please select the division(s) the subject is taught within.</p>
    @foreach($divisions as $division)
        <label class="checkbox-inline">
            <input type="checkbox" id="division_id" name="division_id[]" value="{{$division->id}}"> {{$division->name}}
        </label>
    @endforeach                            
</div>

6th July, 2017

Tangaye left a reply on Display Values That Are Checked When Editing In Laravel • 2 weeks ago

@rodolz I'm getting > Undefined variable: subject

Tangaye started a new conversation Display Values That Are Checked When Editing In Laravel • 2 weeks ago

I'm working on a laravel application. In this application I have three tables:

subjects

id | name
-- | ----
01 | maths
02 | english

divisions

id | name
-- | ----
01 | Senior High
02 | Junior High

division_subject pivot table

division_id | subject_id
--- | ---
01 | maths
02 | english

A subject can have many divisions, so, in my form I have a list of all divisions as checkboxes. I the subject is taught in a single division a single division will be checked. If the subject is taught is many divisons all the divisions the subject is taught in will be checked also. Now this is working fine when inserting with no problems. This is how the form looks: enter image description here

Problem

Now, I want to be able to edit a subject and when I click on a edit button I want all divisions that are checked to a subject checked or all divisions that are assigned to a subject in the pivot table checked. This is what I haven't been able to get my head around in laravel. so far this is how my code looks:

Division controller that returns all the divisions to be assigned to a subject:

public function index(Request $request)
{
    //
    
    if ($request->ajax()) {
        $divisions = Division::all();

        return $divisions->pluck('name', 'id')->toArray();
    }
    //return view('division.show', compact('divisions'));
}

This is how I'm rendering it in the table.

<td>
<!-- If a subject belongs to a division or divisions list all the divisions
that belongs to the subject -->
@if(count($subject->divisions))
    @foreach($subject->divisions as $division)

        <a href="#" data-type="checklist" data-value="{{$division->id}}" data-title="Select divisions" data-name="division" class="division" data-pk="{{$division->id}}" role="button">
            <span class="badge label-primary">{{$division->name}}</span>
        </a> 

    @endforeach
@endif
</td>

This i how I'm rendering it in a model that has a form.

<div class="form-group">

    <label for="division">Level</label>
    <p class="text-muted">Please select the division(s) the subject is taught within.</p>
    @foreach($divisions as $division)
        <label class="checkbox-inline">
            <input type="checkbox" id="division_id" name="division_id[]" value="{{$division->id}}"> {{$division->name}}
        </label>
    @endforeach                            
</div>

The thing is I'm doing the same in the edit form but don't know how to checked up that values that have been assigned to a subject.

Is there a way that when the user click the edit button than all the divisions assigned to the subject be checked up.

anchor element that shows edit modal.

<td>
    <a class="edit-modal" data-id="{{$subject->id}}" data-name="{{$subject->name}}" data-toggle="tooltip" title="Edit" href="#" role="button">
        <i class="glyphicon glyphicon-edit text-info"></i>
    </a>
</td>

This is my script for now:

$(document).on('click', '.edit-modal', function(event) {
            event.preventDefault();
            /* Act on the event */
            $('#edit-name').val($(this).data('name'));
            $('#edit-modal').modal({
                show: true,
                backdrop:'static',
                keyboard:false
            });
        });

5th July, 2017

Tangaye started a new conversation X-editable Doesn't Check Up Checked Checklist Values • 3 weeks ago

Good day guys. In a Laravel application I'm working on, I'm using the X-editable library for inline editing options. I'have a many to many relationship table (pivot table) that I need to update. To do so I'm trying to utilize X-editable checklist option as seen in the docs: checklist

The problem I'm facing is whenever I click on one of the values to edit the checklist dialog pops out but the value I clicked on isn't checked. Here is a picture that better illustrate this:

checklist image

From the picture you see that the values to be checked are Senior High, Junior High and Elementary, but they are not check and I can't figure out why.

This is how my view looks:

<td>
    <!-- If a subject belongs to a division or divisions list all the divisions
    that belongs to the subject -->
    @if(count($subject->divisions))
        @foreach($subject->divisions as $division)

            <a href="#" data-type="checklist" data-value="{{$division->id}}" data-title="Select divisions" data-name="division" class="division" data-pk="{{$division->id}}" role="button">
                <span class="badge label-primary">{{$division->name}}</span>
            </a> 

        @endforeach
    @endif
</td>

controller:

 public function index(Request $request)
{
    //
    
    if ($request->ajax()) {
        $divisions = Division::all();

        return $divisions->pluck('name', 'id')->toArray();
    }
    //return view('division.show', compact('divisions'));
}

script:

$('#subjects').editable({
    mode:'popup',
    container:'body',
    selector:'a.division',
    type:'checklist',
    source: function () {
        // body...
        var result;
        

        $.ajax({
            url: '/divisions',
            type: 'GET',
            async: false,
            global  : false,
            dataType:'json',
            success: function (data) {
                // body...

                console.log(data);

                result = data;

            }
        })
        .done(function(data) {
            console.log("success");
        })
        .fail(function(data) {
            console.log("error");
            console.log(data);
        });

        return result;
        console.log(result);
        
    }
});

result from source:

enter image description here

27th June, 2017

Tangaye started a new conversation How To Validate X-editable Request In Laravel (Server Side) • 4 weeks ago

I've managed to get x-editable (https://vitalets.github.io/x-editable/) to work with a page, in so far as when I click on a field, it displays inline and I can edit it, and I'm able to successfully submit to a POST URI.

The idea here is that I'm sending three key-value pairs:

array:3 [▼
  "name" => "name"
  "value" => "mathematics"
  "pk" => "1"
]

and my update() method catches the array, and it successfully updates the record in the database. But I'm failing to validate the data.

This is how my controller looks:

 public function update(Request $request)
{
    //
    $id = $request->pk;
    $subject = Subject::findOrFail($id);

    $rules = array (
        'name' => 'bail|required|max:20|unique:subjects,name,'.$id
    );

This validation pass easily even if I try to fail it

    $validator = Validator::make ( $request->all(), $rules );

    if ($validator->fails ()) {
        return response()->json ( array (
                    
         'errors' => $validator->getMessageBag ()->toArray ()
        ) );
    } else {
        $subject->update([$request->name => $request->value]);
    }
    return response ()->json ( $subject );
 }

Route:

Route::post('/subjects/update/', [email protected]');

script:

$('#subjects').editable({
     container:'body',
     selector:'td.name',
     type:'post',
     dataType:'JSON',
     validate:function(value){
        if ($.trim(value) === '') {
           return "Field is required";
        }
                
     },
              success:function(data){
                    console.log(data);
              } ,
              error:function(data) {
                $('#fail').text('The was and error please try again');
           }
});

Tangaye left a reply on Laravel And X-editable, Ajax Not Being Validated • 4 weeks ago

@sanuglia I'm stuck like you. Have you found a solution?

26th June, 2017

Tangaye started a new conversation How To Use X Editable To Edit Multiple Fields In Laravel • 4 weeks ago

I'm currently editing a single field in Laravel using the X-editable library.

But I want to do this for multiple fields without having to create new routes and methods in my controller, if it is possible. How can I accomplish this?

view:

<td data-url="/subjects/update/{{$subject->id}}" data-id="{{$subject->id}}" data-type="text" data-name="{{$subject->name}}" class="name" data-pk="{{$subject->id}}">{{$subject->name}}</td>

controller:

public function update(Request $request, $id) {
    $subject = Subject::findOrFail($id);
    $subject->name = $request->value;
    //$subject->level = $request->level;
    $subject->save();
    return response ()->json ( $subject );
}

script:

$.ajaxSetup({
   headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    }
});

$('#subjects').editable({
    container:'body',
    selector:'td.name',
    type:'post',
    validate:function(value){
        if ($.trim(value) === '') {
            return "Field is required";
        }
    }
 });

Now this is the other field that I want to edit along with its scripts

html:

<td data-url="/subjects/update/{{$subject->id}}" data-id="{{$subject->id}}" data-type="text" data-name="{{$subject->level}}" class="level" data-pk="{{$subject->id}}">{{$subject->level}}</td>

script:

$('#subjects').editable({
    container:'body',
    selector:'td.level',
    type:'post',
    validate:function(value){
        if ($.trim(value) === '') {
            return "Field is required";
        }
    }
});

What changes should I make to my controller in order to get this working?

13th June, 2017

Tangaye started a new conversation How To Generate Custom Identification Values In Laravel? • 1 month ago

Good day guys, I have two(2) fields, persondId (primary key) which is auto incremented and personCode which should be a custom four(4) digits incremented value based on the personId field.

For example when when a record is inserted into the persons table personId becomes 1 and personCode should become 0001

How do I accomplish this in laravel?

For in depth description here is a link to a thread I created on stackoverflow: https://stackoverflow.com/questions/44523813/how-to-generate-custom-identification-values-in-laravel

6th June, 2017

Tangaye left a reply on Laravel 5 Ajax GET And POST Examples? • 1 month ago

@ufodisko sure it does.

Edit Your Profile
Update

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