Issue with passing value to view in Laravel [duplicate] - php

This question already has an answer here:
Issue with Laravel orderby
(1 answer)
Closed 5 years ago.
)
I am trying to order my products by price and I keep getting the same message error : Undefined index: title (View: C:\xampp\htdocs\eshop\resources\views\content\item.blade.php)
From what I understood my "item" wasn't added correctly to $data but I can't figure it out what is the correct way.
My Route :
Route::get('shop/{category_url}/sorting-{sort?}', 'ShopController#products');
My view in content.products:
#if($products)
<br><br>
High to low |
Low to high
My item.blade.php:
#extends ('master')
#section('content')
<div class="row">
<div class="col-md-12 text-center">
#if('item')
<h1>{{ $item['title']}}</h1>
<p><img width="500" src="{{ asset ('images/' . $item['image'])}}" </p>
<p>{!! $item['article'] !!}</p>
<p><b>Price on site:</b>{{ $item['price']}}$</p>
<p>
#if(Cart::get($item['id']))
<input disabled="disabled" type="button" value="In Cart!" class="btn btn-success">
#else
<input data-id="{{ $item['id']}}" type="button" value="+ Add to cart" class="btn btn-success add-to-cart">
#endif
Checkout
</p>
#else
<p class="text-center" style="font-size: 18px">No product details ...</p>
#endif
</p>
#endsection
My Controller:
public function products(Request $request, $category_url, $sort= 'ASC'){
Product::getProducts($category_url, self:: $data);
$catsort = Categorie::where('url', '=', $category_url)->first();
$products = Product::where('categorie_id', $catsort->id)->orderBy('price', $sort)->get();
return view('content.products', self::$data ,['products' => $products, 'sort' => $sort]);
}
public function item($category_url, $product_url){
Product::getItem($product_url, self::$data);
return view('content.item', self::$data);
}
My Model:
static public function getProducts($category_url, &$data){
$data['products']=$data['category']=[];
if ($category=Categorie::where('url','=', $category_url)->first()){
$category= $category->toArray();
$data['category']=$category;
$data['title']=$data['title']. ' | ' . $category['title'];
if ($products=Categorie::find( $category['id'])->products){
$data['products']= $products->toArray();
}
}
}
static public function getItem($product_url, &$data) {
$data['item'] = [];
if ($product = Product::where('url', '=', $product_url)->first()) {
$product = $product->toArray();
$data['item'] = $product;
$data['title'] .= '|' . $product['title'];
}
}

You are passing $data from the controller to the view with view('content.products', self::$data, ...).
In your model, you add the product data to $data['item'] which will be accessible in the view template through the variable $item, and then you add the product title to $data['title'], which then will be accessible in the view template through the variable $title.
This should be working, as long as your product data is being loaded correctly, which doesn't seem to be the case.
Try to replace in the view template {{ $item['title']}} with {{ $title }}. If this result in an empty title, then it means that the product data is not being loaded correctly. To make sure you can try to dump the data in the view with {{ dd($item) }}.
EDIT
There is a problem with your routes.php and the route you posted here doesn't seem to be the problem, but the other one probably is.
If you defined it as Route::get('shop/{category_url}/{product_url}', ...), both routes will match the URL /category/sorting-asc.
You could add something to the URL to say it is a product URL
Route::get('shop/{category_url}/product/{product_url}', ...);

Related

Trying to get property 'title' of non-object (View: C:\xampp\htdocs\lsapp\resources\views\posts\show.blade.php)

I am getting above error while requesting to next page but I want posts title is as page title as well
#extends('layouts.app')
#section('pageTitle', $post->title)
#section('content')
Go Back
<br> <br>
<h1>{{ $post->title }}</h1>
<div class="">
<p>{!! $post->body !!}</p>
</div>
<hr>
<small>Written on: {{ $post->created_at }}</small>
<hr>
Edit
#endsection
public function show($id)
{
$post = Post::find($id);
return view('posts.show')->with('post', $post);
}
Post::find(...) can return null. You will have to make sure that you are actually receiving a model instance, the record exists, before trying to use it. You can use something like Post::findOrFail(...) to allow this to fail when it doesn't find a record. This would allow you to continue in the code knowing $post will be a valid instance.
Because the return type should be an array,
you can use this
public function show($id)
{
$post[] = Post::find($id);
return view('posts.show')->with('post', $post);
}

