Undefined variable when trying to use two loops - laravel

I have two functions
whatsnew()
and
perfume()
both has its own #foreach in different sub folders which i show them in one page.
problem is if one #foreach works the other show an error undefined variable
ps- this is my first time posting a question in SO .. sorry if its sloppy..
ProductController.php
//to show last 5 latest items
public function whatsnew(){
$cat_new = products::orderBy('id', 'desc')->take(5)->get();
return view('/home', compact('cat_new'));
}
//to show category
public function perfume(){
$perfume = products::where('category','LIKE','perfume')->get();
return view('/home', compact('perfume'));
}
Web.blade.php
Route::get('/', [
'uses' => 'ProductController#whatsnew',
'as' => 'db.whatsnew']);
Route::get('/', [
'uses' => 'ProductController#perfume',
'as' => 'db.perfume']);
perfume.blade.php
#foreach($perfume as $perfume_cat)
whatnew.blade.php
#foreach($cat_new as $row)

It looks like you are passing only 1 collection back to the view each time, which is probably why one or the other works.
If you change this:
public function whatsnew(){
$cat_new = products::orderBy('id', 'desc')->take(5)->get();
return view('/home', compact('cat_new'));
}
public function perfume(){
$perfume = products::where('category','LIKE','perfume')->get();
return view('/home', compact('perfume'));
}
to this:
public function whatsNew(){
$cat_new = products::orderBy('id', 'desc')->take(5)->get();
return $cat_new; // return the collection
}
public function perfume(){
$perfume = products::where('category','LIKE','perfume')->get();
return $perfume; // return the collection
}
// Create a new index function and pass both collections to your view
public function index() {
return view('index', [
'cat_new' => $this->whatsNew(),
'perfume' => $this->perfume(),
]);
}
Your web routes file can be:
Route::get('/', 'ProductController#index')->name('product.index');
Your index.blade.php
<div class="container">
<div class="row">
<div class="col-lg-12">
<div class="card">
<div class="card-body">
<ol>
#foreach( $cat_new as $new )
<li>{{ $new->foo }}</li>
#endforeach
</ol>
</div>
</div>
<div class="card">
<div class="card-body">
<ol>
#foreach( $perfume as $p )
<li>{{ $p->bar }}</li>
#endforeach
</ol>
</div>
</div>
</div>
</div>
</div>
where foo and bar are whatever columns you are after.

//merge become one
public function perfume(){
$perfume = products::where('category','LIKE','perfume')->get();
$cat_new = products::orderBy('id', 'desc')->take(5)->get();
return view('/home', compact('perfume', 'cat_new'));
}

Related

Show category posts in Laravel is not working

I want to show posts that are in a category by clicking on them, but when I click on a category,$articles in category.blade.php returns null.
$articles should return articles that have a specific category
this is my index.blade.php:
<div class="tab-pane fade" id="show-categories" role="tabpanel">
<h6 class="sidebar-title">Categories</h6>
<div class="row link-color-default fs-14 lh-24">
#foreach($categories as $category)
<div class="col-6">
<a href="{{ route('cms.category', $category->id) }}">
{{ $category->name }}
</a>
</div>
#endforeach
</div>
</div>
category.blade.php:
#extends('layouts.app')
#section('content')
#forelse ($articles as $article)
<h1>{{$article->title}}</h1>
#empty
<span>array is empty</span>
#endforelse
#endsection
router:
Route::get('cms/categories/{category}', [articlesController::class, 'category'])->name('cms.category');
and articlesController:
public function category(Category $category)
{
return view('cms.category')
->with('category', $category)
->with('articles', $category->articles()->searched()->simplePaginate(3))
->with('categories', Category::all())
->with('tags', Tag::all());
}
Please, don't forget to define the relationship from Category to Article on your model. Like: one category has many articles. For example:
On your Category.php model:
public function articles()
{
return $this->hasMany(Article::class);
}
Then on your, controller, you may call the relationship like this way:
public function category(Category $category)
{
$articles = Category::with("articles")->where("id", $category->id)->simplePaginate(3);
return view('cms.category')
->with('category', $category)
->with('articles', $articles)
->with('categories', Category::all())
->with('tags', Tag::all());
}
Please share the model file and second I prefer to write the category method in a different way.
public function category($category_id)
{
try {
$articles= Article::where('id', $category_id)->get();
return view('cms.category', $articles);
} catch (\Throwable $th) {
Log::error($th->getMessage());
}
}
Let me know if you still face any issue. Try to use dd $articles ..

