patrykszady

patrykszady

Member Since 4 Years Ago

Experience Points
10,040
Total
Experience

4,960 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
97
Lessons
Completed
Best Reply Awards
3
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 3
10,040 XP
Mar
29
1 year ago
Activity icon

Replied to Nginx 504 Gateway Time-out With Php.ini Changed - Works On Local Homestead

Thanks! I've reached out to them. Will post results asap.

Activity icon

Replied to Nginx 504 Gateway Time-out With Php.ini Changed - Works On Local Homestead

Honestly, I have both changed right now in hopes one would work. Like you said, I hoped set_time_limit() would overwrite it just like it does on my dev environment with homestead.

Is there anything in nginx.conf I should be adding/changing to try?

Activity icon

Replied to Nginx 504 Gateway Time-out With Php.ini Changed - Works On Local Homestead

Thanks all, I've tried everything above. set_time_limit(300); works great on my dev homestead but of course not on my forge production. It's nice that there's the php.ini edit on the forge env … unfortunate it just displays what I already edited on the server.

Is there any nginx setting I can add to limit timeout? I'm not familiar with the settings but forge has a Edit for it. But then again, why is it working on my dev and not production if the only thing different is the location of the php.ini settings - which are the same on both.

Mar
28
1 year ago
Activity icon

Replied to Nginx 504 Gateway Time-out With Php.ini Changed - Works On Local Homestead

I just triple checked to make sure I'm not going crazy: Changed

max_input_time = 120 max_execution_time = 300

in

/etc/php/7.1/fpm/php.ini

Activity icon

Started a new conversation Nginx 504 Gateway Time-out With Php.ini Changed - Works On Local Homestead

Hi all,

I can't figure this out -

I'm using snappy pdf to create a large pdf doc with images. the task is done within 30secs most times, and it always works as expected unless the process takes longer than 30secs. I changed all relevant php.ini settings on my forge ( /etc/php71/fpm/php.ini) and on homestead. It works on my local homestead but my production on forge always fails if it takes longer than 30 secs to create. This makes me believe Forge is ignoring the php.ini file? I checked and my server is using /etc/php5/fpm/php.ini which is the file that has changed. I have restarted php and nginx but I don't understand what could be happening.

Thanks for any pointers!

Nov
04
1 year ago
Activity icon

Replied to Error 500 After Upgrading To 5.5 Everytime Whoops Is To Show

sorry, I'm not following. How and what am i trying to log? and I'm using w/e came with the laravelr 5.5 installer, 2.0 I believe.

Activity icon

Replied to Error 500 After Upgrading To 5.5 Everytime Whoops Is To Show

here's that dd from handleShutdown()

array (size=4)
  'type' => int 1
  'message' => string 'Uncaught Error: Call to undefined method Whoops\Handler\PrettyPageHandler::setApplicationPaths() in /home/vagrant/sites/gs/vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/Handler.php:374
Stack trace:
#0 /home/vagrant/sites/gs/vendor/laravel/framework/src/Illuminate/Support/helpers.php(1035): Illuminate\Foundation\Exceptions\Handler->Illuminate\Foundation\Exceptions\{closure}(Object(Whoops\Handler\PrettyPageHandler))

#1 /home/vagrant/sites/gs/vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/Handler.php(379): tap(Object(Whoops\Handler\PrettyPageHandler), Object(Closure))

#2 /home/vagrant/sites/gs/vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/Handler.php(333): Illuminate\Foundation\Exceptions\Handler->whoopsHandler()

#3 /home/vagrant/sites/gs/vendor/laravel/framework/src/Illuminate/Support/helpers.php(1035): Illuminate\Foundation\Exceptions\Handler->Illuminate\Foundation\Exceptions\{closure}(Object(Whoops\Run))
#4 /home/vagrant/sites/gs/vendor/laravel/framework/src/Illu
"file" => "/home/vagrant/sites/gs/vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/Handler.php"
  "line" => 374

Activity icon

Replied to Error 500 After Upgrading To 5.5 Everytime Whoops Is To Show

i have 5.5.19.. in .json and lock - that's what I want becuase I know it works on another and new app.

Activity icon

Started a new conversation Error 500 After Upgrading To 5.5 Everytime Whoops Is To Show

