nurge

nurge

Member Since 7 Months Ago

Experience Points
12,110
Total
Experience

2,890 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
113
Lessons
Completed
Best Reply Awards
0
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.

Level 3
12,110 XP
Jul
30
1 month ago
Activity icon

Replied to How To Replace A Value From A Select() Method In Laravel

Amazing! thank you very much! Such an elegant solution Anna Kendrick! ;-)

Activity icon

Started a new Conversation How To Replace A Value From A Select() Method In Laravel

I have a model called 'GearItem' that has rows of gear items. One of the columns is called 'manufacturer_id'. - These are the id's of the 'Manufacturer' model that holds the data about the manufacturer of each gear item.

I have created a function in my GearItem controller called "getItemsNames" and I want it to return a JSON that will look like so:

[
{id: 1,
name: "foo",
manufacturer: "bar"}, 
{id: 2,
name: "baz",
manufacturer: "qux"},
{...}, 
]

How do I change the query GearItem::select('id', 'name', 'manufacturer_id')->get();

to replace the 'manufacturer_id' by $manufacturer[0]->name after I define:

$manufacturer = Manufacturer::select('name')
                            ->where('id', GearItem::value('manufacturer_id'))
                            ->get();

I don't know how to insert this logic without breaking the JSON structure. Is there an elegant way to do it or do I have to iterate through the JSON and replace every 'manufacturer_id' by the name?

Jul
22
2 months ago
Activity icon

Started a new Conversation Vue.js And Livewire Ignored When A Blade Is Included In Another Blade

Hi, I have created a product card view in Laravel. the card has a simple "accordion" ('Show Details') - closed by default - that is managed by Vue.js as well as a livewire quantity counter that changes the weight value in grams if you add products. It all functions very well on the card's view .

Then I have another view in which I query my DB for product names with Vue.js to display all products of the same name as a result. The problem is when the cards are displayed on that "parent" view, they all appear with the accordion open and the counter is not responsive.

