Laravel - Trying to get property text' of non-object - laravel

This is something I've done a million times before so I'm really confused as to why I'm getting this error.
In my Controller, I fetch some results:
$modOfSubchanIDs = Auth::user()->modOf->pluck('id')->toArray();
$modmails = ModMail::whereIn('subchan_id', $modOfSubchanIDs)
->with('subchan')
->with('creator')
->with('appeal')
->orderBy('created_at', 'desc')
->paginate(10);
then in Blade, I try to output the results of the following relationship:
#foreach ($modmails as $modmail)
<div>
{{$modmail->appeal->text}}
</div>
#endforeach
Modmail Model relationship:
public function appeal()
{
return $this->belongsTo(SubchanBanAppeal::class, 'appeal_id');
}
But I get the following error:
ErrorException Trying to get property 'text' of non-object
Strange. So I try just
<div>
{{$modmail->appeal}}
</div>
which returns the following in Blade:
{"id":1,"subchan_id":8,"subchan_ban_id":1,"text":"test","denied":0,"created_by":5003,"created_at":"2021-03-26T00:07:58.000000Z","updated_at":"2021-03-26T00:07:58.000000Z"}
So now I'm really confused. Why is it returning that properly but not when I try a specific column? I also tried {{$modmail->appeal['text']}} but this returns
Trying to access array offset on value of type null
It feels like I'm missing something really basic here...

Did you do the {{ $modmail->appeal }} debug inside the loop? It is likely that most of the $modmails have an appeal, but one or two do not. If it's not the first one that is missing, your test would look right.
The optional() helper method can help in this scenario.
#foreach ($modmails as $modmail)
<div>
{{ optional($modmail->appeal)->text }}
</div>
#endforeach
https://laravel.com/docs/master/helpers#method-optional

Related

Missing required parameter on form action

First of all, I would like to say that my English is not so good and is my first time posting here, so excuse me if I did something wrong! Well, I am starting practicing with Laravel and I am trying to create a URL for users can like posts. my URL and controller is right now this Route::post('/post/{post}/like', [LikeController::class, 'postLike'])->name('post.like'); where post is the posts id that i am trying to pass through my form action attribute. Here is my form:
#props(['id'])
<div {{ $attributes->merge(['class' => 'card-footer d-flex justify-content-around']) }}>
<form action= "{{ route('post.like' , $id) }}" method="post" >
#csrf
<button>submit</button>
</form>
</div>
If you wonder if the id is not actually passed into the component, I checked {{ dd($id) }} and it printed it.
My controller is this which it doesn't actually do anything right now. I am just trying to pass the id:
class LikeController extends Controller
{
public function postLike(Post $post) {
dd($post);
}
}
After all this i am getting the error:
Missing required parameter for [Route: post.like] [URI: post/{id}/like] [Missing parameter: id]. (View: blog\resources\views\components\post\interaction.blade.php)
I am having two days to find the problem and I am still trying this moment I am sending this... I can't found where is the mistake! If you could help me would be much appreciated! Ty in advance
You need to pass the ID as an associative array in your route().
{{ route('post.like', ['id' => $id]) }}
If the named route defines parameters, you may pass the parameters as the second argument to the route function. The given parameters will automatically be inserted into the generated URL in their correct positions and you should name 'post' instead of 'id':
Route::post('/post/{post}/like', [LikeController::class, 'postLike'])->name('post.like');
And you can call this route anywhere
route('post.like', [$postId])
If that still doesn't work for you. Then it might be issue of Route Cache Run:
php artisan route:clear
Use same name parameter
When you use "id" keyword as a parameter in web.php then also same name pass in function argument in the controller
Route::post('/post/{id}/like', [LikeController::class, 'postLike'])->name('post.like');
Controller
class LikeController extends Controller
{
public function postLike(Post $id) {
dd($id);
}
}
Sorry for my bad English.
I have no idea this could be the problem but after many changes i cast the id of the post into an integer and it actually worked <form action= "{{ route('post.like' , (int)$id) }}" method="post" > . I don't know why i should cast the id into an integer because its already an integer by default and i checked that with {{ dd(getType($id)) }} and printed "integer"! I am really confused but it works! But i am not happy because i have no idea why i should cast an integer into an integer to make it work! Doesn't make any sense! If anyone has an answer to this would be great!

Undefined variable on Laravel

I´m a beginner starting with Laravel. I´m trying to show a question made on this website.
Here is the Controller page:
public function show($id)
{
//Use the model to get 1 record from the database
$question = $Question::findOrFail($id);
//show the view and pass the record to the view
return view('questions.show')->with('question', $question);
}
I have included at the top of the file:
use App\Question;
Here is my blade page:
#section('content')
<div class="container">
<h1> {{ $question->title }} </h1>
<p class="lead">
{{ $question->description }}
</p>
<hr />
</div>
#endsection
In the model I have not defined anything since I don´t need to specify any special rule. And finally here is the Route:
Route::resource('questions', 'QuestionController');
I got the error "ErrorException Undefined Variable: Question" and supposedly the error is on:
$question = $Question::findOrFail($id);
I´m looking forward to your observations.
Kind Regards.
You just need to change the controller section
public function show($id)
{
//Use the model to get 1 record from the database
$question = Question::findOrFail($id); // here is the error
//show the view and pass the record to the view
return view('questions.show')->with('question', $question);
}
Explanation:- You are going to use a variable $Question that is not defined. This is the basic PHP error, not the laravel issue.
However, You are using the "App\Question" model class not a sperate variable.