Hi guys,

I just upgraded an app to 5.5 (5.5.18) and my Whoops exception pages are showing Error 500 in my browser instead. I've also created a new laravel 5.5 app from scratch and that one is showing my Whoops pages..but not my existing ones. I don't even know where to start.

My last laravel.log error

[2017-11-04 19:23:36] local.ERROR: Uncaught Error: Call to undefined method Whoops\Handler\PrettyPageHandler::setApplicationPaths() in /home/vagrant/sites/gs/vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/Handler.php:374
Stack trace:
#0 /home/vagrant/sites/gs/vendor/laravel/framework/src/Illuminate/Support/helpers.php(1035): Illuminate\Foundation\Exceptions\Handler->Illuminate\Foundation\Exceptions\{closure}(Object(Whoops\Handler\PrettyPageHandler))
#1 /home/vagrant/sites/gs/vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/Handler.php(379): tap(Object(Whoops\Handler\PrettyPageHandler), Object(Closure))
#2 /home/vagrant/sites/gs/vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/Handler.php(333): Illuminate\Foundation\Exceptions\Handler->whoopsHandler()
#3 /home/vagrant/sites/gs/vendor/laravel/framework/src/Illuminate/Support/helpers.php(1035): Illuminate\Foundation\Exceptions\Handler->Illuminate\Foundation\Exceptions\{closure}(Object(Whoops\Run))
#4 /home/vagrant/sites/gs/vendor/laravel/framework/src/Illu {"exception":"[object] (Symfony\Component\Debug\Exception\FatalErrorException(code: 1): Uncaught Error: Call to undefined method Whoops\Handler\PrettyPageHandler::setApplicationPaths() in /home/vagrant/sites/gs/vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/Handler.php:374
Stack trace:
#0 /home/vagrant/sites/gs/vendor/laravel/framework/src/Illuminate/Support/helpers.php(1035): Illuminate\Foundation\Exceptions\Handler->Illuminate\Foundation\Exceptions\{closure}(Object(Whoops\Handler\PrettyPageHandler))
#1 /home/vagrant/sites/gs/vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/Handler.php(379): tap(Object(Whoops\Handler\PrettyPageHandler), Object(Closure))
#2 /home/vagrant/sites/gs/vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/Handler.php(333): Illuminate\Foundation\Exceptions\Handler->whoopsHandler()
#3 /home/vagrant/sites/gs/vendor/laravel/framework/src/Illuminate/Support/helpers.php(1035): Illuminate\Foundation\Exceptions\Handler->Illuminate\Foundation\Exceptions\{closure}(Object(Whoops\Run))
#4 /home/vagrant/sites/gs/vendor/laravel/framework/src/Illu at /home/vagrant/sites/gs/vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/Handler.php:374)
[stacktrace]
#0 /home/vagrant/sites/gs/vendor/laravel/framework/src/Illuminate/Foundation/Bootstrap/HandleExceptions.php(137): Symfony\Component\Debug\Exception\FatalErrorException->__construct()
#1 /home/vagrant/sites/gs/vendor/laravel/framework/src/Illuminate/Foundation/Bootstrap/HandleExceptions.php(123): Illuminate\Foundation\Bootstrap\HandleExceptions->fatalExceptionFromError()
#2 /home/vagrant/sites/gs/vendor/laravel/framework/src/Illuminate/Foundation/Bootstrap/HandleExceptions.php(0): Illuminate\Foundation\Bootstrap\HandleExceptions->handleShutdown()
#3 {main}
"} 
Oct
12
2 years ago
Activity icon

Replied to Combine Two Tables Into One Result Set. Merge/append/join

yes, expense_splits.expense_id is related toexpenses.id. Attributes:

    "id" => 1
    "expense_date" => "2017-06-06"
    "amount" => 123.0
    "project_id" => 1
    "vendor_id" => 1
    "paid_by" => "6"
    "invoice" => "Cash"
    "check_id" => null
    "reimbursment" => "0"
    "receipt" => "1-2017-06-06-22-59-54.jpg"
    "receipt_html" => null
    "distribution_id" => null

