MarianoMoreyra

Member Since 7 Months Ago

Buenos Aires

Experience Points
118,190
Total
Experience

1,810 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
268
Lessons
Completed
Best Reply Awards
147
Best Reply
Awards
  • start your 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-in-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 Created with Sketch.

    Subscriber

    Earned if you are a paying Laracasts subscriber.

  • lifer Created with Sketch.

    Lifer

    Earned if you have a lifetime subscription to Laracasts.

  • evangelist 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.

  • Community Pillar

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

Level 24
118,190 XP
Feb
25
14 hours ago
Activity icon

Awarded Best Reply on Laravel / Breeze / Inertia - Display Vue.version

@pc579 it seems you are using Vue 3 maybe?

Try the following:

require('./bootstrap');

// Import modules...
import { createApp, h } from 'vue';
import { App as InertiaApp, plugin as InertiaPlugin } from '@inertiajs/inertia-vue3';
import { InertiaProgress } from '@inertiajs/progress';

const el = document.getElementById('app');

createApp({
    data: function()
    {
        return { 
            vueVersion: Vue.version 
        }
    },
    render: () =>
        h(InertiaApp, {
            initialPage: JSON.parse(el.dataset.page),
            resolveComponent: (name) => require(`./Pages/${name}`).default,
        }),
})
    .mixin({ methods: { route } })
    .use(InertiaPlugin)
    .mount(el);

InertiaProgress.init({ color: '#4B5563' });

and then at Welcome.vue, as suggested in my previous reply:

Laravel v{{ laravelVersion }} (PHP v{{ phpVersion }}) + Vue v{{this.$root.vueVersion}}
Feb
24
1 day ago
Activity icon

Replied to Laravel / Breeze / Inertia - Display Vue.version

@pc579 it seems you are using Vue 3 maybe?

Try the following:

require('./bootstrap');

// Import modules...
import { createApp, h } from 'vue';
import { App as InertiaApp, plugin as InertiaPlugin } from '@inertiajs/inertia-vue3';
import { InertiaProgress } from '@inertiajs/progress';

const el = document.getElementById('app');

createApp({
    data: function()
    {
        return { 
            vueVersion: Vue.version 
        }
    },
    render: () =>
        h(InertiaApp, {
            initialPage: JSON.parse(el.dataset.page),
            resolveComponent: (name) => require(`./Pages/${name}`).default,
        }),
})
    .mixin({ methods: { route } })
    .use(InertiaPlugin)
    .mount(el);

InertiaProgress.init({ color: '#4B5563' });

and then at Welcome.vue, as suggested in my previous reply:

Laravel v{{ laravelVersion }} (PHP v{{ phpVersion }}) + Vue v{{this.$root.vueVersion}}
Activity icon

Replied to Laravel / Breeze / Inertia - Display Vue.version

Hi @pc579

Just add the following data at your resources\js\app.js file:

new Vue({
    data: function()
    {
        return { 
            vueVersion: Vue.version 
        }
    },
//...

Then you can access this 'global' state with this.$root.vueVersion at your components. In your case, at Welcome.vue you can do for example:

Laravel v{{ laravelVersion }} (PHP v{{ phpVersion }}) + Vue v{{this.$root.vueVersion}}

Hope this helps!

Feb
23
2 days ago
Activity icon

Replied to What's The True Benefit Of Using SaveOrFail() Instead Of Save()?

Hi @shingomaeda

I believe that the only case where it makes a difference is when you add a ->onUpdate('cascade') constraint to the corresponding table at your migration:

$table->foreignId('user_id')
      ->constrained()
      ->onUpdate('cascade')

ref: https://laravel.com/docs/8.x/migrations#foreign-key-constraints

In that case, if you just use save (without transaction handling) you may end with some corrupted data. Anyway, I understand that onUpdate('cascade') only takes effect when you change the Primary Key of the Parent table, which is something you won't usually want to do or allow.

Hope this helps!

Activity icon

Replied to Getting A Null When Console.log(this.user)

Hi @ifrit

If what you are trying to achieve is to pass the authenticated User from Laravel to Vue, you should do something like this:

@extends('layouts.app')
@section('content')
  <div id="app">
    <create-product :user="{{ $user }}"/>
  </div>
@endsection

Of course, this assuming you are passing the $user from the Controller.

Also, be really careful about this, as you might be exposing User data that you may not want to expose!

Hope this helps

Feb
09
2 weeks ago
Activity icon

Awarded Best Reply on Passing Data To A Modal

I'm sorry @jgonsuron

You probably already solved this. But just in case you haven't, try this at the blade:

<div wire:click="showModal({{$user->id}})" :users="$user" :key="$user" class="cursor-pointer">
                            {{ $user->name }} 
                        </div>

I forgot that this is the way to pass the parameters in Livewire:

ref: https://laravel-livewire.com/docs/2.x/actions#action-parameters

And then at the Component, type hint the User as you already did before:

    public function showModal(User $user) 
    {
        $this->selectedUser = $user;
        $this->modalFormVisable = true;
    }

Finally, at the Modal, this is the way it should work now the event parameter is passed as supposed:

<x-slot name="title">
            {{ $selectedUser->name ?? ''}}
        </x-slot>
Feb
08
2 weeks ago
Activity icon

Replied to Passing Data To A Modal

That's weird @jgonsuron

I've just reproduce this locally as suggested in my last reply and it's working for me! So just to be sure...you tried changing the showModal call to pass the id like this?

showModal( {{$user->id}} )

with the curly braces around the $user->id?

Anyway, I understand your frustration, although you may encounter similar problems with Vue and Inertia, or even with vanilla JavaScript, since sometimes there is a little detail that we are missing.

Hope you get to make this work with whatever you choose to work with!

Activity icon

Replied to Passing Data To A Modal

I'm sorry @jgonsuron

You probably already solved this. But just in case you haven't, try this at the blade:

<div wire:click="showModal({{$user->id}})" :users="$user" :key="$user" class="cursor-pointer">
                            {{ $user->name }} 
                        </div>

I forgot that this is the way to pass the parameters in Livewire:

ref: https://laravel-livewire.com/docs/2.x/actions#action-parameters

And then at the Component, type hint the User as you already did before:

    public function showModal(User $user) 
    {
        $this->selectedUser = $user;
        $this->modalFormVisable = true;
    }

Finally, at the Modal, this is the way it should work now the event parameter is passed as supposed:

<x-slot name="title">
            {{ $selectedUser->name ?? ''}}
        </x-slot>
Feb
06
2 weeks ago
Activity icon

Replied to Passing Data To A Modal

@jgonsuron you’ve missed the first part of my original post.

You have to pass the corresponding user at the click event:

<div wire:click="showModal($user)" :users="$user" :key="$user" class="cursor-pointer">
                            {{ $user->name }} 
                        </div>

If it doesn’t work with the added type hint, try removing it after adding the parameter to the click call

Feb
05
2 weeks ago
Activity icon

Replied to Passing Data To A Modal

@jgonsuron

Just in case, please post the entire code of the component to check it again.

Activity icon

Replied to Passing Data To A Modal

@jgonsuron

I see...you have to either initialize the variable (new User) or check for nulls at the modal:

<x-jet-dialog-modal wire:model="modalFormVisable">
        <x-slot name="title">
            {{ $selectedUser->name ?? '' }}
        </x-slot>

        <x-slot name="content">
            
            <div class="mt-4">
                <img src="{{ $selectedUser->profile_photo_url ?? '' }}" alt="{{ $selectedUser->name ?? '' }}'s Profile picture" class="rounded-full h-10 w-10 object-cover mr-2">
                
            </div>
                        
            
        </x-slot>

Hope it works now!

Activity icon

Replied to Passing Data To A Modal

Hi @jgonsuron

I’d add a public $selectedUser to your component do you can then pass the corresponding user to the showModal method:

< div wire:click="showModal($user)" :users="$user" :key="$user" class="cursor-pointer">
                            {{ $user->name }} 
                        </div>

Then at the showModal method:

    public function showModal($user) 
    {
        $this->selectedUser = $user;
        $this->modalFormVisable = true;
    }

And finally you reference the selectedUser at your modal:

     <x-jet-dialog-modal wire:model="modalFormVisable">
        <x-slot name="title">
            {{ $selectedUser->name }}
        </x-slot>

        <x-slot name="content">
            
            <div class="mt-4">
                <img src="{{ $selectedUser->profile_photo_url }}" alt="{{ $selectedUser->name }}'s Profile picture" class="rounded-full h-10 w-10 object-cover mr-2">
                
            </div>
                        
            
        </x-slot>

Hope this works!!

You’ll probably have to do some adjustsments tho, as I’m writing this from my phone so I’m sure there must be some typos

Feb
02
3 weeks ago
Activity icon

Awarded Best Reply on $fillable Array Error

Hi @mkuilen

Try removing thearray keyword and just leave it like:

protected $fillable = [];

Hope this helps!

Activity icon

Replied to $fillable Array Error

Hi @mkuilen

Try removing thearray keyword and just leave it like:

protected $fillable = [];

Hope this helps!

Feb
01
3 weeks ago
Activity icon

Replied to How To Loop Through Saved Enum Values From Db And Show Them As A List In Blade ?

Hi @tinkerbell

I'm pretty sure that @nimrod was just giving an example, assuming that you wanted to list user roles, based on the code snippet you've shared.

Anyway, do you have a Model for the table with the information to show in the select list?

I'll assume you have a Model, and that it's called Type. Also, I'm assuming the table has to fields, named id and name.

With that scenario, you can get all the Types to list, as nimrod suggested, by doing something like this at your controller:

$types = Type::all();

and passing $types to the view where you want to render the dropdown/list.

Then at your view you'll do something like this:

<select id="user_type" name="user_type">
    @foreach($types as $type)
        <option value="{{$type->id}}">{{$type->name}}</option>
    @endforeach
</select>

Again...it's just an example...you'll have to change it to match your Model and fields. Also, I've simplified a lot the example. You'll probably want to add the possibility to keep the selection in case you have to show a validation error after submitting the form, but let's leave that for a future question, once you get this working.

Finally, as previously suggested, I'll recommend to watch the Laravel 6 from scratch series and/or some other video tutorial, like the ones from Coder's Tape in YouTube to get the grip of the basics of the framework.

Hope this helps!

Activity icon

Awarded Best Reply on How To Set Condition In Maatwebsite Laravel/Excel Upload

Hi @noblemfd

To make it really simple, you could create to private associative arrays with the provided information, and then use the null coalescing operator to assign the corresponding value or null to those fields.

Something like this for the arrays:

class FirstLeaveSheetImport implements ToModel, WithHeadingRow, WithBatchInserts, WithValidation
{
    protected $staffid;
    private $errors = []; 
    private $leave_type = ['Annual' => 0, 'Maternity' => 1, 'Paternity' => 2];
    private $gender = ['Female' => 0, 'Male' => 1];

    use Importable;

and then model method:

public function model(array $row)
{   
   $this->staffid = $row['staff_id'];

    return new HrLeaveRequest([
        'employee_id'              => $this->getStaffId(),
        'leave_type'               => $this->leave_type[$row['leave_type']] ?? null, 
        'commencement_date'        => $this->transformDate($row['commencement_date']),
        'resumption_date'          => $this->transformDate($row['resumption_date']),
        'company_id'               => Auth::user()->company_id,
        'gender'                   => $this->gender[$row['gender']] ?? null, 
    ]);        
}

Hope this works for you!

Jan
31
3 weeks ago
Activity icon

Replied to Vue Style Return Value From Method Or Computed

Hi @stelikas

It worked for me, so maybe the v-card is overriding (or not merging) the style you are passing, or any other global styles.

What happens if you append a !important to the style?

 <v-card @click="displayAmendments(article)" :style="needsApprove(article) ? 'background: black !important;' : ''">

Hope this helps

Jan
30
3 weeks ago
Activity icon

Replied to How To Set Condition In Maatwebsite Laravel/Excel Upload

Hi @noblemfd

To make it really simple, you could create to private associative arrays with the provided information, and then use the null coalescing operator to assign the corresponding value or null to those fields.

Something like this for the arrays:

class FirstLeaveSheetImport implements ToModel, WithHeadingRow, WithBatchInserts, WithValidation
{
    protected $staffid;
    private $errors = []; 
    private $leave_type = ['Annual' => 0, 'Maternity' => 1, 'Paternity' => 2];
    private $gender = ['Female' => 0, 'Male' => 1];

    use Importable;

and then model method:

public function model(array $row)
{   
   $this->staffid = $row['staff_id'];

    return new HrLeaveRequest([
        'employee_id'              => $this->getStaffId(),
        'leave_type'               => $this->leave_type[$row['leave_type']] ?? null, 
        'commencement_date'        => $this->transformDate($row['commencement_date']),
        'resumption_date'          => $this->transformDate($row['resumption_date']),
        'company_id'               => Auth::user()->company_id,
        'gender'                   => $this->gender[$row['gender']] ?? null, 
    ]);        
}

Hope this works for you!

Jan
28
4 weeks ago
Activity icon

Awarded Best Reply on Missing Required Parameter For [Route: Application.index] [URI: Application/{id}] [Missing Parameter: Id].

@artisticre

Anyway, if you have a form with a similar route calling, but with application.index instead, you are probably missing the ID parameter. You should do something like:

<form method="POST" action="{{ route('application.submit', ['id' => $id]) }}" enctype="multipart/form-data">

ref: https://laravel.com/docs/8.x/routing#generating-urls-to-named-routes

Hope this helps

Activity icon

Replied to Htmlspecialchars() Expects Parameter 1 To Be String, Object Given

Well @emfinanga my solution did work regarding the error you were having.

Now this is a complete different problem, nothing to do with the original error neither with my answer, but there was no way to asume all this from your previous reply.

Anyway, I’ll see if I can help you with this too. Although I’d recommend being more explicit with your answers to solutions provided, otherwise it gets really difficult to help :)

Activity icon

Replied to Htmlspecialchars() Expects Parameter 1 To Be String, Object Given

Hi @emfinanga

Take a look to this line:

<option value="{{$key}}" @if($key == $editbillinfo->unit_issue_id) selected @endif>{{$dt}}</option>

You are trying to render $dt there, which is an object. Try choosing a property from that object and see if it works. Example:

<option value="{{$key}}" @if($key == $editbillinfo->unit_issue_id) selected @endif>{{$dt->devicetype}}</option>

Hope this works for you

Activity icon

Replied to Display Of New Data Without Refresh Laravel + Vue

Hi @myirlik

Normally you’ll do something like:

data() {
            return {
              qualifying:[],
     
            }
        },

addQualifying(id) {
    axios.post('qualifying/' + id)
        .then( res => {
            this.qualifying = res.data
        })                  
    }

Or I’m I missing something and you need something different?

Hope this helps!

Activity icon

Replied to How To Display Dynamic Navigation Bar From Blade Template

You’re welcome @codemaster96

If this actually works for you, please remember to mark the question as replied so others can found this solution easier on the future

Activity icon

Replied to How To Display Dynamic Navigation Bar From Blade Template

Hi @codemaster96

You have to use View Composers to achieve what you want:

https://laravel.com/docs/8.x/views#view-composers

Here is a reply I gave in another post explaining it step by step.

https://laracasts.com/discuss/channels/laravel/how-to-get-dynamic-data-into-a-layout-file?page=1#reply=677055

Hope this helps!

Jan
27
4 weeks ago
Activity icon

Replied to Missing Required Parameter For [Route: Application.index] [URI: Application/{id}] [Missing Parameter: Id].

@artisticre

Anyway, if you have a form with a similar route calling, but with application.index instead, you are probably missing the ID parameter. You should do something like:

<form method="POST" action="{{ route('application.submit', ['id' => $id]) }}" enctype="multipart/form-data">

ref: https://laravel.com/docs/8.x/routing#generating-urls-to-named-routes

Hope this helps

Activity icon

Replied to Missing Required Parameter For [Route: Application.index] [URI: Application/{id}] [Missing Parameter: Id].

Hi @artisticre

The route requested at the form action doesn't match the one of the error.

Please paste the form, link or button where you are calling application.index instead of application.submit

Activity icon

Replied to Sum HTML Table Columns Using Livewire

I'm glad it worked @pokeycam !!

I've fixed the typo in my previous reply for anyone needing the same solution, thanks for pointing that out!

Again, I'm glad that I was able to help!

Activity icon

Awarded Best Reply on Sum HTML Table Columns Using Livewire

Hi @pokeycam

Maybe you could wire the keydown event on each input, so you can trigger a sum function. Something like this:

livewire\timesheet.blade.php

...
<td class='content-center px-2'>
<input type='text' name='entries[{{$index}}][hours_sun]' 
    wire:model='entries.{{$index}}.hours_sun' 
    class='border-2 border-gray-300 rounded w-16 text-lg p-2 text-center disabled:opacity-25' 
    @if($day['locked'] == 1) disabled @endif
    wire:keydown="sumColum('hours_sun')"
>
</td>
...

then you add the sumColumn() method along with corresponding public variables to hold the totals: Controllers\Livewire\ShowTimesheet.php

public $totals =  [
    'total_mon',
    'total_tue',
    'total_wed',
    'total_thu',
    'total_fri',
    'total_sat',
    'total_sun',
]

public function sumColumn($columnName)
{
    $this->totals[$columnName] = array_reduce($this->entries, function($total, $item) use ($columnName) {
        $total += $item[$columnName];

        return $total;
    });
}

And finally you just need to add a row at the end of your table where to render the $totals array.

Please, have into consideration that I'm writing this on-the-fly and didn't have the chance to test it, so you'll surely need to do some adjustments to make it work, although I guess it is a good starting point!!

Hope it makes sense to you and that you can make it work!

Jan
26
4 weeks ago
Activity icon

Replied to How Do I Package An Artisan Command In Order To Share It With The Community?

Hi @m615

You may want to take a look at this package with tools to make packages:

https://github.com/spatie/laravel-package-tools

It's from Spatie, so you can be sure it's high quality!

Also, they have a skeleton for Laravel packages that might be useful too:

https://github.com/spatie/package-skeleton-laravel

Finally, if you have the chance to spend a few bucks, they have an excellent video course on the topic:

https://spatie.be/products/laravel-package-training

Hope this helps and looking forward to your brand new package!

Activity icon

Awarded Best Reply on Apache Settings

Hi @tovisbratsburg

The second one is the right one for two reasons:

  1. You need to have a <Directory> block matching your DocumentRoot in order to configure it
  2. You don't want to allow anything at /var/www/laravel as there is where it lives your .env file with all your sensitive credentials!

Hope this helps!

Activity icon

Replied to Apache Settings

Hi @tovisbratsburg

The second one is the right one for two reasons:

  1. You need to have a <Directory> block matching your DocumentRoot in order to configure it
  2. You don't want to allow anything at /var/www/laravel as there is where it lives your .env file with all your sensitive credentials!

Hope this helps!

Activity icon

Awarded Best Reply on Laravel Dependent Dropdown Check

Hi @www888

It’s passes because empty string “” is not null in JavaScript. Try with the following:

             if(a_id != “” && b_id != “” && c_id != “”) {
                $.ajax({
                    url: "{{  url('/get/') }}/"+a_id+"/"+b_id+"/"+c_id,
                    type:"POST",
                    dataType:"json",
                    success:function(data) {
                      if(data){
                        $("#p").empty();  
                           ///
console.log(data); 
     
                      }else{ $("#p").empty();} 
                    },
                });
            } else {$("#p").empty();} 

Hope this works

Activity icon

Replied to Laravel Dependent Dropdown Check

Hi @www888

It’s passes because empty string “” is not null in JavaScript. Try with the following:

             if(a_id != “” && b_id != “” && c_id != “”) {
                $.ajax({
                    url: "{{  url('/get/') }}/"+a_id+"/"+b_id+"/"+c_id,
                    type:"POST",
                    dataType:"json",
                    success:function(data) {
                      if(data){
                        $("#p").empty();  
                           ///
console.log(data); 
     
                      }else{ $("#p").empty();} 
                    },
                });
            } else {$("#p").empty();} 

Hope this works

Jan
25
1 month ago
Activity icon

Replied to Add Vuejs + Vuetify To My Laravel 8 Running With Sail Script (for A Fullstack Developer)

HI @leostereo

Had the chance to try my solution? Did it work?

Got intrigued :)

Jan
24
1 month ago
Activity icon

Replied to Add Vuejs + Vuetify To My Laravel 8 Running With Sail Script (for A Fullstack Developer)

Nada que agradecer @leostereo

Regarding the link, just pay attention to the material design part. Just run:

$ npm install @mdi/font -D

And the, at your resources\sass\app.scss file add the following:

// Material Design Icons
@import '[email protected]/font/css/materialdesignicons.min.css';

Finally run:

npm run dev

And you should be able to use the icons simply by adding something like this at your code:

<v-icon>mdi-view-dashboard</v-icon>
<v-icon>mdi-cog</v-icon>

Let me know if that worked for you!

Activity icon

Replied to Add Vuejs + Vuetify To My Laravel 8 Running With Sail Script (for A Fullstack Developer)

Hi @leostereo

Haven’t had the opportunity to test this myself but I guess is what you might be needing:

https://vuetifyjs.com/en/features/icon-fonts/#material-icons

Let me know if it works! I’ll try to test it later too!

Hope this helps

Jan
23
1 month ago
Activity icon

Replied to Appending Query String Values

That's great @warpig !!

Happy to be of help!

Regarding ->withQueryString() I believe that maybe you'll need to use it in addition to ->appends to add the Tag that was selected to the pagination links, otherwise I understand that if you click on a page as it is right now, you'll be loosing the Tag filter...

Activity icon

Awarded Best Reply on Appending Query String Values

@warpig

Well...first of all, this two routes are basically the same for Laravel:

Route::get(
    'posts/{slug}',
    [PostsController::class, 'show']
);

Route::get('posts/{tag}', function () {
    $tag = Tag::simplePaginate()->withQueryString();

    $tag->appends(['name' => 'tag']);

    return view('posts.index', ['tag' => $tag]);
});

Since Laravel doesn't have a way to determine when you are passing a slug or a tag as a parameter. So basically, it will always go to the route that comes first in your routes file. I will take a guess and say that the 'posts/{slug}' one comes first...

Anyway, I believe the error that you've shared on flare saying that $posts doesn't have a ::links method, it has to be with the if on your index method from Controller...as you are not paginating there: Maybe this will work:

    public function index(Category $category)
    {   
        if (request('tag')) {
        $post = Tag::where('name', request('tag'))
                ->firstOrFail()
                ->posts()      // it needs the () otherwise you'll keep getting that error
                ->simplePaginate(5); // <--- this was missing
    } else {
        $post = Post::latest()->simplePaginate(5);
        $category = Category::select('image_url')->get();
    }   
        return view('posts.index', [
            'posts' => $post,
            'category' => $category
        ]);
    }

You may want to add the ->withQueryString() after the ->paginate(5) in both cases (the if and the else) if you want, but I'd recommend to solve one problem at a time.

And finally, at the view just call the links for now (as you were originally doing):

<span> {{ $posts->links() }} </span>

Hope this works or at least, starts to solve some problems!!

Activity icon

Replied to Appending Query String Values

@warpig

Well...first of all, this two routes are basically the same for Laravel:

Route::get(
    'posts/{slug}',
    [PostsController::class, 'show']
);

Route::get('posts/{tag}', function () {
    $tag = Tag::simplePaginate()->withQueryString();

    $tag->appends(['name' => 'tag']);

    return view('posts.index', ['tag' => $tag]);
});

Since Laravel doesn't have a way to determine when you are passing a slug or a tag as a parameter. So basically, it will always go to the route that comes first in your routes file. I will take a guess and say that the 'posts/{slug}' one comes first...

Anyway, I believe the error that you've shared on flare saying that $posts doesn't have a ::links method, it has to be with the if on your index method from Controller...as you are not paginating there: Maybe this will work:

    public function index(Category $category)
    {   
        if (request('tag')) {
        $post = Tag::where('name', request('tag'))
                ->firstOrFail()
                ->posts()      // it needs the () otherwise you'll keep getting that error
                ->simplePaginate(5); // <--- this was missing
    } else {
        $post = Post::latest()->simplePaginate(5);
        $category = Category::select('image_url')->get();
    }   
        return view('posts.index', [
            'posts' => $post,
            'category' => $category
        ]);
    }

You may want to add the ->withQueryString() after the ->paginate(5) in both cases (the if and the else) if you want, but I'd recommend to solve one problem at a time.

And finally, at the view just call the links for now (as you were originally doing):

<span> {{ $posts->links() }} </span>

Hope this works or at least, starts to solve some problems!!

Activity icon

Replied to Appending Query String Values

@warpig I'm sorry but I'm still a little bit confused...

Are you displaying Posts or Tags? In case you are displaying (and hence, paginating) Posts, I believe you should have the Post in the Route parameter, but most importantly, you should be doing the simplePaginate on your Post model instead of Tag.

whenever I want to sort the posts by clicking on a given tag, the exceptions begin to emerge.

I don't see how you might be ordering based on a selected Tag...or do you mean you are filtering the results to show only the Posts that have the selected Tag?

Now from the error shared on flare...it seems to me that you might be having different routes that catch by mistake the URL you are trying to access...

Also, you are looping over a $posts variable and doing $posts->links() but this code is not sending $posts to that view, but $tags instead:

Route::get('posts/{tag}', function () {
    $tag = Tag::simplePaginate()->withQueryString();

    $tag->appends(['name' => 'tag']);

    return view('posts.index', ['tag' => $tag]);
});

If you want/can please share the rest of the routes involved with Posts and Tags to see if there is any definitions colliding.

Activity icon

Replied to Appending Query String Values

Hi @warpig

I'm sorry but I'm not understanding your question.

On one side, the error says:

Undefined variable: posts in Posts.Index

but on the other side, you show a route that returns the posts.show view and not the Posts.Index:

return view('posts.show');

So I'm not sure if the error is related to the appends or is occurring somewhere else.

Also, it's not clear what the final result should be...

Hope you can give some more insights so I can try to help!

Activity icon

Replied to Sum HTML Table Columns Using Livewire

Hi @pokeycam

Maybe you could wire the keydown event on each input, so you can trigger a sum function. Something like this:

livewire\timesheet.blade.php

...
<td class='content-center px-2'>
<input type='text' name='entries[{{$index}}][hours_sun]' 
    wire:model='entries.{{$index}}.hours_sun' 
    class='border-2 border-gray-300 rounded w-16 text-lg p-2 text-center disabled:opacity-25' 
    @if($day['locked'] == 1) disabled @endif
    wire:keydown="sumColum('hours_sun')"
>
</td>
...

then you add the sumColumn() method along with corresponding public variables to hold the totals: Controllers\Livewire\ShowTimesheet.php

public $totals =  [
    'total_mon',
    'total_tue',
    'total_wed',
    'total_thu',
    'total_fri',
    'total_sat',
    'total_sun',
]

public function sumColumn($columnName)
{
    $this->totals[$columnName] = array_reduce($this->entries, function($total, $item) use ($columnName) {
        $total += $item[$columnName];

        return $total;
    });
}

And finally you just need to add a row at the end of your table where to render the $totals array.

Please, have into consideration that I'm writing this on-the-fly and didn't have the chance to test it, so you'll surely need to do some adjustments to make it work, although I guess it is a good starting point!!

Hope it makes sense to you and that you can make it work!

Jan
22
1 month ago
Activity icon

Awarded Best Reply on Eloquent - Where Clause In Anonymous Function Not Behaving As Expected

Hi @headdesk2

I’m not sure if with calls can be chained, so just in case I’d try the following:

	    $users = User::with(['usersSubscriptionFeesCollection' => function ($q) use ($value) {
                $q->where('settled','=','0');
            },
            'usersSubscription' => function ($q) use ($value) {
                $q->('active', '=', '1');
            }])
            ->where('active', '=', '1')
            ->get();

Hope this works!

Jan
21
1 month ago
Activity icon

Replied to Drilling Down To Get All Meals() Relations Of A BelongToMany Relationship

Hi @bmcn99

If I understand correctly, what you may be needing is Nested Eager Loading, in which case when you fetch the user, you fetch the school with all the restaurants with their meals:

Something like this:

$user = User::with('users_school.restaurants.meals')->find(user_id);

ref: https://laravel.com/docs/8.x/eloquent-relationships#nested-eager-loading

In case you need to work with an already fetched user, you may take a look at Lazy Nested Eager Loading, which may end in something like this:

$meals = $this
                ->users_school
                ->load('restaurants.meals')
                ->get();

https://laravel.com/docs/8.x/eloquent-relationships#nested-lazy-eager-loading-morphto

Hope this works for you!

Activity icon

Replied to Eloquent - Where Clause In Anonymous Function Not Behaving As Expected

Hi @headdesk2

I’m not sure if with calls can be chained, so just in case I’d try the following:

	    $users = User::with(['usersSubscriptionFeesCollection' => function ($q) use ($value) {
                $q->where('settled','=','0');
            },
            'usersSubscription' => function ($q) use ($value) {
                $q->('active', '=', '1');
            }])
            ->where('active', '=', '1')
            ->get();

Hope this works!

Jan
18
1 month ago
Activity icon

Replied to Vue.component Is Not A Function

Hi @reaz

No errors when you run npm run dev?

Also, just in case, that code is from \resources\js\app.js and not from \public\js\app.js right?

Jan
17
1 month ago