Laravel 8 form select option dropdown problem

Am having problem here
I have two tables
Department table
with fields
id dept_code dept_name
I also have Persons table
with fields
id Persons_names Dept_name Position_held
I have a data entry form to enter data to the Persons_table
the problem am having is I want to create select option to get Dept_name From Department_table but am always getting undefined value error.
this is my form
{!! Form::open(['url' => 'persons_form/store']) !!}
{{ csrf_field() }}
<div class="form-row">
<div class="form-group col-md-6">
{{Form::label('FullNames', 'Fullnames')}}
{{Form::text('names', '',['class'=>'form-control','placeholder'=>'Persons Fullnames'])}}
</div>
<div class="form-group col-md-6">
{{Form::label('Department', 'Department')}}
#foreach ($depts as $dept)
{{
Form::select('department', $dept->department_name, null, ['class'=>'form-control','placeholder' => 'Select Department'])
}}
#endforeach
</div>
<div class="form-group col-md-12">
{{Form::label('Position', 'Position')}}
{{Form::text('level', '',['class'=>'form-control','placeholder'=>'Departmental Position'])}}
</div>
</div>
<div>
{{Form::submit('Save Data',['class'=>'btn btn-outline-primary text-center',])}}
</div>
{!! Form::close() !!}
this is my personsController
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Models\People;
class PeopleController extends Controller
{
public function index()
{
$depts = DB::table('departments')->select('department_name')->get();
return view('strategic_plan.people_form', ['depts' => $depts]);
}
public function create()
{
$depts = DB::table('departments')->pluck('department_name');
}
public function store(Request $request)
{
$this->validate($request,[
'names'=>'required',
'department'=>'required',
'level' =>'required'
]);
$persons =new People;
$persons->names=$request->input('names');
$persons->department=$request->input('persons');
$persons->level=$request->input('level');
$dept->save();
return redirect('/people')->with('message','Person Added Succesifully');
}
public function show()
{
$persons = People::all()->sortByDesc("id");
return view('strategic_plan.people',compact('persons'));
}
public function edit($id)
{
}
public function update(Request $request, $id)
{
//
}
public function destroy($id)
{
//
}
}
When I try to open the Form am getting
$depts is undefined
Try using compact, And get #dd in your blade of $depts and share the code.
Use
return view('strategic_plan.people_form', ['depts' => $depts]);
instead of
return view('strategic_plan.people_form', compact('depts');
write it down

Livewire throwing error when using paginated data

So I am being given this error when trying to paginate my data and send it in to a view through a livewire component.
I am trying to get all posts and display at max 5 posts per page using pagination in laravel.
Livewire version: 2.3.1
Laravel version: 8.13.0
Error:
Livewire\Exceptions\PublicPropertyTypeNotAllowedException
Livewire component's [user-posts] public property [posts] must be of type: [numeric, string, array, null,
or boolean]. Only protected or private properties can be set as other types because JavaScript doesn't
need to access them.
My Component:
<?php
namespace App\Http\Livewire;
use Livewire\Component;
use App\Models\Post;
use Livewire\WithPagination;
class UserPosts extends Component
{
use WithPagination;
public $posts;
public $type;
protected $listeners = ['refreshPosts'];
public function delete($postId)
{
$post = Post::find($postId);
$post->delete();
$this->posts = $this->posts->except($postId);
}
public function render()
{
if($this->type == 'all')
$this->posts = Post::latest()->paginate(5);
else if($this->type == 'user')
$this->posts = Post::where('user_id',Auth::id())->latest()->paginate(5);
return view('livewire.user-posts', ['posts' => $this->posts]);
}
}
My Blade:
<div wire:poll.5s>
#foreach($posts as $post)
<div style="margin-top: 10px">
<div class="post">
<div class="flex justify-between my-2">
<div class="flex">
<h1>{{ $post->title }}</h1>
<p class="mx-3 py-1 text-xs text-gray-500 font-semibold"
style="margin: 17px 0 16px 40px">{{ $post->created_at->diffForHumans() }}</p>
</div>
#if(Auth::id() == $post->user_id)
<i class="fas fa-times text-red-200 hover:text-red-600 cursor-pointer"
wire:click="delete({{$post->id}})"></i>
#endif
</div>
<img src="{{ asset('image/banner.jpg') }}" style="height:200px;"/>
<p class="text-gray-800">{{ $post->text }}</p>
#livewire('user-comments', [
'post_id' => $post->id,
'type' => 'all'
],
key($post->id)
)
</div>
</div>
#endforeach
{{ $posts->links() }}
</div>
$posts should not be declared as a property in the Livewire component class, you passed the posts with the laravel view() helpers as data.
Remove the line
public $posts;
And replace $this->posts by $posts in the render function:
public function render()
{
if($this->type == 'all')
$posts = Post::latest()->paginate(5);
else if($this->type == 'user')
$posts = Post::where('user_id',Auth::id())->latest()->paginate(5);
return view('livewire.user-posts', ['posts' => $posts]);
}
}

