iambaz

iambaz

Member Since 3 Years Ago

Experience Points 5,650
Experience Level 2

4,350 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 48
Lessons
Completed
Best Reply Awards 0
Best Reply
Awards
  • Start Your Engines Achievement

    Start Your Engines

    Earned once you have completed your first Laracasts lesson.

  • First Thousand Achievement

    First Thousand

    Earned once you have earned your first 1000 experience points.

  • One Year Member Achievement

    One Year Member

    Earned when you have been with Laracasts for 1 year.

  • Two Year Member Achievement

    Two Year Member

    Earned when you have been with Laracasts for 2 years.

  • Three Year Member Achievement

    Three Year Member

    Earned when you have been with Laracasts for 3 years.

  • Four Year Member Achievement

    Four Year Member

    Earned when you have been with Laracasts for 4 years.

  • Five Year Member Achievement

    Five Year Member

    Earned when you have been with Laracasts for 5 years.

  • School In Session Achievement

    School In Session

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

  • Welcome To The Community Achievement

    Welcome To The Community

    Earned after your first post on the Laracasts forum.

  • Full Time Learner Achievement

    Full Time Learner

    Earned once 100 Laracasts lessons have been completed.

  • Pay It Forward Achievement

    Pay It Forward

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

  • Subscriber Achievement

    Subscriber

    Earned if you are a paying Laracasts subscriber.

  • Lifer Achievement

    Lifer

    Earned if you have a lifetime subscription to Laracasts.

  • Laracasts Evangelist Achievement

    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 Achievement

    Chatty Cathy

    Earned once you have achieved 500 forum replies.

  • Laracasts Veteran Achievement

    Laracasts Veteran

    Earned once your experience points passes 100,000.

  • Ten Thousand Strong Achievement

    Ten Thousand Strong

    Earned once your experience points hits 10,000.

  • Laracasts Master Achievement

    Laracasts Master

    Earned once 1000 Laracasts lessons have been completed.

  • Laracasts Tutor Achievement

    Laracasts Tutor

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

  • Laracasts Sensei Achievement

    Laracasts Sensei

    Earned once your experience points passes 1 million.

  • Top 50 Achievement

    Top 50

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

31 Mar
2 years ago

iambaz started a new conversation Chain WhereHas To Traverse Through A Self-referencing Model

Imagine I have the following models:

App\Location

This has a self referencing hierarchy, and has the following data

UK
  |---North West
  |             |----Liverpool
  |             |----Manchester
  |---North East
                |----Newcastle
                |----Sunderland

In this model I have a self relation

public function parent()
{
    return $this->belongsTo('App\Location', 'location_id');
}

and a recursive relation...

public function parentRecursive()
{
   return $this->parent()->with('parentRecursive');
}

App\Shop

The shop model has a 'location' relation.

public function location()
{
    return $this->belongsTo('App\Location', 'location_id');
}

What I want to do is to get all of the shops within a category. So if I have a shop called "ACME" that is related to "Liverpool", I can easily get it by sending the ID for "Liverpool" (as $value) in the following condition....

->whereHas('location', function($q) use ($value) {
            $q->where('id', $value);
    })

But technically, this shop is also in "North West" and in "UK".

So if I send the ID for the UK Location to that query, it will not return the ACME shop as it is not directly related to North West or UK ID.

I can get it working by sending the UK id ($value) to this...

$this->builder->whereHas('location', function($q) use ($value) {
        $q->where('id', $value);
    })->orWhereHas('location.parent', function($q) use ($value) {
            $q->where('id', $value);
    })->orWhereHas('location.parent.parent', function($q) use ($value) {
            $q->where('id', $value);
    });

So is there a better way to write the above which is ugly and would only work for a finite number of 'jumps' in the relation tree. I need it to traverse all of the locations until it reaches the top of the tree.

13 Feb
2 years ago

iambaz left a reply on How To Use Auth Middleware In My Own Package

I worked this out - seems I had to add the web guard to the route group like so:

