megaman

megaman

Member Since 4 Years Ago

Experience Points 2,245
Experience Level 1

2,755 experience to go until the next level!

In case you were wondering, you earn Laracasts experience when you:

  • Complete a lesson — 100pts
  • Create a forum thread — 50pts
  • Reply to a thread — 10pts
  • Leave a reply that is liked — 50pts
  • Receive a "Best Reply" award — 500pts
Lessons Completed 0
Lessons
Completed
Best Reply Awards 0
Best Reply
Awards
  • start-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.

03 May
2 months ago

megaman left a reply on Strongly Declared Variables

I like to use the following style synxax a lot

class myClass{

private someDependancy;

constructor(someDependancy) {
    $this->someDependancy = someDependancy
}

}

This does not use a service container. Is it still considered to be dependancy injection?

megaman left a reply on View Snippets From Packages

@BOBBYBOUWMANN - when injecting a service into blade what shoould the return type be

megaman started a new conversation View Snippets From Packages

In drupal there is a concept called a block

and block is a small view which can be dropped in any designated "region" in your main view. they can be used for things like menus, search bars, adverts ect

blocks can be created by modules (Drupals equivalent of packages)

laravel does not have blocks but a similar effect can be used with specific blade files which are inserted using @yield('region') in a layout template.

alternatively @include('regeon') can be used in a pages individual template but would only apply the 'region' to that page.

This raises 2 questions.

Is there any way a laravel package can create 'blocks' or sub views which can be inserted by the developer into a region in the projects views?

I have described how to handle separate regions in the view layer (blade files) but how would you give each region its own data - since they dont have sub controller methods.

02 May
2 months ago

megaman left a reply on Strongly Declared Variables

I did say that my belief was that it does not "strongly type" the variable and that what it actually does is dependancy injection (although i used other terms)

is this sort of type hinting laravel specific?

megaman started a new conversation Strongly Declared Variables

When using laravel sometimes you see code which has a object type before a variable name like this

__construct(UserRepository $users)

or

post_message(StoreMessageRequest $request)

In other languages (particularly strongly typed ones) this declares the variable as an object of that specific type. would i be correct to believe that it does not do this at all in Laravel and what it does is fetch an object of that type from the service container and based on its contect populate it with other data (for example a request object would have the http request data)

megaman left a reply on Event Listeners

if you are using event discovery how do you associate more than one event with a listener

megaman left a reply on Event Listeners

@NAKOV - how do u listen for multiple events in one listener

megaman started a new conversation Event Listeners

event listeners only have 1 handle method so is there any way for a single listener to listen for multiple events?

17 Apr
3 months ago

megaman left a reply on Use Statement Without Laravel

would i be correct to think that when using laravel the require DIR . '/vendor/autoload.php'; line is executed by laravel somewhere

megaman left a reply on Use Statement Without Laravel

@IMPETO - but you could do

16 Apr
3 months ago

megaman left a reply on Use Statement Without Laravel

I understand that use is for resolving namespaces

when not using laravel is there any reason why i should not just write

require DIR . '/vendor/autoload.php'; $a = new classInstance()

and leave it at that?

megaman left a reply on Use Statement Without Laravel

@RUFFLES - In laravel applications is this bit, and the $loader->addPsr4() stuff automatically handled by laravel?

megaman started a new conversation Use Statement Without Laravel

When using laravel i am used to being able to install laravel packages and other php composer libraries with composer and then do

use someauthor/somepackage

$a = new somepackage

How do you make this work without Laravel (ie when not using a php framework)

Do you have to manually perform the autoloading?

20 Feb
5 months ago

megaman left a reply on Update Some Related Models Of Some Models

Perhaps inverting my use of customer and order would be a way to ovoid a foreach loop

ie

Order::where('dispatched','=','yes')->whereHas('customer', function ($query) { $query->where('country','=','uk'); })->update(['discount_applied' => 'yes']);

