ComputerMaverick

ComputerMaverick

Software Engineer at Reconnaissance Technologies

Member Since 7 Months Ago

Abuja

Experience Points
700
Total
Experience

4,300 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
0
Lessons
Completed
Best Reply Awards
0
Best Reply
Awards
  • start your engines Created with Sketch.

    Start Your Engines

    Earned once you have completed your first Laracasts lesson.

  • first-thousand Created with Sketch.

    First Thousand

    Earned once you have earned your first 1000 experience points.

  • 1-year Created with Sketch.

    One Year Member

    Earned when you have been with Laracasts for 1 year.

  • 2-years Created with Sketch.

    Two Year Member

    Earned when you have been with Laracasts for 2 years.

  • 3-years Created with Sketch.

    Three Year Member

    Earned when you have been with Laracasts for 3 years.

  • 4-years Created with Sketch.

    Four Year Member

    Earned when you have been with Laracasts for 4 years.

  • 5-years Created with Sketch.

    Five Year Member

    Earned when you have been with Laracasts for 5 years.

  • school-in-session Created with Sketch.

    School In Session

    Earned when at least one Laracasts series has been fully completed.

  • welcome-newcomer Created with Sketch.

    Welcome To The Community

    Earned after your first post on the Laracasts forum.

  • full-time-student Created with Sketch.

    Full Time Learner

    Earned once 100 Laracasts lessons have been completed.

  • pay-it-forward Created with Sketch.

    Pay It Forward

    Earned once you receive your first "Best Reply" award on the Laracasts forum.

  • subscriber Created with Sketch.

    Subscriber

    Earned if you are a paying Laracasts subscriber.

  • lifer Created with Sketch.

    Lifer

    Earned if you have a lifetime subscription to Laracasts.

  • evangelist Created with Sketch.

    Laracasts Evangelist

    Earned if you share a link to Laracasts on social media. Please email [email protected] with your username and post URL to be awarded this badge.

  • chatty-cathy Created with Sketch.

    Chatty Cathy

    Earned once you have achieved 500 forum replies.

  • lara-veteran Created with Sketch.

    Laracasts Veteran

    Earned once your experience points passes 100,000.

  • 10k-strong Created with Sketch.

    Ten Thousand Strong

    Earned once your experience points hits 10,000.

  • lara-master Created with Sketch.

    Laracasts Master

    Earned once 1000 Laracasts lessons have been completed.

  • laracasts-tutor Created with Sketch.

    Laracasts Tutor

    Earned once your "Best Reply" award count is 100 or more.

  • laracasts-sensei Created with Sketch.

    Laracasts Sensei

    Earned once your experience points passes 1 million.

  • top-50 Created with Sketch.

    Top 50

    Earned once your experience points ranks in the top 50 of all Laracasts users.

Level 1
700 XP
Sep
02
1 month ago
Activity icon

Started a new Conversation HTML Input Array Not Working

So i have this section of my form that is supposed to be an input array. Upon clicking the add button, another box is show to collect the data. When submitting to database, only the data of the first input box is processed. It is treated as a single input box instead of an array of input elements.

Form Section Containing implementation.