Laravel Livewire key() expects parameter 1 to be array, integer given | nested components | loading a component inside a loop

I've been working with Laravel livewire for a while now, I've a nested components, which is product list for my site and inside that list I've another component for adding product to wishlist. As per documentation stated here , it says
"Similar to VueJs, if you render a component inside a loop, Livewire has no way of keeping track of which one is which. To remedy this, livewire offers a special "key" syntax:"
Like this:
<div>
#foreach ($users as $user)
#livewire('user-profile', $user, key($user->id))
#endforeach
</div>
Here is my code snippets from my project.
<div>
#foreach($products as $product)
<div class="product-box white-bg mb-8" data-dusk="product">
{{-- here im passing product id as param in key(), 'productList' is a static value for a variable of mount(). --}}
#livewire('desktop.wish-list-add', $product, key($product->id), 'productList')
<div class="product-content d-flex justify-content-between align-items-center p-5">
...............
#endforeach
{{ $products->links() }}
</div>
The issue is when I try to pass $product->id as param for key(), it gives error
key() expects parameter 1 to be array, integer given
But the doc clearly shows that we have to pass id as param. Has anyone faced this issue so far?
#livewire('photos.photo-wire', ['photo' => $photo], key($photo->id))
instead of
#livewire('photos.photo-wire', ['photo' => $photo, key($photo->id)])
because that will generate the error:
key() expects parameter 1 to be array, integer given
okay, I found the solution ( however it doesn't make sense to me , but it works :/ )
You have to pass other parameters for mount() like this:
#livewire('desktop.wish-list-add', 'productList', $product->id, key($product->id))
Instead of this:
#livewire('desktop.wish-list-add', $product, key($product->id), 'productList')

Laravel Blade Helpers not pulling in columns with spaces

I have a table with many columns and some of those columns have spaces in their names (i.e. 'Provider First Name'). I know the syntax to use these in Blade helpers and am using this in other parts of my app: {{$provider->{'Provider First Name'} }}. This works fine in other parts.
I have the following in my ProviderController:
public function show($id)
{
$provider = NPIData::where('NPI', $id)->first();
$providers = NPIData::all();
return view ('profiles.provider', compact('provider', 'providers'));
}
I have brought in the NPIData Model to the controller.
I have the following in my provide.blade.php file:
#extends('layouts.profiles')
#section('content')
<div>
{{ $provider->NPI }}
{{$provider->{'Provider First Name'} }}
</div>
#endsection
Oddly, the NPI will pull in, but the 'Provider First Name' does not. I have tried many other columns with spaces and none of them work. I even copied and pasted from other parts of my app where the syntax to pull these in works and it does not work here.
Instead of:
{{$provider->{'Provider First Name'} }}
Try this:
#php
$providerFirstName = $provider->{'Provider First Name'};
#endphp
{{ $providerFirstName }}
UPDATE
If not you can always go with array access:
{{ $provider['Provider First Name'] }}

Laravel ErrorException & Undefined variable even though the variable is defined and has a value

I am getting an Undefined Variable error even though I have passed the variable through the controller using compact(), and I even tried passing the variable to the blade view like so return view('address/create', ['addresses' => $addresses]);
Route:
Route::get('/addresses/create', function () {
return view('address/create');
})->middleware(\App\Http\Middleware\CheckSuperUser::class);
Controller function:
public function create()
{
$addresses = Address::all();
return view('address/create', compact('addresses'));
}
View code (address/create):
<div class="col-md-4">
<legend>Available Addresses</legend>
#foreach($addresses as $address)
{{ $address }}
#endforeach
</div>
Error message:
ErrorException in 656cf590f275580a61ff680434f2a7bc0399cbdb.php line 51:
Undefined variable: addresses (View: C:\Users\xxx\xxx\xxx\dorf\resources\views\address\create.blade.php)
I tried clearing the cache and views, but that didn't help at all. Restarted the server and the computer and still same error. Any ideas what might be going on?
#qasimalbaqali You are giving wrong path You have to use like this
Route::get('/addresses/create','ControllerName#create')->middleware(\App\Http\Middleware\CheckSuperUser::class);
Replace ControllerName with your Controller.
I hope this will help you.
Try to pass this way
return view('address/create')->with('addresses', $addresses);
Updated
#foreach($addresses as $address)
{{ $address->address }}
#endforeach

Resources