would that work

megaman left a reply on Update Some Related Models Of Some Models

I see a mistake i made there is no all() function on models, it is get()

megaman started a new conversation Update Some Related Models Of Some Models

I need to update a load of models

The models i need to update must be related to a different model which must be filtered by a where clause The models being updated also need to be filtered

I tried to do something like this

Customer::where('country','=','uk') ->orders() ->where('dispatched','=','yes') ->update(['discount_applied' => 'yes']);

I have also tried this

$customers = Customer::where('country','=','uk') ->orders() ->all()

foreach ( $customers as $c) { $c->orders() ->where('dispatched','=','yes') ->update(['discount_applied' => 'yes']); {

Nothing works

Is it possible to do this without a foreach loop (there can be multiple customers who have orders which need updating)

How can i make this work.

also when i use all() exactly like in the example ubove i get an error because all() is not a method, although apparently first() is. DO i need to use all() before starting a loop and why does it think it does not exist?

23 Nov
7 months ago

megaman left a reply on Downloading A File

@SNAPEY - I did check the file path name thoroughly This includes the case

have not tried in tinker yet, that would be another test (although a successful run would not help much as i can run it as a command anyway)

megaman started a new conversation Downloading A File

In one of my controllers I have the following line of code

$file = Storage::disk('local')->get('folderName/fileName.zip');

The file root is declared in config/filesystems.php and .env

When i run this code locally it works. When i run this exact same code on my production server it throws a fileNotFound exception. When i run the exact same code from a command on my production server it works again.

The only time it does not work is when executed from a controller. (i have tested it in 2 different controllers - including one which only has a single method with this line of code in without any sort of laravel route authentication enabled)

I have placed a info::log() immediately after the line of code to make sure it does not get any further then that (so nothing which comes after could be the cause).

I have tried several other functions of the FileSystem class which access the file including exists(). size() and lastmodified(). all of them except for exists cause the same error (exists simply returns nothing)

I have tried different files including a blank .zip file created using touch > file.zip, a random text file and a zip file which i know to be a valid zip file I always get the same problem.

I have made sure the file it attempts to download has been 777 ed ( all access permissions granted)

I have tried running it from a HTTP route which has no authentication requirements

The full pathname of the file is printed in the error, the path is correct and the file certainly exists.

I have made sure my laravel config and .env files in both machines are identical

from what i can tell i have tested the following

  • the file itself
  • the file path and access permissions
  • laravels setup
  • my code (the part which breaks works when used on a different machine or from a command)
  • both machines, operating systems, installed programs, php dll's, composer packages ect

The only thing (which i can think of) which is involved ONLY when the error occurs and never when it does not occur is the instance of Apache installed on the production server because this is the only component (which i can think of) which is used when running the script in a controller and not used when running it in a command.

any help please!

12 Nov
8 months ago

megaman started a new conversation Relationships And Controler Logic Advice

I have 4 models which have the following structure

A -> (one to many) -> B -> ( one to many ) ->C

all 3 models have a status column

My logic starts with a single instance of A using a for each loop i select all associated B models and change their status. from this loop I get the C model associated with the current B model and loop though all of its associated B models (effectively every sibling of B if C is a parent)

Depending on how many C models there are with different statuses I set a different status on B

are the following improvements recommended

Updating all the the B models related to my A model using something other than a loop? if yes what?

creating a hasmanythrough relationship between A - C, this would skip B but would there be any point considering a make a change to B, if yes how would this work?

3)While looping through the B elements is there a better way to get all of the sibling models (ie without fetching the C element of the B element which i get from A

Is it worth moving all of this logic out of the controller and into a model function, model change event or an event?

10 Oct
9 months ago

megaman started a new conversation Model Deleting Event Not Working

I have the following model and relationship structure

A -(has many)> B -(has many)> C

when A is deleted I want all associated B rows to be deleted and in turn all associated C rows to be deleted

i have the following code in my A model

protected static function boot() { parent::boot();

static::deleting(function($A) {
    log::info('deleteding B');// before delete() method call this
    $A->B()->delete();
});

This works

I have the following code in my B model

protected static function boot() { parent::boot();

static::deleting(function($B) {
    log::info('deleteding C');// before delete() method call this
    $B->C()->delete();
});

The relevant relationships on each model seam to be complete

The problem is that the first static::deleteing statement work and the second one does not in fact the log::info statement in the second one does not run which shows the deleteing event is not running at all.

although if i put a log::info immidiatly after the parent::boot() cal l in model B it does print which shows a B model is being created

It is been suggested to me that something like this is going on https://github.com/laravel/framework/issues/2536

Is that what is happening here? is there any way to make a static::deleteing clause on a model delete the related C models or will i need to loop from my main code (controller, job, command ect)

11 Aug
11 months ago

megaman started a new conversation Validation Problem

I am using laravel validation However the validation is done by a seperate project (connected via HTTP requests) so it does not automatically redirect back to the form if there are errors.

instead i have a line which looks something like this in the controllers

if($errors = true){ return back()->messageBag($errors) }

I use the same forms for both creating an updating reasorces a typical input will look like this

{{errors->customer_name}}

On an edit customer form this would pre-populate the field with the existing value (fetched from the database) On a create new customer form it would give an empty form field. the isset() is used to prevent an error when customer is not set (because it is a create instace of the form.

A problem i have is if there are validation errors and it rediretcs back to the form

  • if it is a create form the form fields become empty
  • if it is an edit form the form fields become empty in both cases the users previous input is lost.

This is to be expected In the case of create forms no values are loaded form the database so nothing gets set as the field values when the view loads. In the case of edit forms normally the HTTP call would recieve a model as a response which contains the value, but in these cases it recieved a validation error so again the field values are not sent to the view.

my question is this would adding withMessages($request->all()) to the end of mt return statement like this

return back()->messageBag($errors)->withMessages($request->all())

be enough to populate the form fields with the values the user previously entered.

04 Aug
11 months ago

megaman left a reply on Session On Api Routes

"Ha thats so funny. Its a two factor authentication package but you want to use it for something other than authentication?"

NO!

I am using it for exactly that a second type of authentication.

and at no point did i say anything otherwise!

I use passport for oauth and this package for OTP

megaman left a reply on Session On Api Routes

the package is antonioribeiro/google2fa-laravel

i tried to post the name twice but once it blocked me for re-posting too soon and the other time the post did not appear

03 Aug
11 months ago

megaman left a reply on Session On Api Routes

Cronix Indeed but we did not realize that this package required session until the very last stage of developing the feature which we want to use it for

megaman left a reply on Session On Api Routes

Cronix, I am not sure that would work

A session is seperate for each client and a client is usually a browser. However i my project there are 2 laravel projects. One project is a gateway which the users (via their browsers) connect to directly. The second other is the API which actually provides the services and has access to various datasources

The gateway project makes all HTTP requests to the API project This means there is only one "client" connecting no matter how many users there are or put another way each user does not have his own unique session with the API

megaman started a new conversation Session On Api Routes

I am attempting to use some middleware provided by a package on some api routes It throws an error because session is not available.

Is there any way arround this without refactoring the package?

21 Jul
11 months ago

megaman left a reply on Blade Directives - Why?

yes Snapey i figured that out.

I needed to retrun it from the directive (so the view would render it) or run print/echo in the directive

The thing i could not get my head around was why the directive always showed the value of any variable being its name in the debugger rather than its actual value.

20 Jul
1 year ago

megaman started a new conversation Blade Directives - Why?

I tried to use a blade directive to make some re-usable blade code that had logic in it today

All was find until i tried to pass some data to the directive ie @mydirective(var)

I tried @mydirective({{var}}) and when i did that the data variable was always its own name (ie the litteral string "var") I tried @mydirective(var) This caused the same thing unless i returned the variable in which case the value was returned.

given how much of a pain in the arse this was

why would i use a directive when i can just use a sub template (ie @include())

17 Jul
1 year ago

megaman left a reply on WhereHas With Dot Notation Load

the example on that page uses with is

$users = App\User::with(['posts' => function ($query) { $query->where('title', 'like', '%first%'); }])->get();

Does this also work on for a load()?

also my load uses dot syntax and the model i want to retrain on is in the middle of the dot chain

ie load('model.model.QUERYIED_MODEL.model') will it still work

megaman started a new conversation WhereHas With Dot Notation Load

I have code like the following

$model->load('account.user.posts.comments') I use load() rather than with() because when i tried to use with the related models appeared as their own properties on the main model but i needed them as children of their pearent model

anyway

I need to query the posts table and only get $models->account->user where there is at least one post which matches a given criteria

i have tried using whereHas but that does not seam to do anything in this case

Is it because dot notation is used? is it because load() is used? is it something else?

How can i made a where clause on the post relation? and do i have to do anything else in order to exclude any $models->account rows which dont have at least one use that matches the given where clause.

16 Jul
1 year ago

megaman left a reply on Working With Appended Properties

i am not on my development machine right now

but its something like this (names changed)

Js -id -customer name -customer country

JDs -J_id -D_id -status

Ds -id -name -description

where J is my first table, D is my 3rd table and JD is the pivot table

megaman started a new conversation Working With Appended Properties

I have a situation where my primary model has a related model which is a pivot table which in turn is related to a 3rd table (effectively a many to many relationship between the first and 3rd tables).

I need to get ALL rows from the 3rd table and mark the ones which have a connection to my main model via the pivot table.

To clarify what i am trying to do - the intended application is to display all the columns from a single row in the first table and all of the rows in the 3rd table and place a tick next to the ones which have a join via the pivot table.

I have decided to load all models from the 3rd table and pluck the list of IDs into an array.

I then use where() to load only the released rows in the pivot table and use a loop through the array of IDs to check each pivot table model to see if the id and foreign_key match

If it does i want to add a custom property to the model for the row from the 3rd table and change its default value to indicate that there was a match.

SO far i have managed to add a customer property and set its default value using this https://laravel.com/docs/5.3/eloquent-serialization#appending-values-to-json

However i cannot seam to change the value when i find a match

I have tried $model->property = $value I have tried getIsXXXAttribute() to getIsXXXAttribute($value = $default) and calling it from my loop with the new value passed in. I have tried using setXXXAttribute() none of these work.

I have considered using the map function of the collection class would this work

is there a different way of doing it

or is there a simply way to do it without faffing about creating and updating a custom value

23 Jun
1 year ago

megaman left a reply on Attach Many Related Models

does the saveMany() function have an update many equivilant?

22 Jun
1 year ago

megaman started a new conversation Attach Many Related Models

I have a many-one relationship which is defined with a hasMany() function on one of the models and a belongsTo on the other.

The "many" model exists first and at a certain time a instance of the "one" model is generated and associates itself with any of the "many" models which match a certain where clause.

Currently i use code like this to do this

foreach (model in models){ $model->related_id = $id {

is there any way to replace the "$model->related_id = $id" line with something smaller?

I dont think i should have to referance the foreign key field and parent model id to link them.

15 Jun
1 year ago

megaman started a new conversation Validation Across 2 Projects

I am working on a project which is split into 2 laravel projects

the first project controls the web interface. the second project controls the data. the first project interfaces with the second project via POST http requests

Currently my validation rules exist in the first project

If from my first project i used .all() or .toArray() on any request attributes being sent from the browser and used this array as my list of POST parameters in my http requests going to project two would the same validation rules still work if i moved them to project two?

megaman left a reply on FirstOrCreate

Thanks guys I suspected the 2x 3d array approach would work but the regular documentation does not state this. and i could not find the function in the api documentation at all.

14 Jun
1 year ago

megaman started a new conversation FirstOrCreate

I have a table with 4 columns (+ the date columns laravel makes).

I want to find an instance based on the value of 2 of the columns and if there is no match create it and also add the value of the other 2 columns.

so for example if i had the following data

id | customer id | state | address | name

1 : 1 : green : blah : blah 2 2 : red : blah : blah

I may want to search for customer_id=2 and state=green it would not find this so it would add this record and add address=blah name=blah

Is it possible to do this with firstOrSave() / firstOrCreate()

10 Jun
1 year ago

megaman left a reply on Access Database From Second Project

perhaps i can change my models from extending eloquent to extending a middle class which in turn extends eloquent

and in the middle class override the functions which directly access the database (or PDO) with versions which make the HTTP calls.

The http calls would send the raw query string and name of the model (i believe there is a function which obtains this) to the other project.

In the other project controller i would call the model named in the http call and call the raw query string sent in the http call (i believe there is an eloquent function for this). serialize the returned collection object and send it back to the requesting project

here the collection object would be unserialized (can php objects be created in this way) and passed to the calling function in the same way that the function i overrode does.

megaman started a new conversation Access Database From Second Project

I am working on a project which has been split into 2 separate Laravel projects running on different servers.

One of the projects manages the data. It has models and connects to the database in the normal Laravel way.

The Second project is an interface. From its controllers it makes HTTP requests to the first projects controllers which fetch the desired data via models and return it as JSON.

normally the Laravel process would be something like route -> controller -> model -> return view this is now route -> controller -> http -> receive json -> return view

The second project (the interface one) is not aloud to have direct access to the database.

Is there any way I can map the models in the second project (the interface one) to the models in the first project so that i can use the normal Laravel workflow from the interface project.

I thought of manually adding the database fields to the models in the interface project and setting the value of them with http requests (effectively moving the http calls from the controllers to the model) but even if this did work im not sure how well relationships would continue to work, I would have to create both request and set http calls (how could i make a model do this correctly) and would have to manually set all of the properties.

Is there a package that can do this for me is there some other way to do this?

09 Jun
1 year ago

megaman started a new conversation Traits In Laravel

My understanding of PHP traits are they are like snippets of code which can be inserted using a use statement inside of a class and the effect is as if you had copy/pasted the code in at the point. The same as if you use include() or require()

so why is it that some of the laravel API documentation pages list traits associated with classes? example https://laravel.com/api/5.6/Illuminate/Database/Eloquent/Model.html

listing methods and properties makes sense because these things are a part of an object. traits however are not

08 Jun
1 year ago

megaman started a new conversation Form Model Binding

I am interested in using Laravel Collective forms for their form model binding feature https://laravelcollective.com/docs/5.0/html

A few questions

I am working on a large project with lots of form and many tables/models My data structure in most cases does not exactly match my forms. Some data is on a different model from the primary model associated with the form.

Is it possible for me to automatically bind the fields to the model if a relationship is placed on the model? If yes how would I do this.

ie if collective has generated the following form fields

and i have a customer model and a addresses model with a one - one relationship between customer and address how would i bind the "customer_primary_address" field?

Is this also possible if the relationship between customer and address is a one-many relationship (a customer can have many addresses)

05 Jun
1 year ago

megaman started a new conversation Passport Authenticating

The laravel passport documentation say that you make routes require oauth authentication using auth:api like so

Route::get('/user', function () { // })->middleware('auth:api');

it also says that to authenticate a scopre you use scope:scope_name like so

Route::get('/orders', function () { // Access token has both "check-status" and "place-orders" scopes... })->middleware('scopes:check-status,place-orders');

If using scope do you need to use both or just the scope one ie do you need

middleware('auth:api'); or middleware(['auth:api','scopes:check-status,place-orders']);

26 May
1 year ago

megaman started a new conversation Code Dependent On External Package

I need to write a new route to trigger a controller action which is provided by a package which i installed in a project. The package provides its own route for this but i need to make a custom route.

obviously this route should only exist if the package is installed.

What is the best way to do this

Is there a way to declare a route in my web/api.php files which is dependant on the existance of this package?

Perhaps i can make my own package which creates this route and make it dependent on the other package?

perhaps there is another way

28 Feb
1 year ago

megaman started a new conversation How Use Works

Im used to using functions such as include() and require() to import other PHP files

i have experience namespaces and keyworks such as use and import in other languages

and my question i this. i always though namespaces were not native to php and to access other php files from a php file you needed to make a file system relative (or absolute) reference using include() and require()

so how exactly does laravel make using use work? and how can i do this without laravel (ie native php)

megaman left a reply on Missing Auth Routes

the ones related to resetting forgotten passwords

megaman started a new conversation Missing Auth Routes

I have a project which has some of the files created by php artisan make:auth , but many are missing

it also has manually declared some of the routes which should be there but not all, the ones which are there are slightly changed from the default (controller names have been changed)

I need to add some of the others, specifically password reset ones.

I couldn't just run artisan make:auth because this would overwrite some existing views and controllers I cant use the shorthand facade which can go in the route.php file because this would not currently produce the existing routes which have been changed from the default (although i suppose i could have inserted if after the existing manual route declarations.

I have had to manually, (a lot of google searching and looking in the vendors folder) create the missing routes and views.

my question is

is there any reason why a developer would have made the application like this in the first place?

25 Feb
1 year ago

megaman left a reply on Validation Values

I am trying to do this cleanly https://laracasts.com/discuss/channels/laravel/editing-request-values

easy to do, not easy to do cleanly. in short the problems are

  • Cannot have any logic before the validator runs. the only ways arround this is to switch to the function based syntax for validation or putting the logic in the validation class itself (option 1 is inconsistant with the rest of the project option 2 is unclean)

  • It is recommended that i dont modify the $request object and until now i though validator code could only read the request object so i could not just copy the values to another array.

  • The controller uses fill() to match the form field names with the db columns automatically, if i copy my value to annother array (other than the $request array) i will need to manually submit this value to the DB ie

$id = $model->fill($request

would become

$id = $model->fill($request) $model->where('id','=',$id)->update('field_name'.$value);

  • storing the value in a hidden field on the front end and using JS to update it whenever the user makes a change is messy.

it sounds like this would be the best way

if (validator([ 'type' => $request['someValue'] . $request['anotherValue'] ], [ 'type' => 'exists:babyAnimals' ])->fails()) {

// validation failed

}

megaman started a new conversation Validation Values

Laravels validation logic looks something like this

$request->validate([ 'title' => 'bail|required|unique:posts|max:255', 'body' => 'required', ]);

where title and body are variables found in the $request array

Is there any way to validate other variable.

ie

$someValue = "kittens"

$request->validate([ 'title' => 'bail|required|unique:posts|max:255', 'body' => 'required', $someValue => 'exists:babyAnimals' ]);

megaman left a reply on Editing Request Values

My understanding of laravels validation feature is that you have a text string which starts with the name of the value (in the request object) being validated and then lists a load of validation rules.

this is a bit inflexible since you cant add you own custom logic (unless you make a custom validation rule) and you cant validate any value outside of the request object.

or can you?

is there any way to give a validation rule a variable other than a value in the request object

23 Feb
1 year ago

megaman left a reply on Editing Request Values

As i said the validation is done using a specific validate object which is passed into the controller method as an argument

also, (i did not mention this before) the form field names match the database column names and one of laravels auto fill methods is used on the model class - so i cant just copy the request variable, change it and pass that to the DB

it seams javascript will be the best way forward here