<h3>Requirements</h3>
                                <section>
                                    <div class="form-group row mb-3">
                                        <label class="col-md-2 col-form-label" for="requirements">Requirements<span class="tx-danger">*</span></label>
                                        <div class="col-md-10">
                                            <div id = "requirement_area">
                                                <div class="d-flex mt-2">
                                                    <div class="flex-grow-1 px-3">
                                                        <div class="form-group">
                                                            <input type="text" class="form-control" name="requirements[]" id="requirements" placeholder="Provide requirements">
                                                        </div>
                                                    </div>
                                                    <div class="">
                                                        <button type="button" class="btn btn-success" style="" name="button" onclick="appendRequirement()"> <i class="fa fa-plus"></i> </button>
                                                    </div>
                                                </div>
                                                <div id = "blank_requirement_field">
                                                    <div class="d-flex mt-2">
                                                        <div class="flex-grow-1 px-3">
                                                            <div class="form-group">
                                                                <input type="text" class="form-control" name="requirements[]" id="requirements" placeholder="Provide requirements">
                                                            </div>
                                                        </div>
                                                        <div class="">
                                                            <button type="button" class="btn btn-danger" style="margin-top: 0px;" name="button" onclick="removeRequirement(this)"> <i class="fa fa-minus"></i> </button>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </section>
                                <h3>Outcomes</h3>
                                <section>
                                    <div class="form-group row mb-3">
                                        <label class="col-md-2 col-form-label" for="outcomes">Outcomes<span class="tx-danger">*</span></label>
                                        <div class="col-md-10">
                                            <div id = "outcomes_area">
                                                <div class="d-flex mt-2">
                                                    <div class="flex-grow-1 px-3">
                                                        <div class="form-group">
                                                            <input type="text" class="form-control" name="outcomes[]" id="outcomes" placeholder="Provide expected outcomes">
                                                        </div>
                                                    </div>
                                                    <div class="">
                                                        <button type="button" class="btn btn-success" style="" name="button" onclick="appendOutcome()"> <i class="fa fa-plus"></i> </button>
                                                    </div>
                                                </div>
                                                <div id = "blank_outcome_field">
                                                    <div class="d-flex mt-2">
                                                        <div class="flex-grow-1 px-3">
                                                            <div class="form-group">
                                                                <input type="text" class="form-control" name="outcomes[]" id="outcomes" placeholder="Provide expected outcomes">
                                                            </div>
                                                        </div>
                                                        <div class="">
                                                            <button type="button" class="btn btn-danger" style="margin-top: 0px;" name="button" onclick="removeOutcome(this)"> <i class="fa fa-minus"></i> </button>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </section>

JS to append input desired box

<script type="text/javascript"> 
    var blank_outcome = $('#blank_outcome_field').html();
    var blank_requirement = $('#blank_requirement_field').html();
    $(document).ready(function() {
        $('#blank_outcome_field').hide();
        $('#blank_requirement_field').hide();
    });
    function appendOutcome() {
        $('#outcomes_area').append(blank_outcome);
    }
    function removeOutcome(outcomeElem) {
        $(outcomeElem).parent().parent().remove();
    }

    function appendRequirement() {
        $('#requirement_area').append(blank_requirement);
    }
    function removeRequirement(requirementElem) {
        $(requirementElem).parent().parent().remove();
    }
</script>

Ajax Implementation for form submission

<script type="text/javascript">
    var quill = new Quill('#course_description', {
        theme: 'snow',
    });
    var description = quill.getContents();
    var course_description = description.opts;

    /*var arr_req = $("input[name='requirements[]']").map(function() {
        return this.value;
    }).get();

    var arr_out = $("input[name='outcomes[]']").map(function() {
        return this.value;
    }).get();

    var requirements = [];
    $( "input[name='requirements']" ).each(function() {
        requirements.push($( this ).val());
    });

    var outcomes = [];
    $( "input[name='outcomes']" ).each(function() {
        outcomes.push($( this ).val());
    }); */

    $('#wizard1').steps({
		headerTag: 'h3',
		bodyTag: 'section',
		autoFocus: true,
		titleTemplate: '<span class="number">#index#<\/span> <span class="title">#title#<\/span>',
        onFinishing: function (event, currentIndex){
            
            $.ajax({
                type : 'POST',
                url  : "{{route('courses.store')}}",
                headers: {
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                },
                data:{
                    'title':$('#course_title').val(),
                    'short_description':$('#short_description').val(),
                    'course_description': course_description,
                    'level':$('#level').val(),
                    'language_made_in':$('#language_made_in').val(),
                    'is_top_course':$('#is_top_course').val(),
                    'requirements':$('#requirements').val(),
                    'outcomes':$('#outcomes').val(),
                    'course_overview_provider':$('#course_overview_provider').val(),
                    'course_overview_url':$('#course_overview_url').val(),
                    'course_thumbnail':$('#course_thumbnail').val(),
                    'meta_keywords':$('#meta_keywords').val(),
                    'meta_description':$('#meta_description').val(),
                    'is_free_course':$('#is_free_course').val(),
                    'price':$('#price').val(),
                    'discount_flag':$('#discount_flag').val(),
                    'discounted_price':$('#discounted_price').val(),
                },
                success:function(response){
                    if(response.success){
                        swal({
                            title: response.message,                                
                            type: "success"
                            }, function() {
                                location.href = "{{route('courses.index')}}";
                        });
                    } 
                },
                error:function(error){
                    swal({
                        title: "An Error Occured",
                        text: "Please Check Data and Try again.",
                        type: "error"
                        }, function() {
                            location.reload();
                    });
                    console.log(error)
                } 
            });
            event.preventDefault();
        }
	});