I need a collection with the above attributes. If it comes from the expenses table in the database, great, nothing changes. If it comes from the expense_splits table, grab some of the attributes from the parent model but display the entry as an Expense, not as an Expensesplit. ...in my views I'd need to access each as $expense->expense_date... I can't be calling $expense->expense_date and doing if statements all over my views so I can display the same data by calling $expense_split->expense->expense_date.

For instance- An expense has a date and receipt image that will never change. But an expense can be split into multiple projects. It will always hold the original receipt data however.

Activity icon

Replied to Combine Two Tables Into One Result Set. Merge/append/join

@Snapey Thanks but now I'm confused... the below is what I have and the splits are on the bottom of the table. I actually use datatables that does the sorting and it solved my issue (besides a lot of repete code all over my controllers). I'd still love to learn how to have laravel do the work.

Project Controller
$expenses = $project->expenses()->get()->sortByDesc('expense_date');
$expense_splits = $project->expenseSplits()->get()->sortByDesc('expense_date');
<tbody>
    @foreach ($expenses as $expense)
        <tr>
            <td data-order="{{$expense->expense_date}}">{{ $expense->getDate() }}</td>
            <td data-search="{{$expense->amount}}">{{ $expense->getAmount() }}</td>                     <td><a href="{{ route('vendors.show', $expense->vendor->id)}}">{{ $expense->vendor->business_name }}</a></td>
        </tr>
        @endif
    @endforeach
    @foreach ($expense_splits as $split)
        <tr>
            <td data-order="{{$split->expense->expense_date}}">{{ $split->expense->getDate() }}</td>
            <td data-search="{{$split->amount}}" data-search="{{$split->expense->amount}}">{{ $split->getAmount() }}</td>
            <td><a href="{{ route('vendors.show', $split->expense->vendor->id)}}">{{ $split->expense->vendor->business_name }}</a></td>
            @endif
        </tr>
        @endif
    @endforeach
</tbody>
Activity icon

Replied to Combine Two Tables Into One Result Set. Merge/append/join

Thanks,

But I need both the expenses and expense_splits to act as one Collection with the exception of expense_splits having additional attributes added dynamically from the parent model.

When I call $project->expenses()->get() all expenses and expense_splits would be included in one Collection as expense. That way I'd be able to arrange all the data (expenses and expense_splits) the way I want inside my <table> By amount, date, etc together. Two very similar Models acting as one inside views. Right now, of course, $expense->hasMany('App\ExpenseSplit') and $expense_splits->belongsTo('App\Expense')

Maybe i structured this incorrectly in my database becuase it's hard to get the data i need for my purposes. I can do separate foreach statements inside my <table> on my views, but this would always mean my expense_splits are after all expenses are displayed first.

Thanks for your input so far! - Patryk

Oct
11
2 years ago
Activity icon

Started a new conversation Combine Two Tables Into One Result Set. Merge/append/join

I have an expenses and expense_splits table. I'd like to combine both into one result set. Every expense_splits should have added attributes from the expense it belongs to. It seems like there is a lot of ways to go about this but none seem just right.

For example, a leftjoin like this almost works for me but it deletes all my expenses id #s and only keeps expense_splits.

$expenses = DB::table('expenses')
            -leftJoin('expense_splits', 'expenses.id', '=', 'expense_splits.expense_id')
            ->get();

Ideally, I need all attributes from my expense table to show in my expense_splits result. Unless of course attributes are the same on both tables, then show expense_splits attribute (which a jelftjoin does for me..but it deletes my expenses.id).

I can also merge/push my two collections. This is a quick way to show them within one result set. However, I'm not sure how to add expense attributes to each expense_splits. I need my expense_splits to be treated as a regular expense (and if an expense has splits I can't have it shown..but i'll worry about that later). There will never be a time where I don't need this anywhere on my app.

        $splits = ExpenseSplit::all();
        $expenses = Expense::all();

        $expenses = $expenses->merge($splits);

I can also append to my ExpenseSplits result, but, honestly, idk where to place this or if it even makes sense. I'd need it placed somewhere where it's called everytime I call Expense::all() and I can't copy & paste all over the app.

        $expense_split = ExpenseSplit::find(34);
        $expense_split->receipt = $expense_split->expense->receipt;
        $expense_split->receipt_html = $expense_split->expense->receipt_html;
        $expense_split->check_id = $expense_split->expense->check_id;

