Undefined Laravel Product

Encountering the error message Undefined variable: $productsTR, even though I have initialized the products variable in the controller. My setup includes a main blade and a partial blade, where the main blade sends data to the controller before it is returned to the partial blade. How can I address the issue of Undefined variable: $productsTR?

HomeController

  public function viewProduct($id){
    $productsTR = Product::with('ProductsPhoto')->where('id',$id)->get();
    $returnHTML = view('productdetail')->with('productsTR', $productsTR)->render();
    return response()->json(array('success' => true, 'html'=>$returnHTML));
}

Route

Route::get('view-product/{id}', 'HomeController@viewProduct')->name('view.producT');

Partial Blade(productdetail)

@foreach($productsTR as $product)
@foreach($product->ProductsPhoto as $productImage)
           <img src="{{ Storage::url($productImage->filename) }}"  alt="small">
  @endforeach
@endforeach

Main blade

<div class="modal fade" id="view-product" tabindex="-1" role="dialog" aria- 
labelledby="myModalLabel">
<div class="modal-dialog" role="document">
    @include('productdetail')
</div>
</div>


 @foreach($products as $product)
    @if(count($product->ProductsPhoto))
    <a href="javascript:;" id="{{$product->id}}" class="modal-global" >
    <img src="{{Storage::url($product->ProductsPhoto[0]->filename)}}" alt="" >
</a>
        @endif
    @endforeach

Javascript

 <script>
$('.modal-global').click(function(event) {
    event.preventDefault();

    var product_id = $(this).attr("id");
var url = '{{route('view.producT',[":product_id"])}}';
url = url.replace(':product_id', product_id);

    $("#view-product").modal('show');

    $.ajax({
        url: url,
        type: 'GET',
        dataType: 'html',
    })
    .done(function(response) {
        $("#view-product").find('.view-product').html(response);
    });

});
</script>

Main blade (ProductController)

   public function index(Request $request)
  {
    $userId = $request->user()->id;
    $products = product::where('user_id', $userId)->paginate(20);
   return view('product.index',compact('products'));
   }

Main blade Route

Route::get('/user/product', 'ProductController@index');

 

Answer №1

Approach 1

The issue arises from the absence of passing $productsTR in the index function.

public function index(Request $request)
{
    $userId = $request->user()->id;
    $products = product::where('user_id', $userId)->paginate(20);
    
    $productsTR = NULL;//Include this line
    return view('product.index',compact('products', 'productsTR')); //modified here
}

Next, perform a validation at this point

<div class="modal-dialog" role="document">
  @if($productsTR)
    @include('productdetail')
  @else
    //add as required or omit the else part
  @endif
</div>

Approach 2

Alternatively, if rendering solely through script is preferred, follow this method

<div class="modal-dialog" role="document">
   <div class="modal-content">
      <div class="modal-body" id="renderedView">
        
      </div>
   </div>
</div>

$.ajax({
   type:'GET',
   url:url,
   dataType:'JSON,
   success:function(response){
       $("#renderedView").html(response.html);
   }
});

If the rendering is exclusively done via ajax, the 1st approach can be disregarded

Answer №2

Initially, you have integrated the productdetail blade into your main blade when it first loads, but the issue arises because no data is being passed.

<div class="modal-dialog" role="document">
    @include('productdetail')
</div>

You may want to consider adding a condition to verify if productsTr has been initialized or not. Currently, data is only provided when the #view-product element is triggered in your scenario.

Answer №3

An error occurs when transferring data in the blade file. It is important to pass the data as an array, like the example below.

$htmlOutput = view('productdetail',['productsTR'=>$productsTR])->render();

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Fill in a text box with a chosen value from a linked drop-down menu

My database contains two tables: 1 - tbl_category 2 - tbl_shelf_place I am working towards displaying the shelf_code in a textbox based on the selected category_name from a drop-down (book_category) with a value of category_id, instead of using another ...

Unable to Click on Selenium Element

When a link is clicked on a website, the URL remains unchanged but a popup appears on the screen containing elements that can only be accessed after running driver.switchTo().defaultContent(). To access these elements, I have used a javascript executor com ...

PHP and AJAX issue when clicking on something

I'm seeking assistance in making this work more effectively. Currently, the like button only registers a click when I click beside it instead of directly on it. I attempted setting the onclick function within the iframe as well, but that didn't r ...

What is the best way to conceal a lengthy description and create a toggle feature in React JS?