</script>
Aug
28
1 month ago
Activity icon

Replied to "Class 'illuminate\Foundation\Http\FormRequest' Not Found"

I didn't realize that, Thanks.

Activity icon

Started a new Conversation "Class 'illuminate\Foundation\Http\FormRequest' Not Found"

I'm getting a "Class 'illuminate\Foundation\Http\FormRequest' not found" even when it is properly called on my

Error Message

responseJSON:
exception: "Error"
file: "/Applications/XAMPP/xamppfiles/htdocs/EduAfrique/app/Http/Requests/StoreCourseRequest.php"
line: 8
message: "Class 'illuminate\Foundation\Http\FormRequest' not found"

StoreCourseRequest.php

<?php
namespace App\Http\Requests;

use Illuminate\Support\Facades\Gate;
use illuminate\Foundation\Http\FormRequest;
use Symfony\Component\HttpFoundation\Response;

class StoreCourseRequest extends FormRequest {
    public function authorize(){
        abort_if(Gate::denies('course_create'), Response::HTTP_FORBIDDEN, '403 Forbidden');

        return true;
    }

    public function rules(){
        return [
            'course_title' => [
                'required',
                'unique:courses',
            ],
            'short_description' => [
                'required',
                'max:255',
            ],
            'outcomes.*' =>[
                'integer',
            ],
            'outcomes' => [
                'array',
            ],
            'language' => [
                'required',
            ],
            'sub_category_id' => [
                'integer',
                'required',
            ],
            'requirements.*' => [
                'integer',
            ],
            'requirements' => [
                'array',
            ],
            'course_thumbnail' => [
                'required',
            ],
        ];
    }
}

Here is the Ajax call code.

<script type="text/javascript">
    var quill = new Quill('#course_description', {
        theme: 'snow',
    });
    var description = quill.getContents();
    var course_description = description.opts;

    $('#wizard1').steps({
		headerTag: 'h3',
		bodyTag: 'section',
		autoFocus: true,
		titleTemplate: '<span class="number">#index#<\/span> <span class="title">#title#<\/span>',
        onFinishing: function (event, currentIndex){
            
            $.ajax({
                type : 'POST',
                url  : "{{route('courses.store')}}",
                headers: {
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                },
                data:{
                    'course_title':$('#course_title').val(),
                    'shor_description':$('#short_description').val(),
                    'course_description': course_description,
                    'sub_category_id':$('#sub_category_id').val(),
                    'level':$('#level').val(),
                    'language_made_in':$('#language_made_in').val(),
                    'is_top_course':$('#is_top_course').val(),
                    'requirements':$('#requirements').val(),
                    'outcomes':$('#outcomes').val(),
                    'course_overview_provider':$('#course_overview_provider').val(),
                    'course_overview_url':$('#course_overview_url').val(),
                    'course_thumbnail':$('#course_thumbnail').val(),
                    'meta_keywords':$('#meta_keywords').val(),
                    'meta_description':$('#meta_description').val(),
                    'is_free_course':$('#is_free_course').val(),
                    'price':$('#price').val(),
                    'discount_flag':$('#discount_flag').val(),
                    'discounted_price':$('#discounted_price').val(),
                },
                success:function(response){
                    if(response.success){
                        swal({
                            title: response.message,                                
                            type: "success"
                            }, function() {
                                location.href = "{{route('courses.index')}}";
                        });
                    } 
                },
                error:function(error){
                    swal({
                        title: "An Error Occured",
                        text: "Please Check Data and Try again.",
                        type: "error"
                        }, function() {
                            location.reload();
                    });
                    console.log(error)
                } 
            });
            event.preventDefault();
        }
});
</script>
Aug
24
2 months ago
Activity icon

