Array works fine on localhost but not working on live server (gives error message Undefined offset: 0) - Laravel-5.8 - laravel-5.8

Everything works perfectly okay on localhost but when migrated to godaddy live server(cpanel) I keep getting this error (Undefined offset: 0) on my blade view
I have tested the application on my localhost using XAMPP running PHP 7.2.12 and it works very fine but now I moved it to godaddy cpanel running PHP 7.3 and it keeps giving me this error
//This is my Route
Route::get('/conversations', 'DoctorsController#Conversations');
//This is my Controller
public function Conversations(Request $request){
//authenticate user
if($request->us == 'guest'){
return redirect()->intended('login');
}else{
$unread=DB::table('messaging')
->where([
['Reciever', Auth::user()->id],
['ReadStatus', '=', '']
])
->get();
$pending=$unread->count();
//retrieve previous chat;
$conversations=DB::table('messaging')
->where('Sender', Auth::user()->id)
->orWhere('Reciever', Auth::user()->id)
->groupBy('Sender')
->orderBy('ReadStatus', 'asc')
->get();
//retrieve profile of users in the previous chat
$profiles = array();
$read_status = array();
foreach($conversations as $conversation){
if($conversation->Sender == Auth::user()->id){
//check user role to know which database to query
$userRole=DB::table('role_user')
->where('user_id', $conversation->Reciever)
->get();
if($userRole[0]->role_id === 2){
#retrieve the sender details from doctors table
$profile=DB::table('doctors')
->where('doctor_id', $conversation->Reciever)
->get();
}else{
//retrieve the sender details from users table
$profile=DB::table('profiles')
->where('user_id', $conversation->Reciever)
->get();
}
if(in_array($profile, $profiles)){
}else{
array_push($profiles, $profile);
}
//retrieve the reciever details
}else if($conversation->Reciever == Auth::user()->id){
//check user role to know which database to query
$userRole=DB::table('role_user')
->where('user_id', $conversation->Sender)
->get();
if($userRole[0]->role_id === 2){
$profile=DB::table('doctors')
->where('doctor_id', $conversation->Sender)
->get();
}else{
$profile=DB::table('profiles')
->where('user_id', $conversation->Sender)
->get();
}
//retrive unread chat;
$unreadconvers=DB::table('messaging')
->select('ReadStatus')
->where([
['Reciever', Auth::user()->id],
['Sender', $conversation->Sender],
['ReadStatus', '=', '']
])
->get();
if(in_array($profile, $profiles)){
}else{
$profile['unreads'] = $unreadconvers->count();
array_push($profiles, $profile);
//array_push($read_status, $unreadconvers->count());
}
}
$i++;
}
return view('conversations')->with(['profile'=>$profiles, 'pending'=>$pending, 'unreads'=>$read_status]);
//return to the conversation blade
}
}
//This is my Blade template
#foreach($profile as $profile)
<div class="col-md-4 element-animate">
<div class="media d-block media-custom text-center">
<img src= "{{ URL::to(isset($profile[0]->image) ? $profile[0]->image : '../img/user.png') }}" alt="Image Placeholder" class="img-fluid img-fluid-doctors">
<div class="media-body">
<a href="{{ isset($profile[0]->doctor_id) ? url('/chat-doctor?db='.$profile[0]->doctor_id) : url('/chat-doctor?us='.$profile[0]->user_id) }}" class="envelop"><i class="far fa-envelope"></i><span class="unread">{{ isset($profile['unreads']) ? $profile['unreads'] : 0 }}</span>
<h3 class="mt-0 text-black">{{ $profile[0]->name }}</h3>
</a>
</div>
</div>
</div>
#endforeach
At the Controller, this code is expected to retrieve all the messages from the database linking to the logged in user either send or received, store them using an array and display them at the blade template looping through each of the array.
Currently that is what it does on localhost but on live server I get this error message Undefined offset: 0 (View: /resources/views/conversations.blade.php)

You are overwriting the variable in your foreach loop, therefore on the second iteration, it's looping in the profile object instead of your original array.
Change your controller to:
'profiles' => $profiles,
And change your foreach to loop through $profiles instead:
#foreach ($profiles as $profile)
And replace your $profile[0] with $profile.

I have found the solution to this issue, I was using === instead of == where I have this code
if($userRole[0]->role_id === 2)
I now change this line of code to
if($userRole[0]->role_id == 2)
and now is working perfectly well.
Thank you for your response Chin Leung.

