FallOutBoi

FallOutBoi

Member Since 7 Months Ago

Experience Points
2,100
Total
Experience

2,900 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
1
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] 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
2,100 XP
Feb
12
1 week ago
Activity icon

Replied to Loop Through Query Items Before Paginating

Just client thing, it was written like this before i don't want to change too much stuff

Activity icon

Started a new Conversation Loop Through Query Items Before Paginating

Hey guys i have an array like this

'A52D4F3A-1236-4E35-A452-B948E5A33521' : "Effective"
'77DC1BE4-9B38-4926-B5B9-B0850A592B8B' : "Effective"
'CEA780EB-E293-4649-8419-759F0BBC66D0' : "Effective"
'56CA0131-2169-4CE8-AF37-1C6E0560BE35' : "Effective"
'516F7FDB-6272-4A00-9846-96B1E8943C46' : "Effective"
'3476636B-E8D3-4FFA-B628-DBF1693A4BB5' : "Effective"
'B1EB10F7-180E-4683-9384-5F8F614FE487' : "Effective"
'1307C4E9-B096-495F-9516-B590B29E03C3' : "Effective"
'E67A0E52-F714-415B-9F1A-9232A0E15EF6' : "Effective"
'31DAF9BC-0A2A-4678-A2CA-FE0369D5C2D6' : "Effective"
'0ED51C0D-BE22-40FF-A091-822C95728F07' : "Effective"

These are ids of a table called ssv_background_informations. The problem is that i want to run the query and assign the scores based on their id and possibly paginate the results. But i just don't know how to do it. This is my query

$ssv =  Db::table('ssv_background_informations as ssv')
  ->leftJoin('lgas as l', 'l.id', '=', 'ssv.lga_id')
  ->leftJoin('users as u', 'ssv.user_sso_id', '=', 'u.id')
  ->leftJoin('users as u2', 'ssv.creator_user_id', '=', 'u2.id')
  ->leftJoin('schools', 'schools.id', '=', 'ssv.school_id')
  ->select(
    'ssv.*',
    'l.name as lga_name',
    DB::raw("CONCAT(u2.first_name,' ',u2.last_name)  AS creator_user_name"),
    'schools.name as school_name',
    DB::raw("CONCAT(u.first_name,' ',u.last_name)  AS user_sso_name")
  )
  ->whereIn('ssv.lga_id', $lgas)
  ->orderBy('ssv.created_at', 'Desc')
  ->paginate(request(config('app.pagination_query_param'), config('app.pagination_size')));

This is the data

        +"id": "AB36F85B-AFA1-43B9-BEB0-9DCF45333515"
        +"created_at": "2020-02-12 11:45:50"
        +"updated_at": "2020-02-12 11:45:50"
        +"deleted_at": null
        +"lga_id": "071D7D86-4229-35E4-B7E5-33DB226958F2"
        +"user_sso_id": "E46C51F6-E66A-4202-9AB3-AEF4A7532A44"
        +"creator_user_id": "66D70A1A-8ED8-47B0-B12D-2AAD7134DECD"
        +"school_id": "90079F9C-5CC9-4320-8EFB-4DCFF3415812"
        +"head_teacher": "E6470006-B248-405D-BAC1-FCD81A8E24D8"
        +"school_code": null
        +"date": "2020-02-12 00:00:00"
        +"teacher_present": "0"
        +"ssv_count": 5
        +"ssv_submitted": "4"
        +"planned_ht": "0"
        +"hours_spent": 4
        +"feedback_do_well": ""[CE2B151B-2B48-3803-94B6-797D43C41CC2, 2C034265-0DBE-39E8-8176-AE0399F90573, 9DEC42D7-D258-3B10-A5A9-99036560D07B]""
        +"feedback_needs_improve": "[2415D163-9AF7-39FB-A099-554A8E518F30]"
        +"feedback_further_needs_improve": "[0E815DC4-837F-31B6-AD09-D35F215F5000]"
        +"school_year_id": null
        +"school_term_id": null
        +"elv": null
        +"lat": null
        +"lng": null
        +"lga_name": "name"
        +"creator_user_name": "name"
        +"school_name": "school"
        +"user_sso_name": "name"

i want to add another field into the data like 'overall_score=>effective'. Can anyone help me with this please?

Feb
11
1 week ago
Activity icon

Started a new Conversation Laravel 4.2 Nest Single Rows Items

I am trying to build a query where i can nest the ids inside one schools object like so,

