Laravel Relationship not working with belongsTo - laravel

Hello Guys, I am just passing my query to notification blade, but its gave error. I dont know what i did wrong with bellow code. If you guys fix this issue i will be very glad. Thanks in advance
Notification seen model
<?php
namespace App\Models\Backend;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class notificationseen extends Model
{
use HasFactory;
protected $table = 'notificationseens';
public function Notification()
{
return $this->belongsTo(Notification::class, 'notificationID');
}
}
Notification Model
<?php
namespace App\Models\Backend;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Notification extends Model
{
use HasFactory;
protected $table = 'notifications';
public function notificationseen()
{
return $this->belongsTo(notificationseen::class, 'notificationID');
}
}
View Blade
#foreach( $notification as $notify )
#if($notify->Notification->seen == 0)
<!-- Single Notification --><a href="{{ route('singlenotify', $notify->id) }}" id="notifysee" data-id="{{ $notify->id }}">
<div class="alert unread custom-alert-3 alert-primary" role="alert"><i class="bi bi-bell mt-0"></i>
<div class="alert-text w-75">
<h6 class="text-truncate">{{ $notify->name }}</h6><span class="text-truncate">{{ $notify->description }}</span>
</div>
</div></a>
#else
<!-- Single Notification --><a href="{{ route('singlenotify', $notify->id) }}">
<div class="alert custom-alert-3 alert-primary" role="alert"><i class="bi bi-bell mt-0"></i>
<div class="alert-text w-75">
<h6 class="text-truncate">{{ $notify->name }}</h6><span class="text-truncate">{{ $notify->description }}</span>
</div>
</div></a>
#endif
#endforeach
Table structure
$table->increments('id');
$table->integer('userid');
$table->integer('notificationID');
$table->integer('seen')->default('0')->comment("0 for unseen 1 for seen");
$table->timestamps();
Can you please help me out. I cant see any issue but its me error "Attempt to read property "seen" on null"

Ok, some things:
I would use belongsTo in the notificationseen class unless one notificationseen could have more than one Notifications to belong to ;)
Do a Notification have more than one notificationseen references? I do not think so, so in your Notification change the reference to hasOne.
In your blade, use #if($notify->notificationseen->seen == 0) or you call better "Notification::with('notificationseen')->get()" in your controller and then pass it to your view.

You can try to add an isset to avoid the error :
#if(isset($notify->Notification->seen) && $notify->Notification->seen == 0)
(...)
#else
(...)
#endif
EDIT : in your code, you defined 2 belongsTo methods, but according to the official Laravel documentation, you must define a hasOne method and the inverse of it, the belongsTo method.

Related

Trying to get property 'image' of non-object in Laravel

