when i run laravel project on my computer after doing php artisan serve as soon as it login it shows error "Attempt to read property "menus" on null"
Please help me
#foreach ($specials->menus as $menu)
<div class="max-w-xs mx-4 mb-2 rounded-lg shadow-lg">
<img class="w-full h-48" src="{{ Storage::url($menu->image) }}" alt="Image" />
<div class="px-6 py-4">
<h4 class="mb-3 text-xl font-semibold tracking-tight text-green-600 uppercase">
{{ $menu->name }}</h4>
<p class="leading-normal text-gray-700">{{ $menu->description }}.</p>
</div>
<div class="flex items-center justify-between p-4">
<span class="text-xl text-green-600">${{ $menu->price }}</span>
</div>
</div>
#endforeach
welcomecontroller.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Menu extends Model
{
use HasFactory;
protected $fillable = ['name', 'price', 'description', 'image'];
public function categories()
{
return $this->belongsToMany(Category::class, 'category_menu');
}
}
I suppose you forgot to initialize $specials, it is null, that's why you get the error.
Could you try to use dd before foreach statement, so we can see it's content?
{{ dd($specials) }}
UPDATE:
#if(!is_null($specials))
#foreach ($specials->menus as $menu)
<div class="max-w-xs mx-4 mb-2 rounded-lg shadow-lg">
<img class="w-full h-48" src="{{ Storage::url($menu->image) }}" alt="Image" />
<div class="px-6 py-4">
<h4 class="mb-3 text-xl font-semibold tracking-tight text-green-600 uppercase">
{{ $menu->name }}</h4>
<p class="leading-normal text-gray-700">{{ $menu->description }}.</p>
</div>
<div class="flex items-center justify-between p-4">
<span class="text-xl text-green-600">${{ $menu->price }}</span>
</div>
</div>
#endforeach
#else
<div>no item was found</div>
#endif
Your issue is with this line of code (from the comments):
$specials = Category::where('name', 'specials')->first();
->first(); can return null, so when you use it later as $specials->menus, it can be null->menus, which is not valid.
You can use ->firstOrFail() to trigger a 404 in the event $specials results in null, or #foreach($specials->menus ?? [] as $menu) to short-circuit your foreach() with an empty array if $specials is null:
In your Controller:
$specials = Category::where('name', 'specials')->firstOrFail();
return view('welcome', compact('specials'));
OR
In your View:
#foreach($specials->menus ?? [] as $menu)
...
#endforeach
Either case will properly handle your "unsafe" code (unsafe meaning functional, but possible for unhandled errors, like null->menus, etc.) and either trigger a 404 before the view is rendered, or perform a foreach() on an empty array, which does nothing.
Related
Method App\Http\Controllers\CommunityController::show does not exist
My route
Route::get('/community/{id}', [CommunityController::class, 'community'])
->name('profile.community');
Controller
public function community($id)
{
$communityProfile = Community::find($id);
/* $join = CommunityUser::join('communities', 'communities.user_id', '=', 'community_users.user_id')->get(); */
return view('user.comprofile', compact('communityProfile', 'join'));
}
View community
#for ($i = 0; $i < 3; $i++)
<a href=" {{ route('profile.community', $communities[$i]->id) }} ">
<div class="w-full p-6 overflow-hidden bg-white border hover:bg-gray-50 border-gray-200 rounded-lg shadow-md dark:bg-gray-800 dark:border-gray-700">
<h5 class="mb-2 text-2xl font-semibold tracking-tight text-gray-900 dark:text-white">{{$communities[$i]->community}}</h5>
<p class="mb-3 font-normal text-gray-500 dark:text-gray-400 flex gap-3">
<x-iconsax-out-location class="text-[#F15E4A] w-5"/> {{$communities[$i]->address}}, {{$communities[$i]->city}}
</p>
<div class="flex gap-2">
<a href="#" class="inline-flex items-center font-semibold text-[#F15E4A] hover:underline cursor-default">
{{ $communities[$i]->type }}
</a>
#if ($communities[$i]->user_id === Auth::user()->id)
<span class="text-sm text-gray-500 pt-1">{{__('Created by: ')}}</span>
{{Auth::user()->name}}
#else
<span class="text-sm text-gray-500 pt-1">{{__('Created by: ')}}</span>
{{ $communities[$i]->name }}
#endif
</div>
</div>
</a>
#endfor
I am trying to view the community created by users but it gives me "cannot find a Controller Method ".
This can have several causes. Therefore, here is a small checklist:
The controller path is missing from your route:
use App\Http\Controllers\CommunityController; // this line
Route::get('/community/{id}', [CommunityController::class, 'community'])->name('profile.community');
Your CommunityController class name is misspelled
The namespace of the CommunityController is wrong
And then just to be sure, run: php artisan route:clear.
So my front-end Lists of Businesses are not in paginated style. But I do not know how to do it. Can anyone please help? The code I posted is in my BusinessListController.php
BusinessListController.php
`<?php
namespace App\Http\Controllers;
use App\Models\Business;
use App\Models\Category;
use App\Models\Location;
use Illuminate\Http\Request;
class BusinessListController extends Controller
{
public function index(Request $request)
{
$businesses = Business::query()
->with('location')
->whereFilters($request->only(
['search', 'category', 'location']
))
->get();d
return view('pages.business-list', [
'businesses' => $businesses,
'locations' => Location::all(),
'categories' => Category::all()
]);
}
}`
And then here is the code for my view blade front-end
Business-List.blade.php
<div class="row business-list-row mx-auto">
#foreach ($businesses as $business)
<div class="col-md-4">
<div class="card shadow border-light mb-3">
<img
src="https://cdn1.clickthecity.com/images/articles/content/5d6eba1f4795e0.58378778.jpg"
class="card-img-top" alt="...">
<div class="card-body">
<div class="d-flex justify-content-between">
<div>
<h4 class="card-title h6" style="font-weight: bold;">
{{Str::limit($business->name, 20, $end='...')}}
</h4>
<div class="">
<p class="card-text">
{{ $business->location?->name }}
</p>
<p class="card-text" style="color: #32a852;">
{{ $business->category?->name}}
</p>
</div>
</div>
<div class="align-self-center">
<a href="{{ route('store', $business->id) }}" class="btn btn-info stretched-link">
Visit
</a>
</div>
</div>
</div>
</div>
</div>
#endforeach
</div>
So you need to do three things.
In Controller:
$businesses = Business::query()
->with('location')
->whereFilters($request->only(
['search', 'category', 'location']
))
->paginate(15);
put the number of items you need on a single page. here I put 15.
Put this under the </div> of your list.
{{ $business->links() }}
Put this inside the App\Providers\AppServiceProvider boot method.
use Illuminate\Pagination\Paginator;
public function boot()
{
Paginator::useBootstrapFive(); // or
Paginator::useBootstrapFour();
}
This depends upon which version of Bootstrap you are using.
Still confused? Checkout Laravel Pagination Documentation
Just remove ->get();d and add paginate
example
ModelName()->paginate();
im trying to take 3 most viewed post but its just getting only two I don't know why I have tried limit () method it's not showing anything what am I doing wrong here ,
<?php
namespace App\Http\Livewire;
use App\Models\Movie;
use Livewire\Component;
class MovieBox extends Component
{
public function render()
{
return view('livewire.movie-box',[
'movies' => Movie::withCount('read_count')->orderBy('reads', 'desc')->take(3)->get(),
]);
}
}
movie box
<div>
<div class="relative grid grid-cols-3 gap-2 mt-3 user_story md:grid-cols-5">
#foreach ( $movies as $movie )
<a href="#create-post" uk-toggle="target: body ; cls: story-">
<div class="single_story">
<img src="assets/images/avatars/avatar-lg-1.jpg" alt="">
<div class="story-avatar"> <img src="assets/images/avatars/avatar-1.jpg" alt=""></div>
<div class="story-content">
<h4> {{ $movie->title }}</h4>
</div>
</div>
</a>
#endforeach
<span
class="absolute z-10 items-center justify-center hidden p-2 -mr-4 text-xl bg-white rounded-full shadow-md lg:flex w-9 uk-position-center-right"
uk-toggle="target: body ; cls: story-">
<i class="icon-feather-chevron-right"></i></span>
</div>
Change your render method like this.
public function render()
{
return view('livewire.movie-box',[
'movies' => Movie::withCount('read_count')->orderBy('reads', 'desc')->limit(3)->get(),
]);
}
I'm trying to use Laravel pagination. The issue is that when I use the links() method in the Blade file, it gives an error. For example, when I use the URL "http://127.0.0.1:8000/tournaments?page=3," it works fine, but it gives an error in the Blade file, as explained below.
Controller
public function index()
{
return view('front.tournaments', [
'seriesdata' => $this->tournamentList()
]);
}
public function tournamentList()
{
return Series::leftJoin('team_squads as ts', 'ts.id_series', 'series.id')
->leftJoin('series_team_squads as sts', 'sts.id_series', 'series.id')
->leftJoin('admins as a', 'a.adminable_id', 'series.id')
->where('series.lang', 'en')
->orderBy('series.id', 'asc')
->groupBy('series.id')
->select('series.*')
->paginate(10)
->append([
'logo_url',
'location'
]);
}
Blade
#foreach($seriesdata as $series)
<div class="flex flex-inline xs:flex-col sm:flex-row">
<div class="w-full border-b">
<div class="flex justify-center items-start">
<div class="py-2 mx-auto sm:bg-white xs:bg-white w-full">
<a href="{{ url('tournaments/').'/'.$series->url.'/'.$series->id }}" class="flex">
<div class="grid grid-rows-1 grid-flow-col gap-1">
<div class="row-span-1 col-span-2">
<img src="{{ $series->logo_url }}" alt="avatar" class="object-cover w-12 h-12 mx-4">
</div>
<div class="row-span-1 col-span-2">
<h1 class="font-bold text-lg">{{ $series->name }}</h1>
<p class="uppercase font-light text-sm text-grey">{{ $series->location->address }}</p>
</div>
</div>
</a>
</div>
</div>
</div>
</div>
#endforeach
{{ $seriesdata->links() }}
Error
It looks like your append() method is blocking pagination in blade. Try to remove it from tournamentList() in controller.
When you do ->append() after the ->paginate(), you are transforming what ->paginate() returns (basically a LenghtAwarePaginator) into a Collection, and Collection does not have a ->links() method. You can see this as the error shows you are trying to call links method in Illuminate\Database\Eloquent\Collection, that is how I know what ->append() is returning.
for example this is our simple blade view that called dashboard and our class model is "user"
does it work to take use it inside blade like following code? line 1,12
{{use App\Models\User;
$user= User::where('id', '1234')->first();}}
<x-app-layout>
<x-slot name="header">
<h2 class="font-semibold text-xl text-gray-800 leading-tight">
{{ __('Dashboard') }}
</h2>
</x-slot>
<div class="py-12">
<div class="max-w-7xl mx-auto sm:px-6 lg:px-8">
<div class="bg-white overflow-hidden shadow-sm sm:rounded-lg">
<div class="p-6 bg-white border-b border-gray-200">
{{ $user->name }}
</div>
</div>
</div>
</div>
You are confusing things, you SHOULD pass variables to the view IN the controller and then use them in the view (as of your line 12th)
To use that variable in the view, you should pass it in the controller: i.e:
publix function index(){
$user = User::find(1);
return view('index',['user'=>$user]); //'user' is the name of the variable in the view and $user the value that variable will take
}
Then you can use {{$user->id}}
the "use App\Models\User;" syntax should only be used on Controllers or PHP classes, if you indeed need to use the actual model in view (in a loop for example) you can achieve that also!
#foreach(App\Models\User::all() as $user)
<!-- html code -->
#endforeach
<!-- OR -->
{{ App\Models\User::find(104)->name }}
Hope it helped!
You can import classes in .blade.php files the same way you would in any other .php file:
#php
use App\Models\User;
$user= User::where('id', '1234')->first();
#endphp
<x-app-layout>
<x-slot name="header">
<h2 class="font-semibold text-xl text-gray-800 leading-tight">
{{ __('Dashboard') }}
</h2>
</x-slot>
<div class="py-12">
<div class="max-w-7xl mx-auto sm:px-6 lg:px-8">
<div class="bg-white overflow-hidden shadow-sm sm:rounded-lg">
<div class="p-6 bg-white border-b border-gray-200">
{{ $user->name }}
</div>
</div>
</div>
</div>
In this particular case there's little benefit in doing this though and it's generally not a good idea to have database queries happening in view code since views should not be responsible for retrieving models. That's the responsibility of the controller or helpers called from the controller.
you should define all your logic in controller and model.
And pass the data in variable to the blade file.
And there you can use all data using
#foreach(....)
#endforeach