FallOutBoi

FallOutBoi

Member Since 5 Months Ago

Experience Points
1,880
Total
Experience

3,120 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
1,880 XP
Dec
06
1 week 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 weeks 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 weeks 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
4 weeks 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].com"
      +"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
1 month 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
1 month 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
1 month 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
1 month 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
1 month 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
2 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
2 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
2 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
2 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?

Aug
01
4 months ago
Activity icon

Started a new Conversation How To Just Join In Laravel?

Hey guys, i am trying to get a very complex set of records, when i do it in laravel it does inner join and i get identical values, but when i'm doing it on standard sql like this

SELECT * FROM departments 
JOIN role_user ON departments.id = role_user.department_id
JOIN roles ON role_user.role_id = roles.id
JOIN users ON role_user.user_id = users.id
JOIN lgas ON lgas.state_id = departments.state_id
WHERE lgas.id = "123-..."

It returns different amount of values in backend its something like this

$totalSsoCount = DB::table('departments')
                ->join('role_user as ru', 'departments.id', '=', 'ru.department_id')
                ->join('roles', 'ru.role_id','=', 'roles.id')
                ->join('users', 'ru.user_id', '=', 'users.id')
                ->join('lgas', 'lgas.state_id', '=', 'departments.state_id')
                ->where('lgas.id', $id)
                ->where('roles.display_name','SSO')
                ->where('departments.state_id', $state)
                ->count();

How can i just use join instead of standard laravel inner join?

Jul
18
4 months ago
Activity icon

Replied to Model Relationship Returns Error

Thanks guys

Activity icon

Replied to Model Relationship Returns Error

So wishlists belongs to many users and products?

Activity icon

Replied to Model Relationship Returns Error

Thanks alot

Activity icon

Started a new Conversation Model Relationship Returns Error

Hi, i have Product and Wishlist models. I have connected them with relationship but when i try to get all products for that wishlist it returns this

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

Here's my models

Product.php 

 public function wishlist()
 {
      return $this->belongsToMany(Wishlist::class); 
 }
Wishlist.php

public function products()
{
    return $this->hasMany(Product::class);
}

The database table for wishlists looks like this

id  user_id product_id  created_at  updated_at

I tried to change wishlist products method to belongsTo instead of belongsToMany but still the same thing.

Jul
17
4 months ago
Activity icon

Replied to Checking If Relation Exists In Blade

Thanks everyone!

Activity icon

Replied to Checking If Relation Exists In Blade

Yeah got it fixed by @mstrauss 's many to many relationship code

Activity icon

Replied to Checking If Relation Exists In Blade

Yes i did, thank you but i need to change the icons on blade accoring to relation. When i use

@if( $product->check())
   <i class="far fa-heart icon" id="{{$product->id}}"></i>
@else
  <i class="fas fa-heart icon" id="{{$product->id}}"></i>
@endif

Icons are the same

Activity icon

Replied to Checking If Relation Exists In Blade

$auth?? did you mean Auth::user()->itemOnWishlist($product->id) ????

Activity icon

Replied to Checking If Relation Exists In Blade

The first one keeps the same icon on all products, the second one says 'Method name must be a string'.

Activity icon

Started a new Conversation Checking If Relation Exists In Blade

Hi, i am trying to show different icon when user has specific item in wishlist but it doesnt work. I have relations set up like so

Product.php 

    public function wishlist()
    {
        return $this->belongsTo(Wishlist::class);
    }


    public function check($id)
    {
        return optional($this->wishlist()->select('product_id')->where('product_id', '=', $id)->first())->product_id;
    }
Wishlist.php 

    public function products()
    {
        return $this->hasMany(App\Product);
    }

Whenever i call check() and try to count it returns null.

 @if($product->check($product->id) == $product->id)
       <i class="far fa-heart icon" id="{{$product->id}}"></i>
@else
       <i class="fas fa-heart icon" id="{{$product->id}}"></i>
@endif

Table looks like this

id  user_id product_id  created_at  updated_at

What am i doing wrong?

Jul
12
5 months ago
Activity icon

Replied to Model Relationship Only One Column

@nakov Yeah thanks, its working fine

Activity icon

Replied to Model Relationship Only One Column

still the same thing unfortunately :(

Activity icon

Started a new Conversation Model Relationship Only One Column

Hi, i am trying to display an image which is connected to the Product model, i wrote a few lines like this

Product.php; 

    public function productImages(){
      return $this->hasMany(ProductImage::class);
    }
    public function primary() {
    return $this->productImages()->select('image')->where('primary','=', 1)->get();
}

ProductImage.php

  public function product()
  {
      return $this->belongsTo(Product::class);
  }

I am trying to display only the image which has primary column set to true.Like this

<img class="card-img-top" src="/product_images/{{$product->primary()}}" alt="Card image cap">

But it returns this

/product_images/[{"image":"91N5ovoYjoL._SL1500__1562936575.jpg"}]

How can i select only the value which has the filename?

Jul
10
5 months ago
Activity icon

Started a new Conversation Question About Dropzone Validation

Hi, im building a form with dropzone in it. I was wondering if i would not check images for validation can someone just change the maximum file size number in their browser and submit the form? The script is on the same page.

Jul
06
5 months ago
Activity icon

Replied to Method Differences?

Yeah, thanks

Activity icon

Started a new Conversation Method Differences?

I am kinda new can someone explain me the difference between put/patch,delete and post, get? Why these methods exist if i can just send using the standard POST and GET?

Activity icon

Replied to Show Form Sent Message After Redirect

Yeah i saw that i just wanted to for him to be clear that he can use it in whatever element he pleases.

Jul
05
5 months ago
Activity icon

Replied to Simulate A Mouse Clicks For An Alt

insert your script inside your page

Activity icon

Replied to Weird Function On Null Error

The problem is it should not enter the first if scope. Because the value of $request->input('subcategory') is null. But it does enter for whatever reason

Activity icon

Replied to Converting Laravel Form Collective To Normal HTML Form.

Should be

<form action="{{ route('categories.destroy', $category->id) }}" method="post" class="form-inline form-delete">
    @csrf
    @method('delete')

    <input type="hidden" name="id" value="{{ $category->id }}" />

    <button class="btn btn-xs btn-danger delete" name="delete_modal" type="submit">
        @lang('categories.delete')
    </button>
</form>
Activity icon

Replied to Show Form Sent Message After Redirect

If you want to show it only on one form just move

@if(session()->has('message'))
    <div class="alert alert-success">
        {{ session()->get('message') }}
    </div>
@endif

To your specified form div