What is the best place to place this code so it's avaliable as simply as Expense::all() and these splits from my expense_splits table will be included. And of course, how do I go about doing this in the first place. It seems there's a lot of ways to get this done.

Thanks, Patryk

Sep
11
2 years ago
Activity icon

Replied to OrderBy Or SortBy Of GroupBy Sum

Thanks, I'll have a look. For now the following works - I just think it's messy so I'll read over your link.

$expenses = $project->expenses()->select('*', DB::raw('sum(amount) as total'))->groupBy('vendor_id')->orderBy('total', 'DESC')->get();
Activity icon

Started a new conversation OrderBy Or SortBy Of GroupBy Sum

Hi all,

I'm trying to sortBy or orderBy the sum of amount from my groupBy...this is what I have in my controller

$expenses = $project->expenses()->groupBy('vendor_id')->get();

This returns the correct info but I'm not sure how to sort it so that the first result is the largest sum of AMOUNT for each vendor. Amount is stored in Expenses table together with vendor_id. Thank you in advance for any help!

Jul
07
2 years ago
Activity icon

Started a new conversation Validation Request With Arrays

Hi all,

I have two very similar forms with array inputs. On one, if validation fails on one of the array inputs, the correct input is selected with my error styling (simple bootstrap red box outline) and the correct message is displayed atop. On the second one, the error happens and the correct message is displayed atop but the box doesn't get the styling. As if it didn't know which one to target.

FIRST: (This works) Form:

@foreach ($accounts as $key => $account)
<div class="form-group {{$errors->has("account.$key") ? ' has-error' : ''}}">
    <label for="account" class="col-sm-4 control-label">{{$account->name}}</label>
    <div class="col-sm-3">

        <input type="text" class="form-control" id="account{{$key}}" name="account[]" placeholder="Owner - Home" value="{{ old("account.$key") }}" autofocus="autofocus" onfocus="this.select()">

    </div>
</div>

    <input name="distribution_id[]" id="distribution_id.$key" type="hidden" value="{{ $account->id }}">
    
</div>
@endforeach

Request:

public function rules(Request $request)
    {
        return [
        'account.*' => 'required|integer|min:10|max:100'
        ];
    }

    public function messages()
    {
        //can we say Project_name hours... and know if letters or floats are typed, makes for more personalized error messages
        return [
            'account.*' => 'Percent must be numeric and integer. At least 10% and 100% max',
        ];
    }

SECOND ('has-error' doesn't respond to the error'ed input) Form:

@foreach ($projects as $key => $project)
<div class="form-group {{$errors->has("hours.$key") ? ' has-error' : ''}}">
    <label for="hours" class="col-sm-4 control-label">{{ $project->getProjectname() }}</label>
    <div class="col-sm-6">
        <input type="text" class="form-control" id="hours{{$key}}" name="hours[]" placeholder="20 Hours" value="{{ old("hours.$key") }}">
    </div>
    <input name="project_id[]" type="hidden" value="{{ $project->id }}">
</div>
@endforeach 

Request:

public function rules(Request $request)
    {
        return [
        'hours.*' => 'nullable|integer',
        ];
    }

    public function messages()
    {
        //can we say Project_name hours... and know if letters or floats are typed, makes for more personalized error messages
        return [
            'hours.*' => 'Project hours must be numeric and integer',
        ];
    }

I hope there is something simple I'm missing here. Thanks for all your input! -Patryk

May
05
2 years ago
Activity icon

Replied to Validation Required_if Array Issue

So this is what I settled for:

    public function rules(Request $request)
    {
    
    $count = count($request->amount);
    for($i = 0; $i < $count; ++$i){

        if($request->amount[$i] != null){
            return [
            'date' => 'required|date', 
            'amount.*' => 'nullable|numeric',
            'bid.*' => 'nullable|numeric',
            'check' => "required|numeric|unique:checks,check",
            ];
        } else {
            //return back to the For statement with the next amount id
        }
    }
            return [
            'date' => 'required|date', 
            'amount.*' => 'nullable|numeric',
            'bid.*' => 'nullable|numeric',
            ]; 
    }