The tailwindcss code is rendered without a problem but the Vue.js and LiveWire are being completely ignored (Although the parent view's Vue.js functions work perfectly) What am I doing wrong? What am I missing here? Why are the directives inside the included blade being ignored?

Here is the Vue.js method that manages the (product cards) views integration onto the parent (product name search) view:

        setGearItem(gearItem) {

            this.gearItem = gearItem;
            this.modal = false;
            console.log(gearItem);

            document.getElementById("displaySearch").innerHTML = "";

            axios.get('/send-name-get-ids/' + this.gearItem)
                .then((response) => {
                    console.log(response.data);
                    if (response.data.length === 0) {
                        document.getElementById("displaySearch").innerHTML = `"<strong>${gearItem}</strong>" was not found in our database. You can add it manually:`;
                        this.generalForm = true;
                        return;

                    } else {
                        for (let i = 0; i < response.data.length; i++) {
                            axios.get('/gearitem/' + response.data[i])
                                .then((response) => {
                                    console.log(response.data);
                                    document.getElementById("displaySearch").innerHTML += response.data;
                                    this.generalForm = false;
                                })
                                .catch((error) => {
                                    document.getElementById("displaySearch").innerHTML =
                                        "No items to display";
                                    console.log(error);
                                });
                        }
                    }
                });
        },

Jul
06
2 months ago
Activity icon

Replied to How To Include Several "show" Blades Inside An "index" Blade?

So I basically need to copy all the logic from show to index? isn't there a more elegant way? It's having nearly identical methods, no?

Activity icon

Replied to How To Include Several "show" Blades Inside An "index" Blade?

Tried it before asking, it doesn't work...

Activity icon

Replied to How To Include Several "show" Blades Inside An "index" Blade?

It's not a simple instance. I do quite a lot in the "Show" method to create the cards so I can't really pass everything in one variable. I will add my show method to the question for reference.

Activity icon

Started a new Conversation How To Include Several "show" Blades Inside An "index" Blade?

I have a "show" method in my controller that generates an 'id card' for each product in the database. I want to display the "show" blades as cards in the index blade how do I do that? I cannot use @include() because I cannot insert each of the products id's into the @include command or am I missing something here? Do I have to use ajax to get that or is there a more elegant Laravel way?

My show method in the controller:

 public function show(Manufacturer $manufacturer, GearItem $gearItem, GearCategory $gearCategory) // Needs to be cleaned and refactored
    { 
        // Get the item's special features Model's name:
        $featureModel =  'App\'.SpecialFeature::where('sub_categories_id', $gearItem->sub_categories_id)->value('model_name');

        // Get the manufacturer's name and homepage: 
        $manufacturer->name = $manufacturer::where('id', $gearItem->manufacturer_id)->value('name');
        $manufacturer->homepage = $manufacturer::where('id', $gearItem->manufacturer_id)->value('homepage');

        // Get all the item's special features and "clean" them: 
        $specialFeaturesValues = $featureModel::where('gear_items_id', $gearItem->id)->get();
        $specialFeaturesRejects = ['id' => 'xy', 'gear_items_id' => 'xy', 'created_at' => 'xy', 'updated_at' => 'xy'];
        $specialFeaturesClean = array_diff_key($specialFeaturesValues[0]->getAttributes(), $specialFeaturesRejects);

        // Get an array of boolean values: 
        $booleanFeatures = array_keys($specialFeaturesValues[0]->getCasts(), 'boolean');

        foreach($booleanFeatures as $booleanFeature){
            if ($specialFeaturesClean[$booleanFeature] > 0){
                $specialFeaturesClean[$booleanFeature] = 'Yes';
            } elseif($specialFeaturesClean[$booleanFeature] === 0){
                $specialFeaturesClean[$booleanFeature] = 'No';
            } else {
                $specialFeaturesClean[$booleanFeature] = 'Unknown';
            };
        }

        $featureTitles = SpecialFeature::where('sub_categories_id', $gearItem->sub_categories_id)->pluck('title');
        $sfv = array_values($specialFeaturesClean);
        $specialFeatures = array_combine($featureTitles->all() , $sfv);
        // dd($specialFeatures);

        return view('gearitem.show', compact(['gearCategory', 'manufacturer', 'gearItem', 'specialFeatures']));
    }
Jun
29
2 months ago
Activity icon

Awarded Best Reply on How To Query Column Type In Laravel And Retrieve Boolean Values?

So I found a solution for this problem:

In the model where there are boolean values that need to be queried add the name of the boolean feature as a key and 'boolean' as the value like so:

 protected $casts = [
        'waterproof' => 'boolean'
    ];

Then, in the controller:

// Get all the item's special features and "clean" them: 
        $specialFeaturesValues = $specialFeatures::where('gear_items_id', $gearItem->id)->get();
        $specialFeaturesRejects = ['id' => 'xy', 'gear_items_id' => 'xy', 'created_at' => 'xy', 'updated_at' => 'xy'];
        $specialFeaturesClean = array_diff_key($specialFeaturesValues[0]->getAttributes(), $specialFeaturesRejects);

  $booleanFeatures = array_keys($specialFeaturesValues[0]->getCasts(), 'boolean');

        foreach($booleanFeatures as $booleanFeature){
            if ($specialFeaturesClean[$booleanFeature] > 0){
                $specialFeaturesClean[$booleanFeature] = 'Yes';
            } elseif($specialFeaturesClean[$booleanFeature] === 0){
                $specialFeaturesClean[$booleanFeature] = 'No';
            } else {
                $specialFeaturesClean[$booleanFeature] = 'Unknown';
            };

        }

(don't forget to "send" the $specialFeaturesClean to the view with compact())

in the blade view, this simple foreach loop will display the "clean" values, replacing "1" (or any other truthy value) by "Yes", "0" by "No" and "Null" by "Unknown". (see picture for example)

enter image description here

I hope this is helpful... ;-)

Activity icon

Replied to How To Query Column Type In Laravel And Retrieve Boolean Values?

So I found a solution for this problem:

In the model where there are boolean values that need to be queried add the name of the boolean feature as a key and 'boolean' as the value like so:

 protected $casts = [
        'waterproof' => 'boolean'
    ];

Then, in the controller:

// Get all the item's special features and "clean" them: 
        $specialFeaturesValues = $specialFeatures::where('gear_items_id', $gearItem->id)->get();
        $specialFeaturesRejects = ['id' => 'xy', 'gear_items_id' => 'xy', 'created_at' => 'xy', 'updated_at' => 'xy'];
        $specialFeaturesClean = array_diff_key($specialFeaturesValues[0]->getAttributes(), $specialFeaturesRejects);

  $booleanFeatures = array_keys($specialFeaturesValues[0]->getCasts(), 'boolean');

        foreach($booleanFeatures as $booleanFeature){
            if ($specialFeaturesClean[$booleanFeature] > 0){
                $specialFeaturesClean[$booleanFeature] = 'Yes';
            } elseif($specialFeaturesClean[$booleanFeature] === 0){
                $specialFeaturesClean[$booleanFeature] = 'No';
            } else {
                $specialFeaturesClean[$booleanFeature] = 'Unknown';
            };

        }

(don't forget to "send" the $specialFeaturesClean to the view with compact())

in the blade view, this simple foreach loop will display the "clean" values, replacing "1" (or any other truthy value) by "Yes", "0" by "No" and "Null" by "Unknown". (see picture for example)

enter image description here

I hope this is helpful... ;-)

Jun
26
2 months ago
Activity icon

Replied to How To Query Column Type In Laravel And Retrieve Boolean Values?

So I do this in the model of each gear Item type like "Backpacks", "Tents" etc? So if i define all boolean attributes as a cast, then how can I tell whether or not my iterator stumbles upon a boolean column? I need to know if the value of a column is a boolean value of 1 or 0 WITHOUT knowledge of the the column's name. i.e I need to know whether "Waterproof" is a boolean column and whether "num_persons" isn't.

Activity icon

Started a new Conversation How To Query Column Type In Laravel And Retrieve Boolean Values?

Is there a way to be able to tell that a certain column in a given database table is of type "boolean" and if it is - convert the "0" or "1" into "No" and "Yes"?

I have a table called "gearitems" that has basic general info about hiking gear items (like price, weight, description etc) then I have nearly 60 other "one to one" relation tables (ex: "backpacks", "sleepingbags", "tents") that all have specific "special features" according to the type of gear that it is. For example, if it's a backpack it has the capacity in Liters but if it's a tent, the number of stakes required etc etc.

The problem I have, is that many of these small "special features" tables have boolean type columns with different names (like 'waterproof' in "backpacks" or 'attachable' in "sleepingbags" ) and when I want to show the user a specific gear piece, I have a function that will join the general "gearitems" table to the corresponding specific gear type table.

For all column types there is no problem displaying the data as it is inserted in the database but the boolean one returns "1" or "0"... I can't just convert all "1" and "0" into "yes" or "no" as other values might be 1 or 0 which ARE NOT boolean. So I figured, that if I could check whether the column type IS of boolean type data I could then safely convert the values into yes or no but how can I do so without specifically targeting the column's name? (as the list of all boolean-type columns will be too long and hard to edit in the future)

I have created a table called "specialfeatures" that contains a list of all the names of the special features (like "waterproof", "stakes_required" "capacity_l" etc) in each table of every gear type ("backpacks", sllepingbags" etc). I thought about adding a column called "boolean" next to the special_features_name column to indicate if that feature is boolean or not but it seems like a very crude and non elegant way to do it. Surely there's a better way?

If it helps, here are the relevant parts in my code:

My controller:

public function show(Manufacturer $manufacturer, GearItem $gearItem, GearCategory $gearCategory)
    { 
        // Get the item's special features Model's name:
        $featureModel = SpecialFeature::where('sub_categories_id', $gearItem->sub_categories_id)->value('model_name');
        $specialFeatures =  'App\'.$featureModel;

        // Get the manufacturer's name and homepage: 
        $manufacturer->name = $manufacturer::where('id', $gearItem->manufacturer_id)->value('name');
        $manufacturer->homepage = $manufacturer::where('id', $gearItem->manufacturer_id)->value('homepage');

        // Get all the item's special features: 
        $gearItem->features = $specialFeatures::where('gear_items_id', $gearItem->id)->get();
        
        // Iterator for the spacial features names:
        $featureNames = SpecialFeature::where('sub_categories_id', $gearItem->sub_categories_id)->pluck('feature_name');
        $featureNames->title = SpecialFeature::where('sub_categories_id', $gearItem->sub_categories_id)->pluck('feat_html');
        
        return view('gearitem.show', compact(['gearCategory', 'manufacturer', 'gearItem', 'featureNames']));
    }

My view:

   @if($gearItem->url === null)
                <strong>{{$gearItem->name}}</strong> 
                @else
                <strong> <a target="_blank" href="{{$gearItem->url}}">{{$gearItem->name}}</a></strong>
                @endif
                by <strong><a target="_blank" href="{{$manufacturer->homepage}}">{{ $manufacturer->name }}</a></strong>

                <div class="specialFeatures">

                    <div class="row">
                        <div class="col-6">
                            <table class="table">

                                @foreach ($featureNames->title as $title)
                                <tr>
                                    <td>{!! $title !!}</td>
                                </tr>
                                @endforeach

                            </table>
                        </div>

                        <div class="col-6">
                            <table class="table">

                                @foreach ($featureNames as $featureName)
                                <tr>
                                    <td>{{  $gearItem->features[0][$featureName]}}</td>
                                </tr>
                                @endforeach

                            </table>
                        </div>
                    </div>
                </div>
Jun
12
3 months ago
Activity icon

Awarded Best Reply on Laravel Ignores Validation Errors And Makes Form Disappear

Once again, no one here to help so I had to go and find the solution myself... The solution is creating an Ajax form validation. I've written it in vanilla JavaScript for the sake of any other poor n00b like me that might search for the same thing:

document.addEventListener('DOMContentLoaded', function (event) {

(function () {
document.querySelector('#item_form').addEventListener('submit', function (e) {
e.preventDefault()
axios.post(this.action, {
'gear_categories_id': document.querySelector('#gear_categories_id').value,
'sub_categories_id': document.querySelector('#sub_categories_id').value,
'name': document.querySelector('#name').value,
'manufacturer_id': document.querySelector('#manufacturer_id').value
})
.then((response) => {
console.log(response);
window.location.href = '/gearitem/create'
})
.catch((error) => {
const errors = error.response.data.errors
const firstItem = Object.keys(errors)[0]
const firstItemDOM = document.getElementById(firstItem)
const firstErrorMessage = errors[firstItem][0]

// Scroll to the error message:
 firstItemDOM.scrollIntoView({
behavior: 'smooth'
})

// Remove all error messages:
const errorMessages = document.querySelectorAll('.text-danger')
errorMessages.forEach((element) => element.textContent = '')

// Show the error message:
 firstItemDOM.insertAdjacentHTML('afterend',
`<small class="text-danger">${firstErrorMessage}<small>`)

// Remove all form controls with highlighted error text box: 
const formControls = document.querySelectorAll('.form-control')
formControls.forEach((element) => element.classList.remove('border',
'border-danger'))

// highlight the form control with the error:
firstItemDOM.classList.add('border', 'border-danger')

});
});
})();

}); // Dom content load

Well done me. Yay!

Activity icon

Replied to Laravel Ignores Validation Errors And Makes Form Disappear

Once again, no one here to help so I had to go and find the solution myself... The solution is creating an Ajax form validation. I've written it in vanilla JavaScript for the sake of any other poor n00b like me that might search for the same thing:

document.addEventListener('DOMContentLoaded', function (event) {

(function () {
document.querySelector('#item_form').addEventListener('submit', function (e) {
e.preventDefault()
axios.post(this.action, {
'gear_categories_id': document.querySelector('#gear_categories_id').value,
'sub_categories_id': document.querySelector('#sub_categories_id').value,
'name': document.querySelector('#name').value,
'manufacturer_id': document.querySelector('#manufacturer_id').value
})
.then((response) => {
console.log(response);
window.location.href = '/gearitem/create'
})
.catch((error) => {
const errors = error.response.data.errors
const firstItem = Object.keys(errors)[0]
const firstItemDOM = document.getElementById(firstItem)
const firstErrorMessage = errors[firstItem][0]

// Scroll to the error message:
 firstItemDOM.scrollIntoView({
behavior: 'smooth'
})

// Remove all error messages:
const errorMessages = document.querySelectorAll('.text-danger')
errorMessages.forEach((element) => element.textContent = '')

// Show the error message:
 firstItemDOM.insertAdjacentHTML('afterend',
`<small class="text-danger">${firstErrorMessage}<small>`)

// Remove all form controls with highlighted error text box: 
const formControls = document.querySelectorAll('.form-control')
formControls.forEach((element) => element.classList.remove('border',
'border-danger'))

// highlight the form control with the error:
firstItemDOM.classList.add('border', 'border-danger')

});
});
})();

}); // Dom content load

Well done me. Yay!

Jun
11
3 months ago
Activity icon

Awarded Best Reply on Trying To Create A Dynamic @include Request - Please Help...

For whoever is interested:

Managed to solve it myself finally with the following JS function:

function itemFeatures(divId, subCatId){
document.getElementById(divId).setAttribute("name", subCatId.value);
axios.get('/item-type/' + subCatId.value)
.then(function (response){
let itemName = response.data;
document.getElementById(divId).innerHTML = itemName;
})
.catch(function (error) {
document.getElementById(divId).innerHTML = "No special features for this item";
console.log(error);
})
}

Then for the function in my controller:

public function getItemType($subCatId){ // (returns a view partial according to the sub-cat selected)
$subCatName = str_replace(' ', '-', strtolower(SubCategory::where('id', $subCatId)->value('name')));
return view('gearitem.itemtype.'.$subCatName.'');
}

So basically I "fed" the .innerHTML method with the content of the blade partial that I aim at. the blade partial address changes according to which choice is made by the user.

Jun
09
3 months ago
Activity icon

Started a new Conversation Laravel Ignores Validation Errors And Makes Form Disappear

So, I have created a dynamic form to enter hiking gear items. At the beginning, all the user sees is a "select gear category" dropdown, and according to the gear category selected (for ex: "Shelters") - another dropdown appears for the user to select the type of gear item (for ex: "tent"). Then as soon as the choice is made, the user gets a generic form for general features (like price, weight, brand, name etc) + a view partial that fetches (with axios) special features according to the type (if it's a tent - it'll get the N° of persons, if it's a backpack - the carry capacity, etc)

example of the form structure with the special features div:

<div class="form-group col-md-6">

<select class="custom-select" name="manufacturer_id">
<option value="" selected>Brand</option>
@forelse ($manufacturers as $manufacturer)
<option value="{{ $manufacturer->id }}"
{{ (old("manufacturer_id") == $manufacturer->id ? "selected" : "") }}>
{{ $manufacturer->name }}</option>
@empty
<option>No manufacturers</option>
@endforelse
</select>
 
@error('manufacturer_id')
<small class="text-danger">{{ $message }}</small>
@enderror
</div>
</div>

<div class="container pt-3" v-show="formDisplay" id="itemType" style="background: #e1f7d5">
<!-- This div displays the partial view related to the sub category chosen -->
</div>

so far so good. I managed to distribute the data into the appropriate tables via my controller. Here is my 'store' method:


    public function store(){

        $data = request()->validate([
            
            'gear_categories_id' => 'required',
            'sub_categories_id' => 'required', 
            'name' => 'required', 
            'manufacturer_id' => 'required', 

        ]);

        
        $gearItem = auth()->user()->gearItem()->create($data);

        $featureModel = SpecialFeature::where('sub_categories_id', 
	$gearItem->sub_categories_id)->value('model_name');

        $specialFeatures =  'App\'.$featureModel;
        $featuresData['gear_items_id'] = $gearItem->id;
        $featureNames = SpecialFeature::where('sub_categories_id', 
$gearItem->sub_categories_id)->get();
     
        foreach ($featureNames as $featureName) {
            if (SpecialFeature::where('required', 0)->get()){
                $featuresData[$featureName->feature_name] = request($featureName->feature_name); 
            } else {
                $featuresData = request()->validate([
                    $featureName->feature_name => 'required'
                ]);
            }
        }

        $specialFeatures::create($featuresData);
        
        return redirect('/gearitem/'.$gearItem->id);

    }

The problem is, when I deliberately DO NOT fill in required fields in the form - instead of keeping the display of the form stable with the message errors - the whole thing disappears, leaving only the the top drop down (gear categories) and you have to re-select the category again - to see the errors. And another thing - if there are required fields in the fetched "special features" div - the errors won't even show when the user does not fill in the fields. the @error is completely ignored! What am I doing wrong here?

Jun
03
3 months ago
Activity icon

Replied to Trying To Create A Dynamic @include Request - Please Help...

For whoever is interested:

Managed to solve it myself finally with the following JS function:

function itemFeatures(divId, subCatId){
document.getElementById(divId).setAttribute("name", subCatId.value);
axios.get('/item-type/' + subCatId.value)
.then(function (response){
let itemName = response.data;
document.getElementById(divId).innerHTML = itemName;
})
.catch(function (error) {
document.getElementById(divId).innerHTML = "No special features for this item";
console.log(error);
})
}

Then for the function in my controller:

public function getItemType($subCatId){ // (returns a view partial according to the sub-cat selected)
$subCatName = str_replace(' ', '-', strtolower(SubCategory::where('id', $subCatId)->value('name')));
return view('gearitem.itemtype.'.$subCatName.'');
}

So basically I "fed" the .innerHTML method with the content of the blade partial that I aim at. the blade partial address changes according to which choice is made by the user.

Jun
02
3 months ago
Activity icon

Started a new Conversation Trying To Create A Dynamic @include Request - Please Help...

I'm trying to pass a JS variable via .innerHTML method so that the blade command @include will be posted inside a div but Laravel won't have anything to do with it.

Here is my JS function:

<script type="application/javascript" >
function itemFeatures(divId, subCatId){
    axios.get('/item-type/' + subCatId.value)
   .then(function (response){
   let itemName = response.data[0].name;
document.getElementById(divId).innerHTML = `@include('gearitem.itemtype.${itemName}')`    
    })    
}
</script>

I have a blade who's address is gearitem.itemtype.tent.blade.php for example and the 'response.data[0].name' yields 'tent' so logically i'd expect the variable itemName to place 'tent' at the appropriate place in the @include string but instead I'm getting the following error from Laravel:

gearitem.itemtype.${itemName} was not found. Are you sure the view exists and is a .blade.php file?

I have tested the blade by hard coding it so = @include('gearitem.itemtype.tent') inside the div without a problem (it appears correctly) I also tried an .innerHTML =

${itemName}

and the string 'tent' appears in the div perfectly. It seems like Laravel is meddling with my syntax inside the JS before it is even rendered for some reason... What am i missing here?

May
19
4 months ago
Activity icon

Commented on The Skeleton

  1. Create the file in resources/js (called 'file.js' in this example)
  2. Go to webpack.mix.js file (at the bottom)
  3. Add there: mix.js('resources/js/file.js', 'public/js');
  4. Run in terminal : npm run production
  5. Run in terminal: npm run watch
May
15
4 months ago
Activity icon

Replied to Creating A Dropdown That Dynamically Creates Another Dropdown - Please Help....

The first dropdown fetches data from a table called gearCategories (very simple table with a primary key and just the name of the categories) and the idea is that once the user has chosen a category from the first dropdown a second dropdown will appear dynamically under the first one with the sub categories related to the category chosen on the first dropdown. (the subCategory table has a foreign key that features the primary key of the gearCategories table). Later i'd like the form that will appear dynamically under the second dropdown to feature only fields related to the sub-category of objects. I believe there is no way around AJAX query to do it but the question is - could it be done elegantly with Vue or some other method? Or id there already a Laravel function that i'm not aware of to solve exactly that kind of problem?

May
13
4 months ago
Activity icon

Started a new Conversation Creating A Dropdown That Dynamically Creates Another Dropdown - Please Help....

Hi, I'm fairly new to Laravel (and I love it!) I'm trying to do something a bit complicated: Creating a drop-down menu that upon selection of an option -will display a second drop-down menu that will give further options dynamically based on the previous selection.

My controller looks like this:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Manufacturer;
use App\GearCategory;
use App\SubCategory;
use App\GearItem;

class GearItemController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth'); 
    }

    public function create(Manufacturer $manufacturers, GearItem $gearItem, GearCategory $gearCategory, SubCategory $subCategory)
    {
        // dd($gearCategory->all());
        $catNum = 6; // <-- needs to be equal to the dispaly div name. Hard coded as 6 for test purposes. 
        $gearCategory = $gearCategory->all();
        $subCategory = $subCategory::where('gear_categories_id', $catNum)->get();
        $manufacturers = $manufacturers->all();
        

        return view('gearitem.create', compact('gearCategory'), compact('subCategory'), compact('manufacturers'),  compact('gearItem'));
    }
}

My blade looks like this:

  <div class="card-header">
                    <h3>Add a new gear Item</h3>
                    
                </div>
                <div class="container">
                    <select name="gear_categories_id" id="gear_categories_id" class="custom-select mb-3 mt-3"
                        onchange="selector('display_div', this)">
                        <option value="" selected>Choose category</option>
                        @foreach ($gearCategory as $category)
                        <option id="cat_selector" value="{{ $category->id  }}"
                            {{ (old("gear_categories_id") == $category->id ? "selected" : "") }}>{{ $category->name }}
                        </option>
                        
                        @endforeach
                    </select>
                </div>


                <script>
                    "use strict"
                    function selector(divId, element) {

                        console.log(element.value);

                        document.getElementById(divId).setAttribute("name", element.value)
                   
                    }
                </script>

               
                    
                    <div class="display_div container" id="display_div" name="">
                    
                    <select name="sub_categories_id" id="sub_categories_id" class="custom-select mb-3 mt-3">
                    <option value="" selected>Choose item's type</option>
                    @foreach ($subCategory as $scategory)
                    <option id="cat_selector" value="{{ $scategory->id }}"
                        {{ (old("sub_categories_id") == $scategory->id ? "selected" : "") }}>{{ $scategory->name }}
                    </option>
                    @endforeach
                </select>

                </div>

(Sorry for using vanilla JS i haven't gotten into Vue yet...) I'm trying to pass the name of the "display_div" onto the $catNum variable in the controller (set to "6" just to test if it works but should be set to whatever the user is choosing on the first dropdown) The values of the 'gear_categories_id' appear as a foreign key in the SubCategory model and if i'll manage to feed these values to the second dropdown it would work. I've been struggling for hours with it and I can't figure it out... Please help and sorry for being such a n00b.