Replied to AJAX Unprocessable Entity / Invalid Data

If you could please explain why that worked and other options didn't. I thought that was only made to pass single data not an array.

Activity icon

Replied to AJAX Unprocessable Entity / Invalid Data

Below is the code

<script type="text/javascript">
    $(".editRole").click(function(e){
        e.preventDefault();

        var role_id = $(this).data("id");

        /*var permissions = new Array();
        $("input[name^='permissions[]']").each(function() {
            permissions.push($(this).val());
        });*/
        
        swal({
            title: 'Are you Sure?',
            type: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#D9534F',
            confirmButtonText: 'Yes, Update Role',
            showLoaderOnConfirm: true,
        }, function(){
            $.ajax({
                type : 'PUT',
                url  : '/admin/roles/'+role_id,
                headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                },
                data:{
                    'title'         :   $('#title').val(),
                    'permissions'   :   $('#permissions').val().serialize(),
                },
                success:function(response){
                    if(response.success){
                        swal({
                            title: response.message,                                
                            type: "success"
                            }, function() {
                               location.reload();
                        });
                    } 
                },
                error:function(error){
                    swal({
                        title: "An Error Occured",
                        text: "Please Try again.",
                        type: "error"
                        }, function() {
                            location.reload();
                    });
                    console.log(error)
                } 
            });
        });
    });
</script>

Controller Code

public function update(UpdateRoleRequest $request, Role $role)
    {
        $role->update($request->all());
        $role->permissions()->sync($request->input('permissions', []));

        $message = 'Role Updated Successfully';
        return response()->json([
            'success' => true,
            'message' => $message,
        ]);
    }

UpdateRoleRequest

<?php
namespace namespace/namspace

class UpdateRoleRequest extends FormRequest {
    public function authorize() {
        abort_if(Gate::denies('role_edit'), Response::HTTP_FORBIDDEN, '403 Forbidden');

        return true;
    }

    public function rules() {
        return [
            'title' => [
                'required',
            ],
            'permissions.*' => [
                'integer',
            ],
            'permissions' => [
                'required',
                'array',
            ],
        ];
    }
}
Activity icon

Replied to AJAX Unprocessable Entity / Invalid Data

$('#permissions').val().serialize() not a function error

Aug
23
2 months ago
Activity icon

Started a new Conversation AJAX Unprocessable Entity / Invalid Data

Hi guys, so i'm using ajax to update a record in my database. The input block is as follows

<select name="permissions[]" id="permissions" multiple="multiple" class="form-control select2" style="width: 100%">
	@foreach($permissions as $id => $permissions)
         	<option value="{{ $id }}" {{ (in_array($id, old('permissions', [])) || isset($role) && $role->permissions->contains($id)) ? 'selected' : '' }}>{{ $permissions }}</option>
         @endforeach
</select>

When trying to pass the input array to ajax via

$('#permissions').serialize()

Error message says Must be an array

Also JSON.stringify() doesn't work

Aug
18
2 months ago
Activity icon

Started a new Conversation Dashboard Redirect DB Constraint Error

So i have defined roles and permissions for users and would love to redirect each user to a different dashboard after login based on their roles. However, i receive a constraint error while trying to redirect the users.

When i define the relationship as many-to-many, i get the below error.

App\User::isSuperAdmin must return a relationship instance.

And when i define the relationship as one-to-many, i get the below error.

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'roles.user_id' in 'where clause' (SQL: select * from `roles` where `roles`.`user_id` = 1 and `roles`.`user_id` is not null limit 1) 

I have a Roles and Permissions Table. I also have a Role_User Pivot table which i have used to sync the roles to the user.

My user model has these to identify user role

public function roles(){
	return $this->belongsToMany(Role::class);
}

public function isSuperAdmin(){
	return $this->roles->contains(1);
}

I call the isSuperAdmin method in the login controller when i override the redirectTo Method like this

public function redirectTo(){

        if( Auth::user()->isSuperAdmin || Auth::user()->isAdmin ){
            return redirect()->route('/admin/dashboard');
        }
}