Works good just doesn't look great. If anyone has any idea how to clean this up please let me know. - Patryk

Activity icon

Replied to Limiting Records Using Conditional

Help me understand, So you want to filter by user_id, which of course gives you all the orderdetails for the logged in user and then you want to filter down from those results or a complete new set of results from the whole user table?

May
04
2 years ago
Activity icon

Replied to Validation Required_if Array Issue

Thanks, I've tried and... Validation rule required_unless requires at least 2 parameters.

"amount" => array:3 [▼
    0 => null
    1 => "50"
    2 => null
  ]

When the request gets the above amount array, it should require the check input. While validating it should add .0, .1, .2 for each of the amounts. Just like it does when it validates the amount.* inputs

Activity icon

Replied to Validation Required_if Array Issue

Very strange,

The check field is required unless amount.* is in null.
The amount.1 must be a number.

It returned amount.* as if Laravel wasn't recognizing I'm calling an array. For comparison, I made sure I fail my amount input to show how it recognizes the .1

Activity icon

Started a new conversation Validation Required_if Array Issue

Hello,

I'm having an issue with the required_if validation rule. I'm simply trying to require check if ANY of the amount fields are not null. In this particular case amount array is always present in the request as Null even if input is empty.

    public function rules()
    {
        return [
            'date' => 'required|date', 
            'amount.*' => 'nullable|numeric',
            'bid.*' => 'nullable|numeric',
            'check' => 'required_if:amount.*, !=, null',
        ];
    }

Any idea what I could be doing wrong? Thanks - Patryk!

Activity icon

Replied to Display History Of User By Id User

Hahahah. People are so rude. @ohffs took his time to find you a starting point and u demand something else?

Couldn't this guy just do something like user::find orders->products latest ?

Activity icon

Replied to Save Multiple Rows To Database Laravel 5.2

What does your table/form look like?

Activity icon

Replied to How To Query A One To Many Relationship With Condition In Eloquent


$products= Product::whereHas(colors, function ($query) {                                         $query->where('color', 'blue'); //'color' is the column on the Color table where 'blue' is stored.
}])->get();

Give this a try. Hopefully it leads you on the right path.

https://laravel.com/docs/5.4/eloquent-relationships#querying-relationship-existence

May
03
2 years ago
Activity icon

Replied to BelongsToMany With Eloquent Model As Pivot Table

Create a new table for a many to many relationship. A User hasMany Rooms. A Room hasMany Users.

Then you should be able to do $user->rooms and $room->users ? https://laravel.com/docs/5.4/eloquent-relationships#many-to-many

Activity icon

Replied to Trying To Get Property Of Non-object

Try @jbloomstrom s suggestion. I think that's a very clean way to write this scope. Also, with and without the scope take out ->toArray. Have ->get(); be the last of that statement.

Is there a particular reason why you're toarray'ing? ....sorry on my phone so no annotations or tests here.

Activity icon

Replied to Trying To Get Property Of Non-object

Haha I missed the ,true. Forget the scope for now, try

$students = User::where('is_student', true)->get();

Dd($students);

This should return a collection of all Users that are students

Activity icon

Replied to Trying To Get Property Of Non-object

How is is_student stored in the database? What are the values for yes and no/ active and inactive?

Activity icon

Replied to Upload Images To Public/images Folder

There's a few tutorials on here. This one https://www.youtube.com/watch?v=N_i3UFw0_84 is great as well.

Activity icon

Started a new conversation Eloquent Relation WhereHas / With / Sum

Hi all,

I'm trying to get all Projects where status is Not active and Vendor balance for that project is Not 0.

The below gets me all Projects where status is Not active and (Vendor) Bid for that project is Not 0. It seems I need to replace where('amount' , '!=', 0) with something else but I can't seem to figure it out as there is a lot of variables.

        $balances = Project::whereHas('bids', function ($query) use ($vendor){
            $query->where('amount' , '!=', 0)->where('vendor_id', $vendor->id);
            
        })->with(['bids' => function ($query) { // use ($vendor)
            $query->get()->where('latestStatus.title_id', '!=', 5);
        }])->get();

To get the Vendor Balance for a projects I need to sum all Expenses for the vendor for each Project and subtract that from the Bid('amount'). Everything is on separate tables and I can elaborate as well.