$marketers = DB::table('user')
      ->leftJoin('marketer_schools', 'user.id', '=', 'marketer_schools.user_id')
      ->leftJoin('user_role as ur', 'ur.user_id', '=', 'user.id')
      ->leftJoin('role as r', 'r.id', '=', 'ur.role_id')
      ->where('r.name', 'Marketer')
      ->select(
        'user.id',
        DB::raw('CONCAT (first_name, " " , middle_name, " " , last_name) as name'),
        'marketer_schools.school_id'
      )
      ->get();

The table marketer_schools has id, user_id and school_id, the rows can be repeated for a single user meaning that a single user can be assigned to multiple schools. This is what the dumped data looks like

array (size=7)
  0 => 
    object(stdClass)[6672]
      public 'id' => int 50801
      public 'name' => string 'sifojesoifj Adwadwa seoifjseoi' (length=30)
      public 'school_id' => int 31
  1 => 
    object(stdClass)[6669]
      public 'id' => int 50803
      public 'name' => string 'awdawdwad sehaoifheoif oiehafoiw' (length=32)
      public 'school_id' => int 31
  2 => 
    object(stdClass)[6671]
      public 'id' => int 50804
      public 'name' => string 'marketer Two Test' (length=17)
      public 'school_id' => int 31
  3 => 
    object(stdClass)[6670]
      public 'id' => int 50804
      public 'name' => string 'marketer Two Test' (length=17)
      public 'school_id' => int 28
  4 => 
    object(stdClass)[6673]
      public 'id' => int 50804
      public 'name' => string 'marketer Two Test' (length=17)
      public 'school_id' => int 4
  5 => 
    object(stdClass)[6674]
      public 'id' => int 50803
      public 'name' => string 'awdawdwad sehaoifheoif oiehafoiw' (length=32)
      public 'school_id' => int 3
  6 => 
    object(stdClass)[6675]
      public 'id' => int 50801
      public 'name' => string 'sifojesoifj Adwadwa seoifjseoi' (length=30)
      public 'school_id' => int 7

But how can i make it like this

  1 => 
    object(stdClass)[6669]
      public 'id' => int 50803
      public 'name' => string 'awdawdwad sehaoifheoif oiehafoiw' (length=32)
      public 'school' => [
      0 => '4',
      1 => '5',
      2 => '31'
      ]
Feb
04
2 weeks ago
Activity icon

Awarded Best Reply on MethodNotAllowedHttpException

My apologies, the url was wrong when i was sending! instead of https there was http. It started working afterwards.

Activity icon

Replied to MethodNotAllowedHttpException

My apologies, the url was wrong when i was sending! instead of https there was http. It started working afterwards.

Activity icon

Started a new Conversation MethodNotAllowedHttpException

Hi guys, i am trying to generate an access coin with oauth2 and i am getting an error MethodNotAllowedHttpException in RouteCollection.php line 218:. Here's the routes

Route::post('oauth/access_token', function() {
    return Response::json(Authorizer::issueAccessToken());
});


Route::group(['prefix'=>'api','before' => 'oauth'], function(){

    Route::post('test', function(Request $request) {
        $user_id=Authorizer::getResourceOwnerId(); // the token user_id
        $user=\App\User::find($user_id);// get the user data from database
        return Response::json($user);
    });

});

The routes are in place with post parameter, but when i use that method on oauth/access i get the error. I am using ucadegasperi/oauth2-server-laravel package for this. I have no idea what's going on.

Dec
24
1 month ago
Activity icon

Started a new Conversation Monetizing Pages

Hi guys, i am kinda stuck on trying to find a way to build a middleware which will check if the url corresponds to the table item if so it should redirect to the payment page. My monetized_pages table looks like this

|id|    url    | price
|1 |   /index  | 2500

The problem is that some urls can contain parameters such as /index/esf46es84ga68e4wf684wae/show. What can i insert in my database in that case and possibly to compare it. I was thinking about using LIKE but it would also return some items that have the same word in them.

Dec
06
2 months ago
Activity icon

Replied to Method Illuminate\Database\Eloquent\Collection::paginate Does Not Exist.

The pagination parameters are

    'pagination_size' => env('PAGINATION_SIZE', 50),

    'pagination_query_param' => env('PAGINATION_QUERY_PARAM', 'limit'),
Activity icon

Replied to Method Illuminate\Database\Eloquent\Collection::paginate Does Not Exist.

Teacher.php 

<?php