LARAVEL 7 - How to pass variables to views

I have two tables, Companies and Projects. A company hasMany projects and a project belongsTo a company.
Company.php model
protected $fillable = [
'id', 'name', 'description'
];
public function projects()
{
return $this->hasMany('App/Project');
}
Project.php model
protected $fillable = [
'name', 'description', 'company_id', 'days'
];
public function company()
{
return $this->belongsTo('App/Company');
}
From my index.blade.php, I list the companies only and I have made them clickable so that when a user clicks on a company listed, they are taken to show.blade.php where the name of the company and the projects that belong to that company are displayed like so.
<div class="jumbotron">
<h1>{{ $company->name }}</h1>
<p class="lead">{{ $company->description }}</p>
</div>
<div class="row">
#foreach($company->projects as $project)
<div class="col-lg-4">
<h2>{{ $project->name }}</h2>
<p class="text-danger">{{ $project->description }}</p>
<p><a class="btn btn-primary" href="/projects/{{ $project->id }}" role="button">View Projects »</a></p>
</div>
#endforeach
</div>
Now am getting an undefined variable $project error. So I decided to declare variable in my show() function of the CompaniesController.php like so
public function show(Company $company)
{
$company = Company::find($company->id);
$projects = Company::find(1)->projects;
return view('companies.show', ['company' => $company, 'projects' => $projects]);
}
And access variable in show.blade.php like so
<div class="jumbotron">
<h1>{{ $company->name }}</h1>
<p class="lead">{{ $company->description }}</p>
</div>
<div class="row">
#foreach($projects as $project)
<div class="col-lg-4">
<h2>{{ $project->name }}</h2>
<p class="text-danger">{{ $project->description }}</p>
<p><a class="btn btn-primary" href="/projects/{{ $project->id }}" role="button">View Projects »</a></p>
</div>
#endforeach
</div>
Now am getting a Class 'App/Project' not found error when I access show.blade.php. I am having a challenge passing company projects to the view. Any help will be appreciated. Here are my routes;
Route::get('/', function () {
return view('welcome');
});
Auth::routes();
Route::get('/home', 'HomeController#index')->name('home');
Route::resource('companies', 'CompaniesController');
Route::resource('projects', 'ProjectsController');
I would be hilarious if I am right....
In your models where defining relations replace App/Project with App\Project. Do the same for Company.... Replace "/" with "\".
You have to namespace Project class properly
Make sure file name is Project.php
Make sure inside Project.php namespace declaration is correct: namespace App;
Make sure class name inside Project.php is 'Project' : class Project extends Model { ...
Make sure you have imported it in controller. use App\Project
After all that done you will not get error:
Class 'App/Project' not found
You have correctly done passing variable in view but have a look here for another examples and methods passing about it:
https://laravel.com/docs/7.x/views
Hope this helps you
You're already using model binding. In your show method, you do not need to find. just return what you need
public function show(Company $company)
{
return view('companies.show', ['company' => $company];
}
In your view, you can then do:
#foreach($company->projects as $project)
...
#endforeach

invalid argument supplied for foreach() laravel relationship

I'm trying to show a book's comments by ISBN (book table's PK) and I get the following error:
Invalid argument supplied for foreach
I'm using Laravel relationship and a foreach to get the records from the following query, in a Helper class:
function getCommentsByISBN($data)
{
foreach (Book::where("ISBN", $data)->get() as $comments) {
return $comments->comments;
}
}
And here's my Book model, comment relationship:
public function comments()
{
return $this->hasMany(Comment::class, "ISBN", "ISBN");
}
And here's the view where I show the comments:
#foreach(getCommentsByISBN(session("isbn")) as $comment)
<div class="form-group">
<h3>
{{ getUserWhoPostedComment($comment->email) }}
</h3>
<p>
{{ $comment->commentary }}
</p>
#if(Session::has("username") && isAdmin(session("username")))
<button type="button" onclick="openModal('{{$comment->commentary}}')"
name="warningButton" class="btn btn-warning" data-toggle="modal"
data-target="#modalWarning">
<i class="fas fa-exclamation-circle"></i>
</button>
#endif
<hr>
<span>
Hace: {{ getTimeWherePostedComment($comment->publicated_at) }}
</span>
</div>
#endforeach
Thanks in advance!
I think you helper returns void because no book was found with that ISBN.
I think it should look like this btw
function getCommentsByISBN($isbn)
{
if ($book = Book::where("ISBN", $isbn)->first()) {
return $book->comments;
}
}
and in your blade your top should look like
#php
$comments = getCommentsByISBN(session("isbn")) ?: [];
#endphp
#foreach($comments as $comment)
<div class="form-group">
/// Rest of the code

Why my Laravel blade view returns blank page?

this is my route
Route::get('/product/single/{slug}', 'Front\ShopController#shopSingle')
->name('front.shop_single.ru');
and my view where I use that route to load single product
<div class="col-md-4">
<div class="product">
<figure class="product-image">
<img src="/{{ $img[0] }}" alt="bitcoin, bitcoindoc, bitcoin exchange, exchange, libradoc, libradoc exchange">
<i class="licon-cart"></i>Подробно
</figure>
<div class="product-description">
{{ $product->title }}
<h5 class="product-name">{{ $product->price }}</h5>
</div>
</div>
</div>
finally controller to redirect my desired page
public function shopSingle($slug){
$product = Shop::whereSlug($slug)->whereLang(App::getLocale())->first();
$data['product'] = $product;
return view('front.'.'App::getLocale()'.'.shop_single', $data);
}
unfortunately, whenever I try to go to single product it returns blank page but in the view page resource(I use Chrome) everything is okay. Please help, thanks in advance.
You need to send the data as well to your view
public function shopSingle($slug){
$product = Shop::whereSlug($slug)->whereLang(App::getLocale())->first();
// it could work like this
$data['product'] = $product;
return view('front.'.App::getLocale().'.shop_single', $data);
// or
return view('front.'.App::getLocale().'.shop_single', compact($product));
// or
return view('front.'.App::getLocale().'.shop_single')->withProduct($product);
}
Try to change the last line from your controller to
return view('front.'.App::getLocale().'.shop_single', ['product' => $product]);

Laravel 5.5 - Trying to get property of non-object

I am trying to update my data, but i keep getting this error message:
"Trying to get property of non-object (View: C:\xampp\htdocs\blog\resources\views\update.blade.php)".
This is my update.blade.php file
#extends ('layout')
#section ('title')
Update page
#stop
#section ('content')
<div class="row">
<div class="col-lg-12">
<form action="/todo/save" method="post">
{{ csrf_field() }}
<input type="text" class="form-control input-lg" name="todo"
value="{{ $todo->todo }}" placeholder="Type in to create a new todo">
</form>
</div>
</div>
<hr>
#foreach ($todo as $todo)
{{ $todo->todo }} <a href="{{ route('todo.update', ['id' =>$todo->id])
}}" class="btn btn-info btn-sm">Update</a> <a href="{{ route('todo.delete',
['id' =>$todo->id]) }}"class="btn btn-danger">Delete</a>
<hr>
#endforeach
#stop
my controller:
public function update($id){
//dd($id);
$todo = Todo::find($id);
return view('update')->with('todo', $todo);
}
and finally my update route:
Route::get('/todo/update/{id}', 'TodosController#update')-
>name('todo.update');
This is just some basic stuff, but im stuck in here for couple of hours now, and any help is highly appreciated!
Use findOrFail method on your controller to throw an Exception if $todo is empty
public function update($id){
$todo = Todo::findOrFail($id);
return view('update', compact('todo'));
}
The problem is also on your update.blade.php file. foreach $todo as todo, $todo has collection of eloquent model or eloquent model ? I think it's a eloquent model. So a loop doesnt have any sense.
That error would happen if todo were FALSE or some other non-object.
You can inspect it with a var_dump($todo);die(); in the controller.
find() will return either null or the model that is found. Assuming that the model is found, you're doing a for each on that model (foreach ($todo...)), which will iterate over the model's public properties. This is obviously not what you intend to do.
It looks to me like you're trying to loop over a list of your todos and print out edit/delete links. If this is the case, you need to get the list of your todos in your controller, pass it into your view, and fix your foreach statement.
Controller:
$todos = Todo::get();
// pass to view
View:
foreach ($todos as $todo)

Categories