Any any help is appreciated. Writing here and thinking through my issue really helps and everyone is really helpful.

Thanks! Patryk

Activity icon

Replied to How Do You Work With Two Tables That Doesn't Have The Same Eloquent Relationship In The Same Controller

These actually have a relationship.

Stocks hasMany Recivings and Recivings belongsTo Stocks....Or maybe one to one? Your connecting key here is product_id.

In the docs there's a section in the One to One article about using foreign keys https://laravel.com/docs/5.4/eloquent-relationships#one-to-one

Once you have that you should be easily be able to change the stock_count on the Stocks from the ReceivingController.

use App\Stock;

ReceivingController

$item= Stock::findOrFail($request->product_id);
$item->stock_count = $item->stock_count + $request->unit;
$item->update();
Activity icon

Replied to WhereHas Latest Child Equals A Value

Wow, this was difficult for me.

On my Project Model

    public function scopeActive($query){
        return $query->with('latestStatus')->get()->where('latestStatus.title_id', 5);
    }
    public function latestStatus(){
        return $this->hasOne('App\Projectstatus')->latest();
    }
May
02
2 years ago
Activity icon

Replied to WhereHas Latest Child Equals A Value

So I can get what I'm looking for with this

public function latestStatus(){
        return $this->hasOne('App\Projectstatus')->latest()->limit(1)->first()->title_id;
    } 

This returns 4,5,6, etc. and then I can easily use this, however how would I make this work in a scope?

Activity icon

Replied to Problem With Edit Method (Resource Model Binding)

Shouldn't this public function edit(languages $language) Look like this public function edit(Language $language) I believe the edit method expects a single result?

And where are you getting your results? Your query should end with all() or get etc. I believe this is why you're getting a collection and not a single result in your foreach

Activity icon

Replied to Finding A Way To Display 3 Values Simultaneously.

What do you mean? Please be more specific and use Use Markdown with GitHub-flavored code blocks. when commenting your code.

Activity icon

Replied to WhereHas Problem

I have a very similar problem I can't wrap my head around https://laracasts.com/discuss/channels/eloquent/get-model-where-latest-hasmany-equals-a-value

I have a Project and Projectstatus models. I need to get all the Projects that have a status_id of 5 (Active).

$projects = Project::whereHas('projectstatuses', function ($query) {
    $query->latest()->where('status_id', 5);
})->get();

This gives me all Projects as long as they have status_id of 5, it doesn't matter if status_id 6 or 7 or 8 was created after the status_id 5.

It shows as active, even if the project is in another state.

Any pointers would be much appreciated. -Patryk

Activity icon

Replied to WhereHas Latest Child Equals A Value

@Bandab Actually, I jumped the gun because that still gives me all Projects as long as they have status_id of 5, it doesn't matter if status_id 6 or 7 or 8 was created after the status_id 5.

It shows as active, even if the project is in another state.

Activity icon

Replied to WhereHas Latest Child Equals A Value

@Bandab Thanks Darek --- I thought I tried every $query->where/latest last night. This works great and is very clean. Exactly what I was hoping for.

Activity icon

Replied to How To Append User Id With Checkbox Value?

I would do something like this:

In your view:

@foreach ($students as $student)

    <ul class="list-group">
        <li class="list-group-item"><input type="checkbox" checked value="1" name="stud_id[]">Present</li>
<li class="list-group-item"><input type="checkbox" value="2" name="stud_id[]">Absent</li>
    </ul>

//Put Hidden Input here with the $student->id
@endforeach

In your controller:

    $count = count($request->student_id);
    for($i = 0; $i < $count; ++$i){
        if($request->student_id[$i] == null){
        //If this student doen't have 1 or 2 checked, do nothing. Not really for your case scenario but I don't see why not leave this as a safeguard. 
        } else {
            //CREATE this student attendance row.
        }       
    }   

Activity icon

Replied to Create User With Unique Email Stored In Another Table

Hmm, what's the result of dd($this->email)? If it's not an array, and it shouldn't be, then the unique rule is not the problem?

On the update request make sure you're ignoring the current user's email:

 'email' => [
        'required',
        Rule::unique('users')->ignore($user->id),
    ],