I am working on a laravel project. In this project, when i try to view and edit the profile page. I am getting this error.
ErrorException
Trying to get property 'image' of non-object (View: C:\xampp\htdocs\HomeServices\resources\views\livewire\sprovider\sprovider-profile-component.blade.php)
http://127.0.0.1:8000/sprovider/profile
SproviderProfileComponent.php :-
<?php
namespace App\Http\Livewire\Sprovider;
use App\Models\ServiceProvider;
use Illuminate\Support\Facades\Auth;
use Livewire\Component;
class SproviderProfileComponent extends Component
{
public function render()
{
$sprovider = ServiceProvider::where('user_id',Auth::user()->id)->first();
return view('livewire.sprovider.sprovider-profile-component',['sprovider'=>$sprovider])->layout('layouts.base');
}
}
Models/ServiceProvider.php :-
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class ServiceProvider extends Model
{
use HasFactory;
protected $fillable = ['user_id'];
public function category()
{
return $this->belongsTo(ServiceCategory::class,'service_category_id');
}
}
sprovider-profile-component.blade.php
<div class="panel-body">
<div class="row">
<div class="col-md-4">
#if($sprovider->image)
<img src="{{asset('images/sproviders')}}/{{$sprovider->image}}" width="100%" />
#else
<img src="{{asset('images/sproviders/default.jpg')}}" width="100%" />
#endif
</div>
<div class="col-md-8">
<h3>Name: {{Auth::user()->name}}</h3>
<p>{{$sprovider->about}}</p>
<p><b>Email: </b>{{Auth::user()->email}}</p>
<p><b>Phone: </b>{{Auth::user()->phone}}</p>
<p><b>City: </b>{{$sprovider->city}}</p>
<p><b>Service Category: </b>
#if($sprovider->service_category_id)
{{$sprovider->category->name}}
#endif
</p>
<p><b>Service Locations: {{$sprovider->service_locations}}</b></p>
Edit Profile
</div>
</div>
</div>
The only reason this could happen is because $sprovider is null.
When it happens, $sprovider->image will translate to (null)->image, which is indeed Trying to get property 'image' of non-object.
You could do this to prevent $sprovider from being null:
$sprovider = ServiceProvider::where('user_id',Auth::user()->id)->firstOrFail();
By using firstOrFail instead of first, you ensure $sprovider will never be null (like the name suggests, if it doesn't find any provider, it will fail).
You will have another error saying that no provider could be found, this is another issue, probably because you don't have any provider for this user or something like that.
Two possibilities
$sprovider is null and
image key is not available in $sprovider ($sprovider->image) may be you mis-spelled image in database table so for that just use dd($sprovider); or print_r($sprovider); and check image key is available or not.

how to use the where clause in laravel to retrieve different categories of products in the same table

I am currently making an ecommerce site and am new to Laravel, and at the moment I'd like to retrieve data based on different categories from the same table, using a where clause to store the retrieved data in separate variables. The problem here is whenever I run this code it say undefined variable $newproducts. Below is my code. Thanks in advance
My Controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\product;
class ProductsController extends Controller
{
public function index(){
$allproducts=product::all();
$bestsellerproducts=product::where('category','iphone 11')->get();
$newproducts=product::where('category','iphone 12')->get();
return view('test',['products'=>$allproducts],['bestsellerproducts'=>$bestsellerproducts],['newproducts'=>$newproducts]);
}
}
My view Template
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
</head>
<body>
<h2>Best Seller products</h2>
#foreach($bestsellerproducts as $bestsellerproduct)
<label>Name</label>
{{ $bestsellerproduct['name'] }}
<label>Price</label>
{{ $bestsellerproduct['price'] }}
#endforeach<br>
<h2>New products</h2>
#foreach($newproducts as $newproduct)
<label>BaseName</label>
{{ $newproduct['name'] }}
<label>Price</label>
{{ $newproduct['price'] }}
#endforeach<br>
<h2>All products</h2>
#foreach($products as $product)
<label>BaseName</label>
{{ $product['name'] }}
<label>Price</label>
{{ $product['price'] }}
#endforeach<br>
</body>
</html>
You need to pass all view variables in a single array, not multiple arrays:
class ProductsController extends Controller
{
public function index(){
$allproducts=product::all();
$bestsellerproducts=product::where('category','iphone 11')->get();
$newproducts=product::where('category','iphone 12')->get();
return view('test',['products'=>$allproducts, 'bestsellerproducts'=>$bestsellerproducts,'newproducts'=>$newproducts]);
}
}
Alternatively you can use with:
class ProductsController extends Controller
{
public function index(){
$allproducts=product::all();
$bestsellerproducts=product::where('category','iphone 11')->get();
$newproducts=product::where('category','iphone 12')->get();
return view('test')
->with('products',$allproducts)
->with('bestsellerproducts', $bestsellerproducts)
->with('newproducts', $newproducts);
}
}

Get related objects on the view

I have related model
class Myevent extends Model
{
public function photo()
{
return $this->hasMany('App\EventPhoto');
}
}
Ob blade if loop i get items Myevents
#foreach($evetns as $event)
<b>{{$event->name}}</b> <br>
{{$event->place}} <br>
{{$event->description}} <br>
#foreach($event->photo() as $item)
{{$item->id}}
#endforeach
#endforeach
How can I call related objects in a loop on blade?
You seem to be doing correctly, except for one single error $event->photo instead of $event->photo()
#foreach($event->photo as $item)
{{$item->id}}
#endforeach
To clear the confusion regarding brackets https://laraveldaily.com/calling-eloquent-from-blade-6-tips-for-performance/

Laravel Invalid argument supplied for foreach() fetching individual columns

can somebody help with this? I'm trying to pass some data from my Controller page to my index, but I'm getting this error "Invalid argument supplied for foreach()"
Here's my model
class Bookings extends Model
{
//Table name
protected $table = 'bookings';
//Primary key
public $primaryKey = 'book_id';
}
My Controller
use Illuminate\Http\Request;
use App\Bookings;
class PagesController extends Controller
{
public function index(){
$data = Bookings::orderBy('NameENG', 'DetailsENG')->get();
$data = Bookings::all();
$marks = 'NameENG';
$briefs = 'DetailsENG';
return view('pages/index', compact(['data', 'marks', 'briefs']));
}
}
and part of my index
<div class = "container">
#if(count($data) > 0)
#foreach($marks as $mark)
#foreach($briefs as $brief)
<div class="row">
<div class="col-md-4">
<div class="card mb-4 shadow-sm">
<img class="card-img-top" alt="Thumbnail [100%x225]" style="height: 225px; width: 100%; display: block;" src="images/calle_yungay.png">
<div class="card-body">
<h5>{{$mark}}</h5>
<p>{{$brief}}</p>
Can someone help please?
On controller function:
$routes = 'tourNameENG'; // is a string
and on view, you are trying to iterate it:
#foreach($routes as $route)
that's why the error Invalid argument supplied for foreach().
foreach(): works only on arrays and objects, and will issue an error when you try to use it on a variable with a different data type or an uninitialized variable.

Laravel 4 - Method[ ] does not exist

I'm still a novice to Laravel 4 and trying to figure out why I'm getting an error saying that Method [inventoryNotFound] does not exist. It has to do when I am attempting to use the InventoryController#show function.
On my Index page I have a href that I'm trying to send to the show views. The code looks like this:
#foreach($inventory as $item)
<div class="col-md-4 inventory">
<img class="img-responsive" src="{{{$item->image}}}">
<a class="description" href="">{{{$item->title}}}</a>
#foreach($item->size_details as $details)
<p>{{ $details->size }}: {{ $details->price }}</p>
#endforeach
</div>
#endforeach
My show function is:
class InventoryController extends BaseController {
public function index()
{
$inventory = Inventory::all();
return View::make('inventories.index')->with('inventory', $inventory);
}
public function show($id)
{
$inventory = Inventory::find($id);
if(is_null($inventory)){
return $this->inventoryNotFound();
}
return View::make('inventories.show',['inventory' => $inventory]);
}
}
And I have a resource controller as my routes:
Route::resource('inventories', 'InventoryController');
Even when I attempt to run my routes manually, I run into the same problem.
Any ideas as to why?

Resources