Related

Check SHA-256 Laravel

I have a system that requires a homeowner to submit a form about their guest's details. When they submit a form, each will be assigned a unique 6-digit code. This code will be hashed with SHA-256. In the admin's view, there is a list of all submitted forms. I want to do a search function where when I enter the code, the system will look through the hashed code and check if it exists or not.
This is my GuestController:
public function index()
{
//returns admin's view
$guest = Guest::all();
return view('pages.guest.index', compact('guest'));
}
public function store(Request $request)
{
$guest = new Guest;
$guest->code = random_int(100000, 999999);
$guest->hash = hash('sha256', $guest['code']);
$guest->owner_id = Auth::user()->id;
$guest->owner = Auth::user()->name;
$guest->unit = Auth::user()->unit;
$guest->guestname = $request->input('guestname');
$guest->guestphone = $request->input('guestphone');
$guest->guestic = $request->input('guestic');
$guest->guestcar = $request->input('guestcar');
$guest->numberofguests = $request->input('numberofguests');
$guest->datevisit = $request->input('datevisit');
$guest->timevisit = $request->input('timevisit');
$guest->save();
return redirect('show-pass')->with('status', 'Guest Added Successfully');
}
public function search(Request $request)
{
//Get the search value from the request
$search = $request->input('search');
//Search in the code from the list
$guest = Guest::query()
->where('code', 'LIKE', "%{$search}%")
->get();
//Return the search view with the results compacted
return view('pages.guest.search', compact('guest'));
}
This is my search result blade:
<div class="card-body">
#if($guest->isNotEmpty())
#foreach ($guest as $item)
<div class="post-list">
<p>Owner : {{ $item->owner }}</p>
<p>Unit : {{ $item->unit }}</p>
<p>Guest Name : {{ $item->guestname }}</p>
<p>Guest Phone Number : {{ $item->guestphone }}</p>
<p>Guest IC Number : {{ $item->guestic }}</p>
<p>Guest Car Number : {{ $item->guestcar }}</p>
<p>Date : {{ $item->datevisit }}</p>
<p>Time : {{ $item->timevisit }}</p>
</div>
#endforeach
#else
<div>
<h4>No guests with the code was found</h4>
</div>
#endif
</div>
Is what I'm trying to do possible? If yes, how can I edit my search method to be able to do so? May I get some help?

Is it possible to pass 2 variables to a view in View Composers?

I am trying to pass 2 variables to View Composers like this:
public function compose(View $view)
{
$catalog = Category::with('children')->where('parent_id', NULL)->get();
//
if(isset($catalog->img)){
// $cat = Category::
$contents = collect(Storage::disk('google')->listContents('sdfJSALSNldKdnslwk230jsd/', false));
$file = $contents
->where('type', '=', 'file')
->where('filename', '=', pathinfo($catalog->img, PATHINFO_FILENAME))
->where('extension', '=', pathinfo($catalog->img, PATHINFO_EXTENSION))
->first();
$catimg = isset($file['path'])?(Storage::disk('google')->exists($file['path'])?Storage::disk('google')->url($file['path']):NULL):NULL;
};
//
return $view->with(['catalog' => $catalog, 'catimg' => $catimg]);
}
But I am getting the error: Undefined variable $catimg.
Perhaps this is not the correct method for passing the second variable?
And also, at the top I check if the image exists in the database, but it seems to me that this is the wrong way, since only parent elements are returned there, how can I check if there is an image for each category? Probably need to run through foreach?
#foreach( $catalog as $item )
<li class='has-sub'><img class="catalogimg" src="#isset($item->img){{Storage::url($catimg)}}#else /img/categories/kitchen-utensils.png #endisset"><span class="cat-text">{{ $item->name }}</span>
<ul>
#foreach( $item->children as $subitem )
<li><span class="cat-text">{{ $subitem->name }}</span></li>
#endforeach
</ul>
</li>
#endforeach
You are passing the variables correctly!
The problem is that you defined $catimg only inside your if-structure.
You will have to think about the case when isset($catalog->img) is false.
In this case no image is present for the category and the if-structure won't be entered and therefore $catimg is not defined. So you will either have to check in your view file if $cat_img is set, return a default image or disallow this action. (Or only allow categories with images).

I have wrong route in laravel