https://laravel.com/docs/5.4/validation#rule-unique

Activity icon

Replied to Latest Record From Relationship In WhereHas()

I'm having a very similar problem and I can't seen to figure it out. Any update on this? https://laracasts.com/discuss/channels/eloquent/get-model-where-latest-hasmany-equals-a-value

May
01
2 years ago
Activity icon

Started a new conversation WhereHas Latest Child Equals A Value

Hi all,

Besides my problem, I'm really struggling with queries / Eloquent ... any pointes to good tutorials? (summing ->groupBy , etc).

I have a Project(hasMany) and Projectstatus(belongsTo) models. I'm trying to get all Projects where the latest('created_at') Projectstatus('status_id') for this/these Projects is 5:

This is what I have so far:

$projects = Project::whereHas('projectstatuses', function ($query) {
    $query->where('status_id', 5);
        })->get();

This returns all projects where status_id on the projectstatus table = 5, but a Project can have a few statuses throughout it's cycle. I only need this to get projects where the latest('created_at) title_id = 5.

Something like latest()->where('status_id', 5)->first() ? Where would I even put that?

After I figure this out, would this end up in the Model so I can call something like Project::active() to get all active projects?

Thanks so [email protected]! -Patryk

Apr
19
2 years ago
Activity icon

Replied to Array Validation With A Unique Rule (Ignore)

@jlucia Thanks so much! Unfortunately, I too, have put a pin in this and moved on. I hope to come back to this and find a solution.

Activity icon

Replied to Is There Any Way To Ask In Laravel 5.1 Via A @if If The Updated_at Field Was Changed?

If you want to track everytime a change was made, you can create a pivot table (many to many relationship) that would keep track of every update timestamp.

Activity icon

Started a new conversation Nested Users With One Query

Hi all,

I have Vendors and when I'm in my Parent Vendor, I want to get all users (Direct users and users of Vendors that belong to the parent vendor).

The basics of the structure:

Vendor 1
---User 1
---User 2
---Vendor 2 (belongs to Vendor 1 via a belongs_to column on the Vendors table.)
------User 3
------User 4

Vendor 3
---User 5
---User 6

Vendor 4
---User 7
---User 8
---Vendor 5
------User 9
------User 10
---Vendor 6
------User 11
------User 12
App\Vendor::find(1)->users()->get(); //Should Result in Array of User 1,2,3,4 

But, of course,

App\Vendor::find(2)->users()->get(); //Will Result in Array of User 3,4 only 

I should mention that the belongs_to column is on the Vendors table, not the User table. Simply because if Vendor 2 is no longer part of Vendor 1, all the Users of Vendor 2 will no longer show on Vendor 1.

This is what I have so far:

$vendor = Auth::user()->vendor_id;

        $vendors = Vendor::where('belongs_to', $vendor)->get();

        $vendors = [];
        foreach ($vendors as $key => $vendor)
        {
            $vendors[] = $vendor->id;
        }

        return $query->whereIn('vendor_id', $vendors);   
    //In the controller this query would look like this:
    App\User::wherein('vendor_id', $vendors);

It's a little messy but by far the best I can come up with. I'm running 2 queries and have a foreach. Ideally, I want to call this inline, with just one query:

App\User::whereIn('vendor_id', $vendors)->orWhere('vendor_id', $vendor);   

I've tried a few approaches and what I have above works great. The problem I have with it is that it runs 2 separate queries... and I can almost feel that this can be done with one query as I described above. If you think I'm wasting my time trying to fix something that works as it's meant to, please tell me too!

-Patryk

Activity icon

Replied to Combine Queries Into One Collection

How can this be done in one query? The above helped me, but wish I knew how to do this in one run.

Apr
14
2 years ago
Activity icon

Replied to Unselect A Best Answer

yes, please, how?

Activity icon

Replied to Form Redirect To Antother Create Method Keeps Url Of Last

@jobcerto I think I can make that work, I will do so now. I think I saw the nested in 5.1 docs, but they've been taken off in 5.2?

My big question now is, technically, couldn't a user (even if he's Auth'ed) type in clients/{any client that exists}/projects/create into the url and automatically associate the {} client with the project he's about to create? even if by mistake?