namespace Core\Repositories\Teachers;

use Core\Core\Traits\DepartmentScopeTrait;
use Core\Core\Traits\Uuids;
use Core\Repositories\Files\File;
use Core\Repositories\Lgas\Lga;
use Core\Repositories\States\State;
use Core\Repositories\TeacherContactInformations\TeacherContactInformation;
use Core\Repositories\TeacherInserviceTrainings\TeacherInserviceTraining;
use Core\Repositories\TeacherMotivations\TeacherMotivation;
use Core\Repositories\TeacherQualifications\TeacherQualification;
use Core\Repositories\TeacherRecordOfServices\TeacherRecordOfService;
use Core\Repositories\TeacherStatuses\TeacherStatus;
use Core\Repositories\TeacherSubjectTaughts\TeacherSubjectTaught;
use Core\Repositories\TeacherTitles\TeacherTitle;
use Core\Repositories\TeacherWorkInformations\TeacherWorkInformation;
use Core\Services\Import\ImportableInterface;
use Core\Services\Import\ImportTrait;
use EloquentFilter\Filterable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Core\Repositories\HtBackgroundInformations\HtBackgroundInformation;

class Teacher extends Model implements ImportableInterface
{
    use SoftDeletes;
    use Filterable;
    use Uuids;
    use DepartmentScopeTrait;
    use ImportTrait {
        parseImport as teacherParseImport;
    }


    /**
     * The primary key for the model.
     *
     * @var string
     */
    protected $primaryKey = 'id';

    /**
     * Indicates if the IDs are auto-incrementing.
     *
     * @var bool
     */
    public $incrementing = false;