Route::group(['middleware' => ['web', 'auth']], function(){

    Route::get('/importer', '\Vendor\Package\Controllers\[email protected]');
    Route::post('/importer/import', '\Vendor\Package\Controllers\[email protected]');

});

iambaz started a new conversation How To Use Auth Middleware In My Own Package

I have created a new package with some custom routes. Within these routes I need to access the Auth::id(). I have wrapped the routes with the usual auth middleware like so:

Route::group(['middleware' => 'auth'], function(){

    Route::get('/importer', '\Vendor\Package\Controllers\[email protected]');
    Route::post('/importer/import', '\Vendor\Package\Controllers\[email protected]');

});

When I navigate to any of my routes, I am redirected to /home eve whilst logged in.

Do I need to register something in my package to set up the authentication environment?

09 Feb
2 years ago

iambaz started a new conversation Testing Arbitrary Models

I am creating a package which in its simplest form turns csv files into models and saves them to the database. Basically it looks at csv header rows and then maps them to a model and saves.

The API is something like this:

CsvToEloquent::model('App\Person')->file('test.csv')->import();

So the user explicitly tells the package what model user they're using.

How do I test something like this if it fundamentally depends on a eloquent model, but I can never know what model the client will inject?

I can set up some tests on my local machine and mock some of my own models to test easily, but then the test suite is coupled to my models, and other machines will not have the models I am testing with.

Maybe I can crete a test model as part of the test suite? But then I can't test the final result (data in the database) without running a migration which seems overkill for a test.

Any pointers appreciated.

iambaz left a reply on Instantiating Models Through Relations

Thanks Snapey, I should have expanded a bit more that the University / department was just an example and what I was trying to achieve was a little more complex.

Anyway, I ended up checking out the code and it seems there is getter method for the relation, so I can do the following:

$department = new Department();
$university = $department->university()->getRelated();

iambaz started a new conversation Instantiating Models Through Relations

I have a University model and Department model.