I get data from Search and when i want to store/create again, its show "pages not found"
Controller Search
public function searchGuest(Request $request)
{
$q = $request->input('q');
if ($q != "") {
$guests = Guest::where('guestsid', 'LIKE', '%' . $q . '%')
->whereIn('id_status', [2])
->paginate(5);
if (count($guests) > 0) {
$lokasis = Lokasi::all();
return view('guests.guestsId', compact('guests', 'lokasis'));
} else {
return view('guests.searchNotFound');
}
}
}
View
<form action="{{ action('GuestController#store') }}" method="post" id="myform">
{{ csrf_field() }}
<fieldset>
and when i click submit button show this page
but form already get data, but still /searchGuest, in this pict is must /guestsId right?
check if query returns any results otherwise check your query dd(DB::getQueryLog());

I want to use images of products that I register in the database - Laravel

I programmed a product registration. The registration for the database is working correctly. My problem is that I can't show the images that I registered in the database. I created an imput where the name of the image is inserted. This name is saved in the database and the image is saved with the same name, however it is saval in public. The images are inside the public / storage / products folder.
Controller:
public function index()
{
$products = Product::paginate(10);
return view('products.index', [
'products' => $products,
]);
}
public function store(Request $request)
{
// Create registration
$data = $request->only('name', 'price', 'imageName');
Product::create($data);
// Image
if($request->file('imageProduct')->isValid()){
$nameFile = $request->imageName . '.' . $request->file('imageProduct')->getClientOriginalExtension();
$request->file('imageProduct')->storeAs('products', $nameFile);
return redirect()->route('ProductControllerIndex');
}
}
view:
<div>
#foreach ($products as $product)
<p>
Id: {{ $product->id }}
</p>
<p>
Nome do produto: {{ $product->name }}
</p>
<p>
Preço: {{ $product->price }}
</p>
<p>
{{ $product->imageName }}
</p>
<p>
<img src="{{ asset('storage/products/'.$product->imageName) }}" alt="">
</p>
<hr>
#endforeach
</div>
The core issue here is that your Image's extension is not being saved to the database, so $product->imageName, when used in the asset() helper, doesn't generate a complete URL for the image. You'll need to refactor your code a little to get it to save:
public function store(Request $request) {
$nameFile = $request->input('imageName', '');
if($request->file('imageProduct')->isValid()){
$nameFile .= '.' . $request->file('imageProduct')->getClientOriginalExtension();
$request->file('imageProduct')->storeAs('products', $nameFile);
}
$request->merge(['imageName' => $nameFile]);
$data = $request->only('name', 'price', 'imageName');
Product::create($data);
return redirect()->route('ProductControllerIndex');
}
In the above code, the value for $nameFile is defaulted to the value in $request->input('imageName'), or an empty string '' if nothing is supplied. Next, if a valid image is uploaded, the $nameFile variable is appended with the extension. Lastly, the $request variable is updated with the name value for imageName. The remainder of the code creates the new Product with the data supplied (using the ->only() modifier) and redirect as required.
The rest of your code should be ok, as long as the file exists in the correct directory after ->storeAs() and the fully-qualified image name is saved to the database.
Note: If for whatever reason Product::create() doesn't work with this approach, you can use the new Product() ... $product->save() approach: (there might be an issue with $request->merge() using an existing key, as I can't actually test that)
$product = new Product();
$product->name = $request->input('name');
$product->price = $request->input('price');
$product->imageName = $fileName;
$product->save();

Laratrust and users

I do have an app in Laravel 5.5 using Laratrust last version to give roles and permissions.
Now, I want to let and Administrator lists only the users he has created and let the Superadministrator see ALL users.
Let's see some code:
UserController.php
public function index()
{
$id = Auth::user()->id;
if ($id = Laratrust::hasRole('superadministrator')) {
$users = User::orderBy('id', 'desc')->paginate(10);
}
$users = User::where('id', '=', $id)->orderBy('id', 'desc')->paginate(10);
return view('manage.users.index')->withUsers($users);
}
Manage navbar:
#if(Laratrust::hasRole('superadministrator|administrator'))
<li>Usuários</li>
<li>
<a class="has-submenu {{Nav::hasSegment(['roles', 'permissions'], 2)}}">Cargos & Permissões</a>
<ul class="submenu">
<li>Cargos</li>
<li>Permissões</li>
</ul>
</li>
#endif
Any ideas, please?
You are overwriting the $users variable in controller

Resources