    /**
     * Table name
     *
     * @var string
     */
    protected $table = 'teachers';

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'psn',
        'first_name',
        'last_name',
        'middle_name',
        'maiden_name',
        'sex',
        'nationality_id',
        'birth_date',
        'note',
        'photo_file_id',
        'teacher_status_id',
        'marital_status_id',
        'teacher_title_id',
        'religion_id',
        'state_id',
        'lga_id',
        'school_id',
        'department_id',
    ];

    /**
     * The accessors to append to the model's array form.
     *
     * @var array
     */
    protected $appends = [
        'full_name',
    ];

    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    // protected $casts = [
    //     'birth_date' => 'date',
    // ];

    /**
     * Columns can be imported
     *
     * @var array
     */
    protected $importHeaders = [
        'psn' => 'PSN',
        'first_name' => 'First name',
        'last_name' => 'Last name',
        'middle_name' => 'Middle name',
        'maiden_name' => 'Maiden name',
        'sex' => 'Sex',
        'nationality' => 'Nationality',
        'birth_date' => 'Birth date',
        'teacher_status' => 'Status',
        'marital_status' => 'Marital status',
        'teacher_title' => 'Title',
        'religion' => 'Religion',
        'state' => 'State',
        'lga' => 'LGA',
        'school' => 'School code',
    ];

    /**
     * Import enums
     *
     * @var array
     */
    protected $importEnums = [
        'nationality' => [
            'column' => 'nationality_id',
            'relation' => 'nationalities',
        ],
        'teacher_status' => [
            'column' => 'teacher_status_id',
            'relation' => 'teacher_statuses',
        ],
        'marital_status' => [
            'column' => 'marital_status_id',
            'relation' => 'marital_statuses',
        ],
        'teacher_title' => [
            'column' => 'teacher_title_id',
            'relation' => 'teacher_titles',
        ],
        'religion' => [
            'column' => 'religion_id',
            'relation' => 'religions',
        ],
        'state' => [
            'column' => 'state_id',
            'relation' => 'states',
        ],
        'lga' => [
            'column' => 'lga_id',
            'relation' => 'lgas',
        ],
        'school' => [
            'column' => 'school_id',
            'relation' => 'schools',
        ],
    ];

    /**
     * Parse teacher import
     *
     * @param $values
     * @param $headers
     * @return $this|mixed
     */
    public function parseImport($values, $headers)
    {
        // Parse teacher columns
        $this->teacherParseImport($values, $headers);


        // Parse contact info columns
        $contactInfo = new TeacherContactInformation;
        $contactInfo->parseImport($values, $headers);

        if ($contactInfo->isDirty()) {
            $this->setRelation('teacherContactInformation', $contactInfo);
        }


        // Parse work info columns
        $workInfo = new TeacherWorkInformation;
        $workInfo->parseImport($values, $headers);

        if ($workInfo->isDirty()) {
            $this->setRelation('teacherWorkInformation', $workInfo);
        }
        return $this;
    }

    /**
     * Model filter
     *
     * @return \EloquentFilter\ModelFilter
     */
    public function modelFilter()
    {
        return $this->provideFilter(TeachersFilter::class);
    }

    static public function split($teachers)
    {
        //Split full_name for parts and saving in db first_name last_name
//        foreach($teachers as $teacher)
//        {
//            $first_name = explode(' ', $teacher->first_name);
//            $last_name = explode(' ', $teacher->last_name);
//            (isset($last_name)) ? $last_name = array_pop($last_name) : $last_name = array_pop($last_name);
//            ($first_name) ? $first_name = array_shift($first_name) : $first_name = array_shift($first_name);

//            if($teacher->middle_name) {
//                $last_name = $teacher->middle_name;
//            }

//            \DB::table('teachers')->where('id', $teacher->id)->update(
//            self::where('id', $teacher->id)->update(
//                [
//                    'first_name' => $first_name,
//                    'last_name' => $last_name,
  //              ]
 //           );
//        }
    }


    /**
     * @return string
     */
    public function getFullNameAttribute()
    {
        return "{$this->first_name} {$this->last_name}";
    }

    /**
     * @return \Illuminate\Database\Eloquent\Relations\HasOne
     */
    public function teacherContactInformation()
    {
        return $this->hasOne(TeacherContactInformation::class);
    }

    /**
     * @return \Illuminate\Database\Eloquent\Relations\HasOne
     */
    public function teacherWorkInformation()
    {
        return $this->hasOne(TeacherWorkInformation::class);
    }

    /**
     * @return \Illuminate\Database\Eloquent\Relations\HasOne
     */
    public function photo()
    {
        return $this->hasOne(File::class, 'id', 'photo_file_id');
    }

    /**
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function state()
    {
        return $this->belongsTo(State::class);
    }

    /**
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function lga()
    {
        return $this->belongsTo(Lga::class);
    }

    /**
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function teacherTitle()
    {
        return $this->belongsTo(TeacherTitle::class);
    }

    /**
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function teacherStatus()
    {
        return $this->belongsTo(TeacherStatus::class);
    }

    /**
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function teacherQualifications()
    {
        return $this->hasMany(TeacherQualification::class);
    }

    /**
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function teacherSubjectTaughts()
    {
        return $this->hasMany(TeacherSubjectTaught::class);
    }

    /**
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function teacherInserviceTrainings()
    {
        return $this->hasMany(TeacherInserviceTraining::class);
    }

    /**
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function teacherRecordOfService()
    {
        return $this->hasMany(TeacherRecordOfService::class);
    }

    /**
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function teacherMotivations()
    {
        return $this->hasMany(TeacherMotivation::class);
    }
    public function htBackgroundInformation()
    {
        return $this->hasMany(HtBackgroundInformation::class);
    }

}
EloquentTeachersRepository.php

<?php

namespace Core\Repositories\Teachers;

use Carbon\Carbon;
use Core\Core\Traits\CountableTrait;
use Illuminate\Support\Facades\DB;
use Sa\Repositories\Core\RepositoryAbstract;

/**
 * Description of EloquentTeachersRepository
 *
 */
class EloquentTeachersRepository extends RepositoryAbstract implements TeachersRepository
{

    use CountableTrait;

    /**
     * Get model name
     *
     * @return string
     */
    public function model()
    {
        return Teacher::class;
    }

    /**
     * @param null $from
     * @param null $to
     * @param int $min
     * @return mixed
     */
    public function countTeachersWithInServiceTraining(Carbon $from = null, Carbon $to = null, int $min = 1)
    {
        $model = $this
            ->getModel()
            ->select(DB::raw('count(distinct teachers.id) as count'))
            ->leftJoin('teacher_inservice_trainings', function ($join) use ($from, $to) {
                $join->on('teacher_inservice_trainings.teacher_id', '=', 'teachers.id');

                if ($from) {
                    $join->where('teacher_inservice_trainings.date', '>=', $from->format(FORMAT_DATE));
                }

                if ($to) {
                    $join->where('teacher_inservice_trainings.date', '<=', $to->format(FORMAT_DATE));
                }

                $join->whereNull('teacher_inservice_trainings.deleted_at');
            })
            ->groupBy(['teachers.id'])
            ->havingRaw('count(teacher_inservice_trainings.id) >= ?', [$min]);

        return $model->get()->count() ?? 0;
    }