Despite these, i still get the error.

Jun
10
4 months ago
Activity icon

Replied to Eloquent Query For Array

Thanks buddy.

Activity icon

Replied to Eloquent Query For Array

I know that sir. However it says children property of collection instance doesn't exist despite the fact that it does exist.

Activity icon

Replied to Eloquent Query For Array

Thanks Michael, i should have thought of that. However, i still have errors. Please find below the complete codes

Category Model

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Category extends Model
{
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'code', 'name','parent_id', 'slug', 'thumbnail',
     ];

     public function children()
    {
        return $this->hasMany(Category::class, 'parent');
    }

    public function parent()
    {
        return $this->belongsTo(Category::class, 'parent');
    }

}

Controller Logic

<?php

namespace App\Http\Controllers\Admin;
use App\Category;

use App\Http\Controllers\Controller;
use Cocur\Slugify\Slugify;
use Illuminate\Http\Request;

class CategoryController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $categories = Category::with('children')->whereNull('parent_id')->orderBy('name', 'ASC')->get();
        return view('categories')->with('categories', $categories);
    }

Blade Template

<div class="row">
            @if(!empty($categories))
                @foreach($categories as $category)
                <div class="col-sm-12 col-lg-6 col-xl-4">
                    <div class="card card-img-holder">
                        <div class="card-body list-icons">
                            <div class="clearfix">
                                <img src="{{asset('images/categoryThumbnails/'.$category->thumbnail)}}" alt="{{ $category->name }}" title="{{ $category->name }}" width="400" height="255">
                                <h4>{{ $category->name }}</h4>
                            </div>
                            <div class="card-footer p-0">
                                @foreach($categories->children as $subcategory)
                                <p class="text-muted mb-0 pt-4">{{ $subcategory->name }}</p>
                                @endforeach
                            </div>
                        </div>
                    </div>
                </div>
                @endforeach
            @else
                <h4>No Categories Added Yet.</h4>
            @endif
        </div>

Despite all these i still get the

Property [children] does not exist on this collection instance. (View: /Applications/XAMPP/xamppfiles/htdocs/demoProject/resources/views/categories.blade.php)
Activity icon

Replied to Eloquent Query For Array

@michaloravec i have done as suggested however i'm only able to access the child categories. I would like that it shows the parent category as and optgroup element and then the subcategories as options under it.

That is

----->Parent Category Name
	->Subcategory 1
	->Subcategory 2 etc
Jun
03
4 months ago
Activity icon

Replied to Eloquent Query For Array

How so sir, a subcategory can only belong to one parent category. That's the implementation as per my use case

Activity icon

Replied to Eloquent Query For Array

Thanks for the help. However, i'd love it if you could explain the inner workings of this query, finally, the query returns that the subcategory belongs to all parent category, rather than just the one for which the parent_id is specified.

That is, I have Cars, Bikes, Bicycle as parent categories, I have just a Toyota belonging to Cars Category, however it Toyota shows as subcategory for Bikes, Bicycles as well.

Activity icon

Started a new Conversation Eloquent Query For Array

I have a table structure as defined below

id		code		name			parent_id
1		oj8h4rd		Parent Category 1		0		
2		hg64g3		Sub Category 1		1
3		hwfhjf47	Parent Category N		0
4		kffh4jhw	Parent Category O		0
5		jhs4g3g3	Sub Category 2		3
6		hf373g53	Sub Category 3		3

How do i write an eloquent query do show sub categories of belonging to a particular parent category. e.g Parent category 1 has Sub Category 1

Apr
30
5 months ago
Activity icon

Started a new Conversation SymfonyThe POST Method Is Not Supported For This Route. Supported Methods: GET, HEAD.

Currently have an error on my route

The POST method is not supported for this route. Supported methods: GET, HEAD.

Controller Function

public function i_T(Request $request){

        $iT = new Profile();
        $iT->user_id = Auth::user()->id;
        $iT->f_name = $request->f_name;
        $iT->l_name = $request->l_name;
        $iT->city = $request->city;
        $iT->state = $request->state;
        $iT->save()

        return redirect()->back();
    }

Route

Route::post('/save-profile', '[email protected]_T');