Having an issue with my ReactJS application. It consists of card items with brief descriptions that I want to expand into full details when clicking a button. The goal is to toggle between short and long descriptions, providing users with flexibility in ...

"Ng-repeat function seems to be malfunctioning, although I am able to view

There seems to be an issue with ng-repeat when dealing with an array of objects: dummy.json [ {"name":"alpha", "data":[{"name":"Unit 1", "prereqs":[]}]}, {"name":"beta", "data":[{"name":"Unit 1", "prereqs":[]}]} ] While I am able to fetch the total ...

The table headers in the second table do not match the queryAllSelector

I've encountered an issue with my JavaScript snippet that displays a responsive table. When I use the snippet for a second table with the same class, the formatting gets messed up on mobile devices (try resizing your screen to see). It seems like the ...

Using d3.js to dynamically change the color of svg elements based on their data values

I was searching for a way to dynamically color SVG rectangles based on values from a dataset. If I were to create rectangles for each data entry, how could I adjust the rectangle's color according to the data value? Here is what I currently have: // ...

Converting column to date and time format in MySql

I'm facing an issue where a colleague in my company created a database with MySql, but unfortunately set the date column as varchar. It's been like this for at least 10 years, so we can't create a new database. Now I need to work with the da ...

Unable to retrieve data from Meteor find query

I have a collection created in collections.js portfolioItems = new Mongo.Collection('portfolioitems'); This collection is then subscribed to in subscriptions.js Meteor.subscribe('portfolioitems'); And published in publications.js M ...

What steps can be taken to fix the issue of 'this is not defined' when trying to extend EventEmitter?

The code snippet below is encountering an error: var EventEmitter = require('events'); class Foo extends EventEmitter{ constructor(){ this.name = 'foo'; } print(){ this.name = 'hello'; co ...

numerous data visualizations displayed concurrently

I am looking to generate multiple charts using data from mysql. The number of charts will vary depending on the search criteria. I have managed to create a single chart successfully, and my PHP file is echoing the required JSON format perfectly. Now, I wa ...

Confirming if the value is an array using jQuery

Currently, I have a list of elements with various types associated with them. My goal is to identify specific text within these types and hide only those types that do not contain the desired text, leaving the rest unaffected. The structure looks like thi ...

Change the country name to all lowercase letters

I'm attempting to retrieve the country flag icon of the Open Weather Map API. For example: The JSON response for the country code from the API request is in uppercase. To obtain the correct icon for the country, I need the country code in lowercase. ...

Implementing a Singleton Pattern in ReactJS using Context API for Asynchronous Operations

My current implementation involves using a hook: function useFollowUser() { const isFollowing = useRef(false); return (userId) => { if(isFollowing.current) return; // mutual exclusion isFollowing.current = true; ... updat ...

Issue with Vue.js v-for not rendering additional li tags

I am working with a ul that contains items generated from a loop, followed by additional li elements. <ul> <todo-item v-for="(todo,index) in todos" v-bind:todo="todo" :key="index" /> <li :key='"new_item"'> <input pla ...

Implementing pagination within an Angular 11 Mat-table with grouping feature

Encountering an interesting issue with MatTable pagination and grouping simultaneously. I have two components each with a Mat-table featuring Pagination+Grouping. ComponentOne functions smoothly without any issues. When choosing to display 5 elements pe ...

JavaScript: Modifying the Style of a :lang Selector

Currently, I am working on creating a basic multilingual static website using only HTML5, CSS3, and vanilla JavaScript. The structure of the HTML looks something like this: <html> <head> <title>WEBSITE</title> ...

Using an Angular 1 controller scope method as a callback for a captcha library

I have a customer in China who needs a specific captcha that functions there. You can find the captcha I need to use at this link: Essentially, there are 4 steps to make it work: Add this line to the label of your html: <script src="https://ssl.ca ...

What is the best way to substitute spaces with underscores in JSON data and incorporate hyperlinks for each row in datatables?

I am looking to customize JSON data from the back-end before displaying it using datatables. Firstly, I want to replace the spaces ( ) in the column artist.name with underscore symbols (_). Additionally, I would like to create hyperlinks for each row in th ...

JavaScript inheritance through prototypes and the properties of objects

I am currently exploring the concept of prototyped inheritance in JavaScript for a function. This process is well documented in Wikipedia's javascript article. It functions smoothly when dealing with simple JavaScript types: function Person() { t ...