    /**
     * @param Carbon|null $from
     * @param Carbon|null $to
     * @return mixed
     */
    public function countTeachersReTrained(Carbon $from = null, Carbon $to = null)
    {
        return 0;
    }

    /**
     * Count unqualified teachers
     *
     * @param Carbon|null $from
     * @param Carbon|null $to
     * @return int|mixed
     */
    public function countTeachersUnqualified(Carbon $from = null, Carbon $to = null)
    {
        $model = $this
            ->getModel()
            ->select(DB::raw('count(distinct teachers.id) as count'))
            ->leftJoin('teacher_qualifications', function ($join) use ($from, $to) {
                $join->on('teacher_qualifications.teacher_id', '=', 'teachers.id');

                if ($from) {
                    $join->where('teacher_qualifications.qualification_year', '>=', $from->format('Y'));
                }

                if ($to) {
                    $join->where('teacher_qualifications.qualification_year', '<=', $to->format('Y'));
                }

                $join->whereNull('teacher_qualifications.deleted_at');
            })
            ->groupBy(['teachers.id'])
            ->havingRaw('count(teacher_qualifications.id) = 0');

        return $model->get()->count() ?? 0;
    }

    /**
     * Get teachers by psn numbers
     *
     * @param array|Collection $psnNumbers
     * @return mixed
     */
    public function getTeachersByPsn($psnNumbers)
    {
        return $this->getModel()
            ->whereIn('psn', $psnNumbers)
            ->get()
            ->keyBy('psn');
    }
}
Activity icon

Started a new Conversation Method Illuminate\Database\Eloquent\Collection::paginate Does Not Exist.

Hey guys, i am trying to run this simple query but its throwing Method Illuminate\Database\Eloquent\Collection::paginate does not exist. error.

My code goes like this

$teachers = $this->teachersRepository
  ->with(['state', 'lga', 'photo', 'teacherTitle'])
  ->where('first_name','!=', null)
  ->paginate(request(config('app.pagination_query_param'), config('app.pagination_size')));

What am i doing wrong?

Nov
27
2 months ago
Activity icon

Replied to Laravel AJAX 500 Internal Error With No Message

At the end i just changed this part of the code and it worked fine

 $s_standards = [];
            $s_sub_category = [];
            $all_subs = DB::table('lesson_observation_teacher_standard_categories')->pluck('name','id')->toArray();
            
            foreach ($sanitized_needs['standard'] as $skey => $standard) {
                $sname = DB::table('lesson_observation_teacher_standards')->where('id', $standard)->first()->name;
                // $sname = 'null';
                $s_standards[] = $sname;
                foreach ($sanitized_needs['sub_category'] as $key => $substandard) {
                    // $name = 'null';
                    $name = $all_subs[$substandard];
                    // $name = DB::table('lesson_observation_teacher_standard_categories')->where('id', $substandard)->first();
                    if ($key == $skey) {
                        $s_sub_category[$sname][] = $name;
                    }
                }
            }
Activity icon

Replied to Laravel AJAX 500 Internal Error With No Message