Display tests for lessons who belong to Courses

I have Courses which has lessons, and each lesson has a test. I'm trying to display the test when a lesson is clicked.
I've created the models, controller and view and it doesn't seem to work.
Here is the model for the Lesson
public function course()
{
return $this->belongsTo(Course::class, 'course_id')->withTrashed();
}
public function test() {
return $this->hasOne('App\Test');
}
Here is the controller
public function show($id)
{
$course = Course::with( 'lessons')->with('activeLessons')->findOrFail($id);
$created_bies = \App\User::get()->pluck('name', 'id')->prepend(trans('global.app_please_select'), '');
$trainers = \App\User::get()->pluck('name', 'id');
// $test = \App\Test::where('course_id', $id)->get();
$lesson = \App\Lesson::where('course_id', $id)->get();
// $course_test = Course::with('tests')->findOrFail($id);
$user = User::find(1);
$user->name;
return view('admin.courses.showCourse', compact('course', 'test', 'lesson','course_test', 'previous_lesson', 'next_lesson','date', 'user'));
}
function view_tests($id)
{
$lessons = Lesson::findOrFail($id);
$lessons->test;
return view('admin.courses.test', compact('lessons'));
Here is the Route
Route::get('/test/{id}', 'EmployeeCoursesController#view_tests')->name('test.show');
And here is the Blade with the link to display the test
#foreach($course->activeLessons as $lesson)
<article class="lesson" >
<p></p>
<p></p>
{!! $loop->iteration!!}.
<div class="body" id="title"> {!!$loop->iteration!!}. <h4>{{ $lesson->title }}</div>
<p> {!! $lesson->short_description !!}</p>
<iframe width="420" height="315" src="{{ $lesson->video_link}}" frameborder="0" allowfullscreen></iframe>
</article>
#endforeach
The issue was on the test blade. The code works well.

How to Call/Display Foreach Loop after Login

I had problem on calling page inside Foreach Loop.Although It is Okay before I click Login, but when I'd try to login,only the html tag where loaded and foreach loop cannot... On my HomeController extends Controller
public function index()
{
return view('pages.welcome');
}
on where I call welcome page. and inside of it which is foreach loop.
<div class="row">
<div class="col-md-8">
#foreach ($posts as $post)
<div class="post">
<h3>{{ $post->title }}</h3>
<p>{{ substr($post->body, 0,300) }}
{{ strlen($post->body) > 300 ? "..." : " " }}</p>
Read More...
</div>
<hr>
#endforeach
</div>
</div>
And I think the problem is my route:
Route::get('/home', 'HomeController#index');
You haven't passed the $posts variable to the view.
Change
public function index()
{
return view('pages.welcome');
}
To something like this:
public function index()
{
$posts = \App\Post::all(); //Assuming your model is called "Post" in the App namespace
return view('pages.welcome', compact('posts'));
}
NOTE: compact('posts') is just a shortcut for ['posts'=>$posts]

Resources