Tangaye

Experience

3,290

0 Best Reply Awards

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

19th September, 2017

Tangaye left a reply on Login Authentication For User, Guardian And Teacher. • 4 days ago

Thanks for your help. Will appreciate it if you can get me a means(email or social media profile) to get to you. Want you to take a look at the demo when I'm through. Thanks again.

8th September, 2017

Tangaye left a reply on Looping Through Associative Array Returning Single Results When The Are More To Be Returned • 2 weeks ago

@tisuchi thanks. That shows me the two values. Now I have realize that when I try to have an if statement that checks if one date equals another I only get the condition to run against the first value only.

Here is how my code looks:

$recieveDate = Carbon::createFromDate($date); // assume value is 2017
$startDates = Academic::all()->pluck('date_start');
// this should return two values 2017 & 2018

foreach ($startDates as $key => $value) {
    
    // this only check against 2017 and not 2018
    if ($value->year == $recieveDate->year) {
        return response()->json(['exists' => 'The year of School Date Start already exists']);
    } else {
        return response()->json(['none' => null]);
    }
}

How do I get it to check against both values?

Tangaye started a new conversation Looping Through Associative Array Returning Single Results When The Are More To Be Returned • 2 weeks ago

I have this query that returns an associative, but instead of return all of the results from the query I'm getting a single result returned by I dd or die and dump.

Here is the query:

$startDates =  \DB::table('academics')->pluck('date_start');

this is the result returned:

Collection {#301
  #items: array:2 [
    0 => "2017-09-21"
    1 => "2018-06-07"
  ]
}

my loop:

foreach ($startDates as $key => $value) {
    dd($value);
}                   

result from my loop:

"2017-09-21"

9th August, 2017

Tangaye left a reply on Login Authentication For User, Guardian And Teacher. • 1 month ago

@IgorBabko I appreciate your help and patience so far. It has been tremendous. But there is something that @snappy share light on that is bothering me. He stated:

Just watch out for the fact that a teacher could also be a guardian and if your database is around long enough, in time a student can become a guardian or teacher

From what he's suggesting it is possible and likely that a teacher can be a guardian also. How do I handle that based on what you've shown me.

I'm thinking I can have something sort of a switch/if statement to check if the user being created is both a teacher and a guardian. If both holds true I perceive doing something like this:

User::create(['type' => '\App\Teacher']);
User::create(['type' => '\App\Guardian']);

But been that a one-to-one relationship attribute has been set up in the user model I'm sure what I'm trying isn't going to work. Is there a way to get this work?

4th August, 2017

Tangaye left a reply on How To Use Authentication Using Username Instead Of Email • 1 month ago

@Snapey you're right. I followed the documentation and the youtube and applied as instructed. I also noticed that I had to customize the logout method and I did the same. Thanks!

3rd August, 2017

Tangaye left a reply on How To Use Authentication Using Username Instead Of Email • 1 month ago

@tareenmj find this file:

use Illuminate\Foundation\Auth\AuthenticatesUsers;

and the user method from this:

public function username()
{
    return 'email';
}

to this:

public function username() { return 'username'; //or whatever field }

hope this helps!

2nd August, 2017

Tangaye left a reply on Login Authentication For User, Guardian And Teacher. • 1 month ago

@IgorBabko so you're saying my migrations can look like this:

teacher table

id
userId

guardian table

id
relationship
userId

user table

id
firstName
lastName
gender
email
password

If my migration is inline with what you're suggesting then that means whenever I'm creating a user I'll have to check if the admin creating the user specify the type of user. If the type of user for example is guardian I'll now use jquery to append the guardian relationship column to the form.

If the type the admin selects is teacher I`ll append append with jquery also a checkbox list of all subjects and classes.

Now, if what I'm thinking of is the right approach then in my user controller I'll use a lot of if statements like this:

if(request('type') === '\App\Teacher'){
    $user = User::create(['type' => '\App\Teacher']);

    $user->data()->create(request('name', 'gender','address','etc'));

    $user->data()->subjects()->attach(request('subject_ids')); // if 
    request('subject_id') - is an array of IDs.
}

else if (request('type') === '\App\Guardian'){
     $user = User::create(['type' => '\App\Guardian']);

     $user->data()->create(request('name', 'gender','address','etc'));
}

from what you've been teaching me this is how I envision things to work. Am I getting things wrong? Are there better ways to do it?

1st August, 2017

Tangaye left a reply on Login Authentication For User, Guardian And Teacher. • 1 month ago

@IgorBabko things are getting a bit clearer. From what you're suggesting I feel that all table connected to the user table should have the same type of column. Correct me if I'm wrong. Ex:

teacher table

id
firstName
lastName
gender
email
userId

guardian table

id
firstName
lastName
gender
email
userId

But now in the user table there area some columns that just won't be in the tables connected to it, which I see as password and username column.

user table

id
firstName
lastName
gender
email
password

How would you handle such situation?

31st July, 2017

Tangaye left a reply on Login Authentication For User, Guardian And Teacher. • 1 month ago

@IgorBabko are you saying that creating a user will also create a teacher/guardian? If so how does this handles assigning multiple subjects or classes to a teacher and multiple students to a guardian. Please take a look on how I know to insert records into a pivot table in this case subject_teacher. Before I ask this question I had in my to have a form for teacher details and at the bottom there are check-boxes of subjects a teacher can teach. for each checkbox that is checked they are send in an array format which makes it possible for me to loop through the array of subject sent and assigned them to the specify teacher.

$teacher = Teacher::create(request(['name', 'gender','address','etc']));

foreach (request(['subject_id']) as $subject){
    //assigned  subject(s) to teacher
   // this will insert records in the pivot table
    $teacher->subject()->attach($subject);
}               

I know this might not fall inline with yours, but how do I adopt what I'm trying to do with yours?

Tangaye left a reply on Login Authentication For User, Guardian And Teacher. • 1 month ago

@Snapey for now I don't fully understand where you're driving at, but please keep in mind that the system requires that I render different views for teachers and guardians.

Tangaye left a reply on Login Authentication For User, Guardian And Teacher. • 1 month ago

@IgorBabko assuming that I adopt your suggestion. You saying that "the type column will store the fully qualified path to the particular user model class. " I'm a bit confuse because I have no experience on how this is going to work. Take for instance in my form will the type be a drop down list of all the user classes? If so, how do one know that a specific guardian user account is being created given that the type class selected is guardian.

Also is it require that I add a default class path to the type column? I know my question my look a bit dumb, but the only part of your answer I'm understanding is the model and the migration. I know you're doing your best to help me but I'm kind of a novice to the knowledge you're sharing now. Will appreciate it if you can patiently walk me through the solution. Thanks!

Tangaye started a new conversation Login Authentication For User, Guardian And Teacher. • 1 month ago

My system requires login for user, teacher, and guardian. I did a little bit of research on the topic and lot of folks talk about utilizing the user type feature. But I don't think that will work for me or maybe I don't understand how to make it work that way.

One thing I'm concern about when I'm creating a teacher(something only the admin should do) is that a teacher can teach multiple subjects and classes. So, in short a many to many relationship exists between teacher and subject. Whenever I inserting a teacher I have to specify the class(es) he/she teaches. Also a guardian is related to many students, and whenever I'm inserting a guardian I have to specify the student(s) the guardian is related to.

I could create separate migrations, models controllers, and views for all those users(admins, guardians, staffs and teachers) but something tells me that wouldn't be an efficient solution to the problem. What are others alternatives to addressing the issue.

What are others alternatives to addressing this issue, wherein I can have a single login that is use to authenticate different kinds of users and returns views that are specific to user kind.

Is there a way that when the administrator is inserting teacher and guardians a user account be generated for them? Thanks for the attention!

19th July, 2017

Tangaye left a reply on How To Format Or Rearrange Inner Join Query Results In Laravel View Or Controller • 2 months 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 • 2 months 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 • 2 months ago

@martinbean should my route be post?

Tangaye started a new conversation PUT Won't Work, But POST Does Instead • 2 months 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) • 2 months 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) • 2 months 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 • 2 months 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 • 2 months 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 • 2 months 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 • 2 months 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) • 2 months 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 months 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 months 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 months 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 months 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 months ago

@rodolz I'm getting > Undefined variable: subject

Tangaye started a new conversation Display Values That Are Checked When Editing In Laravel • 2 months 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 • 2 months 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) • 2 months 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 • 2 months 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 • 2 months 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? • 3 months 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? • 3 months ago

@ufodisko sure it does.

Edit Your Profile
Update

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