if (empty($decoded_needs)) {
            $training_needs_teacher = array(['0' => 'None']);
        } else {
            $sanitized_needs = [];
            foreach ($decoded_needs as $key => $items) {
                foreach ($items as $index => $item) {
                    foreach ($item as $name => $bit) {
                        $sanitized_needs[$name][] = $bit;
                    }
                }
            }
Activity icon

Replied to Laravel AJAX 500 Internal Error With No Message

Nothing in the log file too :(

Nov
25
2 months ago
Activity icon

Started a new Conversation Laravel AJAX 500 Internal Error With No Message

Hi everyone, I have built a report which is calculating complex numbers and i've used ajax. The code works perfectly on my localhost but on the server it throws 500 internal error with no message. I tried to use dd after each block of the code and it was this part where it throws the error

$decoded_needs = [];
  foreach ($needs_teacher as $needs) {
    $decoded_needs[] = json_decode($needs->training_needed);
  }
  if (empty($decoded_needs)) {
    $training_needs_teacher = array(['0' => 'None']);
  } else {
    $sanitized_needs = [];
    foreach ($decoded_needs as $key => $items) {
      foreach ($items as $index => $item) {
        foreach ($item as $name => $bit) {
          $sanitized_needs[$name][] = $bit;
        }
      }
    }
            
$s_standards = [];
$s_sub_category = [];

// dd() works here

foreach ($sanitized_needs['standard'] as $skey => $standard) {
  $sname = DB::table('lesson_observation_teacher_standards')->where('id', $standard)->first()->name;
  $s_standards[] = $sname;
    foreach ($sanitized_needs['sub_category'] as $key => $substandard) {
      $name = DB::table('lesson_observation_teacher_standard_categories')->where('id', $substandard)->first()->name;
       if ($key == $skey) {
         $s_sub_category[$sname][] = $name;
       }
    }
}
// but not here 
$training_needs_teacher = [];
foreach ($s_sub_category as $key => $index) {
  foreach ($index as $items) {
    $training_needs_teacher[$key] = array_count_values($index);
  }
}

$sanitized_needs = [];
foreach ($training_needs_teacher as $key => $items) {
  foreach ($items as $index => $item) {
    $sanitized_needs[$key . ":" . count($items)][] = $index . ":" . $item;
  }
}
$training_needs_teacher = $sanitized_needs;
}

I know i could have used WhereIn in many cases but i need the duplicate items. I just want to know if there's a way to fix this problem?

Nov
15
3 months ago
Activity icon

Started a new Conversation How To Merge Repeating Columns As Array?

Hey guys, I am trying to get all repeating columns into one column as array. But i right now it shows this way.

    0 => {#1776 ▼
      +"id": "XXXXX-XXX-XXXX-XXXXX-F70A47892AE8"
      +"first_name": "Areg"
      +"last_name": "Areg"
      +"email": "[email protected]"
      +"role": "school-support-officers"
      +"lga": null
    }

I want the LGA to be like so

+"lga": [
  1 : 'Lga 1'
  2 : 'Lga 2'
]

Here's the query where i join the table. Please note that users_lgas is many to many table where it connects a single user to multiple lgas. Right now this causes multiple repeating records when i really need it to be like an array where columns differ.

$users = DB::table('role_user')
          ->join('users', 'role_user.user_id', '=', 'users.id')
          ->join('roles', 'role_user.role_id', '=', 'roles.id')
          ->leftJoin('users_lgas', 'users_lgas.user_id', '=', 'users.id')
          ->leftJoin('lgas', 'lgas.id', '=', 'users_lgas.lga_id')
          ->where('department_id', $auth->department_id)
          ->select('users.id', 'users.first_name', 'users.last_name', 'users.email', 'roles.name as role', 'lgas.name as lga')
          ->get();

Any way i can achieve this?

Oct
30
3 months ago
Activity icon

Started a new Conversation Join Two Tables Without Repeating The Primary Table's Rows

Hey guys i have two tables like so

//trainings table
|id|training_name|
|1 | training one   |

and the participants table

|id|training_id|participant_info|
|1 |1|info|
|2 |1|info|
|3 |1|info|
|4 |1|info|

When i join these tables using

DB::table('trainings')->join('training_participant_info', 'trainings.id', '=', 'training_participant_info.training_id')->get();

I get 4 records in total but i want to use something like distinct on the participants table before joining them together so ill get one for each training. It doesn't matter which one of the participant table records will be left i just want a single record joining for every training. Note i am gonna do extra queries after that so i don't want to use distinct afterwards i just want to join both of them with single participant info.

Oct
29
3 months ago
Activity icon

Replied to Eloquent Simple Join Wont Work

It was connected to the old database *facepalm. I spent like two hours figuring this out :(

Activity icon

Started a new Conversation Eloquent Simple Join Wont Work

Hi guys, i am trying to do a simple table join like so

$t_effective = DB::table('training_participant_info as tpi')
  ->join('teachers as t', 't.psn', '=', 'tpi.teacher_psn')
  ->join('training_monitoring as tm', 'tm.training_id', '=', 'tpi.training_id')
  ->get();

But i get error like this

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'tm.training_id' in 'on clause' (SQL: select * from `training_participant_info` as `tpi` inner join `teachers` as `t` on `t`.`psn` = `tpi`.`teacher_psn` inner join `training_monitoring` as `tm` on `tm`.`training_id` = `tpi`.`training_id`)

The training_id is present on training_monitoring table. What am i doing wrong?

Oct
24
3 months ago
Activity icon

Started a new Conversation How Can I Properly Push Into A Collection?

Hi guys, i am trying to get a massive amounts of records while looping through an array. Right now the way data is collecting is

Collection {#2209 ▼
  #items: array:150 [▼
    0 => Collection {#2405 ▼
      #items: array:150 [▼
        0 => {#2403 …6}
        1 => {#2400 …6}
        2 => {#2397 …6}
        3 => {#2399 …6}
        4 => {#2402 …6}
        5 => {#2398 …6}
        6 => {#2401 …6}
        7 => {#2395 …6}
        8 => {#2394 …6}
        9 => {#2393 …6}
        10 => {#2392 …6}
        11 => {#2391 …6}
        12 => {#2390 …6}
        13 => {#2389 …6}
...

i want the child collection to be emitted so instead of 146 items above it will be 300 and no child collections. This is the way my code is right now.

  $schools = collect();
          foreach($lgas as $lga){
            $school = DB::table('schools')
            ->join('school_categories', 'schools.school_category_id', '=', 'school_categories.id')
            ->leftJoin('school_sub_categories', 'school_sub_categories.id', '=', 'schools.school_sub_category_id')
            ->join('addresses', 'addresses.id', '=', 'schools.address_id')
            ->select('schools.name',
            'schools.code',
            'school_categories.name as category_name',
            'school_sub_categories.name as sub_category_name',
            'schools.email',
            'schools.phone')
            ->where('addresses.lga_id', $lga)
            ->get();
            $schools->push($school);
          }

Is there any possible way that i can achieve that? Thanks in advance

Oct
22
3 months ago
Activity icon

Started a new Conversation How To Select Distinct Date By Day?

Hi guys, i am having a trouble here trying to get created_at from a database table. For example

2019-06-10 14:07:47
2019-06-10 15:07:47
2019-06-10 16:07:47
2019-06-10 17:07:47
2019-06-10 18:07:47

I have these dates inside my created_at column. I want to get distinct records based on the day.

$t = DB::table('table')
            ->where('created_at','>',$start_date)
            ->where('created_at','<',$end_date)
            ->distinct(?)
            ->first();

Any way i can achieve this?

Oct
19
4 months ago
Activity icon

Started a new Conversation Laravel Policy Is Not Working As Expected

Hello, i am trying to set a policy for users. Where only admin and author can use Post crud. Here's my User model where i check for the relationship.

//User.php

    public function isAdmin(){
      return $this->role->name == 'Admin' ? true : false;
    }

    public function role(){
      return $this->belongsTo(Role::class);
    }

    public function isAuthor(){
      return $this->role->name == 'Author' ? true : false;
    }

Here's the PostPolicy

<?php

namespace App\Policies;

use App\Post;
use App\User;
use Illuminate\Auth\Access\HandlesAuthorization;

class PostPolicy
{
    use HandlesAuthorization;


    /**
     * Determine whether the user can create posts.
     *
     * @param  \App\User $user
     * @return mixed
     */
    public function create(User $user)
    {
        if($user->isAuthor() || $user->isAdmin()) {
            return true;
        }else{
            return false;
        }
    }

    /**
     * Determine whether the user can update the post.
     *
     * @param  \App\User $user
     * @param  \App\Post $post
     * @return mixed
     */
    public function update(User $user, Post $post)
    {
        if($user->id === $post->user_id || $user->isAdmin()) {
            Response::allow();
        }else{
            Response::deny('Unauthorized Access');
        }
    }

    /**
     * Determine whether the user can delete the post.
     *
     * @param  \App\User $user
     * @param  \App\Post $post
     * @return mixed
     */
    public function delete(User $user, Post $post)
    {
        if($user->id === $post->user_id || $user->isAdmin()) {
            Response::allow();
        }else{
            Response::deny('Unauthorized Access');
        }
    }


}

I also have a Post model like so

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Webpatser\Uuid\Uuid;
use App\User;
use App\Comment;

class Post extends Model
{
    protected $casts = [
    'id' => 'string'
    ];
    protected $keyType = 'string';

    public $incrementing = false;

    public static function boot()
    {
        parent::boot();
        self::creating(
            function ($model) {
                $model->id = (string) Uuid::generate(4);
            }
        );
    }

    public function user()
    {
        return $this->belongsTo(User::class);
    }

    public function comments()
    {
        return $this->morphMany(Comment::class, 'commentable')->whereNull('parent_id')->orderBy('created_at', 'desc');
    }

    public function comment()
    {
      $this->morphedByMany('App\Post', 'commentable');
    }
}

But whenever i am trying to use the store action with ajax it return this message This action is unauthorized.

I even have it set up in my routes

//web.php

Route::middleware('auth')->group(function () {
  Route::post('/post', '[email protected]')->name('post.store')->middleware('can:create,post');

...

});

What am i doing wrong?

Oct
12
4 months ago
Activity icon

Replied to Return View As Json?

Thanks

Activity icon

Started a new Conversation Return View As Json?

Hi, i am trying to make an ajax call. I was just wondering is there a way to return view as json response with all the blade parsed. Thanks in advance

Oct
06
4 months ago
Activity icon

Replied to Last Inserted Record UUID Returns 0

I tried this instead and it worked. But i still wonder why i couldn't get the id.

$id = DB::table('posts')->latest('created_at')->first()->id;
dd($id);
Activity icon

Replied to Last Inserted Record UUID Returns 0

Post.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Webpatser\Uuid\Uuid;
use App\User;

class Post extends Model
{
    protected $casts = [
    'id' => 'string'
    ];

    public static function boot()
    {
        parent::boot();
        self::creating(
            function ($model) {
                $model->id = (string) Uuid::generate(4);
            }
        );
    }

    public function user(){
      return $this->belongsTo(User::class);
    }
}

Migration

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreatePostsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->uuid('id');
            $table->foreign('user_id')->references('id')->on('users');
            $table->char('user_id',36);
            $table->integer('likes')->default(0);
            $table->string('title');
            $table->longText('content');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('posts');
    }
}
Activity icon

Replied to Last Inserted Record UUID Returns 0

Added that and commented the cast, same result unfortunately

Activity icon

Started a new Conversation Last Inserted Record UUID Returns 0

Hi, I am trying to get the uuid of a row which i just inserted which is UUID. I am trying to get it like this

$post = new Post;
        $post->title = $request->title;
        $post->content = $request->content;
        $post->user_id = Auth::user()->id;
        $post->save();
        $data = [
          'post' => $post,
          'post_id' => $post->id,
          'user' => $post->user,
        ];

Whenever i try to insert the post->id on front end it shows 0. Same thing in here whenever i try to dd($post->id) it returns 0 again. I even casted the id to string inside the model like so

    protected $casts = [
    'id' => 'string'
    ];

The actual id looks like this

e2485f2d-8bc6-4c19-b895-0d9e3fa2881d
Activity icon

Replied to Laravel Mutator Not Working Correctly

I left it there for testing. Ignore that.

Oct
05
4 months ago
Activity icon

Started a new Conversation Laravel Mutator Not Working Correctly

Hello, i am trying to translate male and female by using mutators. I've added something like this in the User model

    public function getSexAttribute($gender)
    {
        if($gender == 'male') {
            return $this->gender = trans('registration.male');
        }else{
            return $this->gender = trans('registration.female');
        }
    }

But when i call it using

<li class="list-group-item">@lang('profile.gender') : {{$user->sex}}</li>

it returns male without translation. The table column name is gender but i want to have a seperate name for the mutator because sometimes i need to recieve the raw non translated data. Can someone please help me achieve this?

Oct
04
4 months ago
Activity icon

Started a new Conversation Custom Table Name Not Working On Many To Many Polymorphic Relationship

Hello, i am running into a problem when i am trying to save polymorphic relationship. It says SQLSTATE[42S02]: Base table or view not found: 1146 Table 'database.audit_trails' doesn't exist . I have set up the custom name inside the model like so

//AuditTrail.php
<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use App\BirthNotification;

class AuditTrail extends Model
{
  protected $table = 'audit_trail';

  public function bn()
  {
      return $this->morphedByMany(BirthNotification::class, 'audit_trail');
  }
}

Here's the second model

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use App\AuditTrail;

class BirthNotification extends Model
{
    protected $table = "birth_notification";

    public function audit()
    {
        return $this->morphToMany(AuditTrail::class, 'audit_trail');
    }
}

But for some reason it can't find the table by that name even though it exists.I am trying to insert into the model like this.

    $bn = BirthNotification::find($id);
    $bn->ba_status_id = $statusId;
        $bn->save();

        $trail = new AuditTrail;
        $trail->user_id = Auth::user()->id;
        $trail->auditable_id = $bn->id;
        $trail->auditable_type = 'App/BirthNotification';
        $trail->description = 'Birth Notification Update Status To' . $status_name[0];
        $trail->txn_date = $date;
        $trail->txn_time = $time;
        $bn->audit()->save($trail);

I also tried to run composer dump but still it didn't worked :( What am i doing wrong?