I have the following relation in my app/Department.php model:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Department extends Model
{
    /**
     * Define parent uni relationships. 
     */
    public function university()
    {
        return $this->belongsTo('App\University');
    }

I want to create a new University instance through the relationship. So something like:

$department = new Department();
$university = new $department->university()->relation();

Obviously the above doesn't work, but I do notice if I do the following:

$department = new Department();
dd($department->university());

I get the following:

BelongsTo {#339 ▼
    #child: Department {#335 ▶}
    #foreignKey: "university_id"
    #ownerKey: "id"
    #relation: "university"
    #query: Builder {#341 ▶}
    #parent: Department {#335 ▶}
    #related: University {#340 ▶}
}

But when I try to access the #related object, it says it is protected.

So is there any way I can do this, or even just get the string value of the name of the related model ("App\University")?

iambaz started a new conversation How To Pass Models To A Function With Type Hinting?

I am building a package that maps data to a model. I have built the facade and the API looks something like this:

DataMap::source('filename.txt')->model('\App\User')->import();

So the 'model' method, when initialised, must always be an instance of an eloquent model. But I am passing a string (as I will be using multiple instances of the passed model).

So is there a cleaner way to write this model method so that it ensures an instance of 'model' is passed?

/** 
 * Setter function for $this->model
 *
 * @param String $model
 * @access public
 */
public function model(string $model){

    if(!new $model instanceof \Illuminate\Database\Eloquent\Model){
        dd("NOT A MODEL");
    } 

    $this->model = $model;
}
03 Feb
2 years ago

iambaz started a new conversation How Would I Implement A Common Breadcrumb Function

So I have created a partial view which I use to show breadcrumbs. It simply loops through a key/val array and spits out the array in a

    .

    I have a simple Breadcrumb class which simply looks at the segments of the Request object and spits out the array according to them like so (I have condensed this down to one method for simplicity):

    /App/Library/MyApp/Display/Breadcrumb.php:

    <?php
    
    namespace App\Library\MyApp\Display;
    
    class Breadcrumb {
        
        protected $request;
        protected $path = [];
    
        public function __construct(\Illuminate\Http\Request $request){
            $this->request = $request;
        
            if($resource = $this->request->segment(1)){
                $this->path[$resource] = '/' . $resource;
            }
    
            if(is_numeric($this->request->segment(2))){
                $id = $this->request->segment(2);
                $this->path['Edit ' . $resource] = '/' . $resource . '/' . $id . '/edit';
            }
            else {
                $this->path['Create'] = '/create';
            }
    
            return $this;
        }
    
        public function array(){
            return $this->path;
        }
    
    } 
    

    I implement this widget into my view like so:

    @include('widgets.breadcrumb', ["breadcrumb"=>$breadcrumb])
    

    And I get the $breadcrumb variable in my controllers like so:

    public function index(Request $request)
    { 
        $breadcrumb = new Breadcrumb($request);
        $data['breadcrumb'] = $breadcrumb->array();
        
        return view('models.location.index', $data);
    }
    

    So the problem is I have to repeat the controller code for every controller action across all my controllers.

    On a top level, what is the 'correct' way to make this available across my views without having to initiate the Breadcrumb() class every time?

    1. Extend the Request object to add a breadcrumb array attribute?
    2. Make the class a Service Provider and inject Request object directly from the Ioc and then use a view composer to make available accross multiple views
    3. Something else?

    Thanks

30 Jan
2 years ago

iambaz started a new conversation Accessing The Foreign Key Variable In A Relation

Is there any way to get the parent foreign key column rather than explicitly defining it?

I have this model:

class Location extends Model
{

    /**
     * Define child location relationsships. This is the cities to the
     * regions and regions to the countries etc
     */
    public function children()
    {
        return $this->hasMany('App\Location', 'location_id');
    }

    /**
     * Recursive children relation to build child tree of child locations
     */
    public function childrenRecursive()
    {
       return $this->children()->with('childrenRecursive');
    }
}

I have the following:

$locations = \App\Location::with('childrenRecursive')->whereNull('location_id')->get();

So my Location model has a self-referencing 'hasMany' relationship. In the above code I am just getting the top level locations.

What I would like to do it not have to explicitly define the 'whereNull' column as 'location_id'. So something like:

$locations = \App\Location::with('childrenRecursive')->whereNull(function(){
    return $this->child->foreign_key;
})->get();

Cheers

28 Jan
2 years ago

iambaz started a new conversation How To Use The Rule Facade In A 'form Request'

I currently have my validation rules in my controller. I want to tidy this up and move the validation to 'Form Request'.

My issue is that I use the following:

'slug' => ['required', Rule::unique('locations')->ignore($id)]

This works great in the controller, but how would I parse the $id value to the form request file?

09 Jun
2 years ago

iambaz left a reply on Modifying The Structure Of My Eloquent Relations / Collection

Basically I just want to loop through and change the attributes array in each row to some other value. I have used a simple string as it seems the most basic example.

iambaz started a new conversation Modifying The Structure Of My Eloquent Relations / Collection

I have a Project model and a ProjectAttribute model.

Project 'has many' Project Attributes. The structure is retuned like so....

[ { "id": 33, "title": "Project one", "attributes": [ { "id": 2, "project_id": "33", "key": "API_TEST", "value": "A value" } ]

I want to modify the resulting structure of the 'attributes array. So, as simple as possible, I tried this:

$collection = $projects->map(function($item,$key){
        $item->attributes = "UPDATED ATTRIBUTES";
        return $item;
});

But when I output the $collection variable, nothing has changed. However if I do the following:

$collection = $projects->map(function($item,$key){
        $item->title = "UPDATED TITLE";
        return $item;
});

The title is updated in the $collection.

What's the deal? How do I modify the attributes?

04 Jun
2 years ago

iambaz left a reply on Another Question On Relations

So this is what I've ended up with. If there is a cleaner way to do it please let me know...

    $tag = Tag::where('id', $id)->with('childrenRecursive', 'parentsRecursive')->get();
    
    $parenttrace = [];
    $parents = $tag[0]->parentsRecursive;
    while($parents)
    {
        array_push($parenttrace, $parents->id);
        $parents = $parents->parentsRecursive;
    }

    $tag[0]["parent_trace"] = $parenttrace;

iambaz started a new conversation Another Question On Relations

I have a self referencing table called 'tags'. I have added recursive parent and child model methods to retrieve a tree of the tags which works nicely.

class Tag extends Model
{
public function children()
{
    return $this->hasMany('App\Tag', 'tag_parent');
}

public function childrenRecursive()
{
   return $this->children()->with('childrenRecursive');
}

public function parents()
{
    return $this->belongsTo('App\Tag', 'tag_parent');
}
public function parentsRecursive()
{
   return $this->parents()->with('parentsRecursive');
}
}   

So in my controller I then do:

public function show($id)
{
    $tag = Tag::where('id', $id)->with('childrenRecursive', 'parentsRecursive')->get();
    return Response()->json($tag, 200);
}

This gives me the correct JSON output of: [ { id:22, tag_parent:"20", title:"Birmingham", description:"", created_at:null, updated_at:null, children_recursive:[ ], parents_recursive:{ id:20, tag_parent:"19", title:"UK", description:"UK", created_at:null, updated_at:null, parents_recursive:{ id:19, tag_parent:"0", title:"Location", description:"Places", created_at:null, updated_at:null, parents_recursive:null } } } ]

So you can see in the JSON that Birmingham can trace it's relations right up to the root record which in this case is 'Places'.

What I need is an array in each of the objects of the 'parent' relation ids. So in this case I'd like the JSON to have:

[  
   {  
      id:22,
      tag_parent:"20",
      title:"Birmingham",
      description:"",
      created_at:null,
      updated_at:null,
     **parent_ids : [20,19]**
      children_recursive:[      
      ],
      parents_recursive:{  

Can anyone point me towards the best method for handling this? As each object is retrieved from a different mysql query, I don't think any of the queries have that information (the full list of relations) at any one time, so I'm guessing I'd need to do some processing on the collection?

Thanks

iambaz left a reply on Is There A Better Way To Write This Eloquent Check

Thanks both, to be honest the crux of the question was regarding the instantiation of one model in another, but the validation tips are useful.

02 Jun
2 years ago

iambaz started a new conversation Is There A Better Way To Write This Eloquent Check

I have the following tables: Users (many to many) Projects (One to many) Pages.

I have a PageController which has a store function to save a page on the database. When I'm saving the page, I need to check that the logged in user is in the user_project pivot table and therefore has ownership of the project meaning I can save a page in that project.

So I have this code in my PageController.php

public function store(Request $request) { $parentProject = Project::find(Input::get('project_id')); if(!$parentProject || !$parentProject->users->contains($this->user->id)) { return Response()->json(["error" => "You're not authorised to do this"], 403); } }

So I get the project_id from an input and load a project object before checking the projects relation to users and seeing if it has the currently logged in user id ($this->user->id).

This doesn't seem right though as I'm depending on a Project model in the Page Controller. What I'm sure I should be doing is something like this:

if( Page::project()->users()->contains($this->user->id) ) { }

So that we chain through the Page's parents until we get to the users, but I'm having trouble knowing how to do this or even if it's the best method.

Thanks

01 Jun
2 years ago

iambaz started a new conversation How Do I Talk To My 'grandfather '

I have three related tables.

Users has a many to many relationship with projects with a pivot table. Projects has a one to many relationship with pages.

All the relevant links are set up in the models.

I am building an API and when I show an individual page, I need to check back to the users table to see if the current user is attached to the project which the page is attached to.

Here is my code:

public function show($id)
{
    $userid = 3;
    if(Page::find($id)->project()->users()->contains($userid))
    {
    dd(TRUE);
     }
}

When I run this I get Call to undefined method Illuminate\Database\Query\Builder::users()

Can someone point me in the right direction?

Thanks