Execute a value twice from the database - php

I have a strange problem, I am working on a personal project in Laravel, a "Q&A" type site, so far everything is fine. When I want to post a question from the database, it will be displayed twice on the display page, even if I only put the question with a certain id.
the error that appears
Route:
Route::get('/viewUserQuestion/{post}', 'PostsController#viewUserQuestion')->name('viewQuestion');
Controllerr:
public function viewUserQuestion() {
if(Auth::check()) {
$posts = Post::latest()->get();
return view('viewQuestion', compact('posts'));
}
else {
return redirect('register');
}
}
Blade:
<div class="card-body p-0">
#foreach($posts as $post)
<div class="mailbox-read-info">
<h5 align="center"> {{ $post->title }}</h5>
<h6> From userID: {{ $post->user_id }}</h6>
<span class="mailbox-read-time" align="center">Created at: {{ $post->created_at }}</span></h6>
</div><div class="mailbox-read-message">
<p>{{ $post->content }}</p>
Route to the display page:
<td>{{ $post->id }}</td>
What do you think would be the exact problem? I would be grateful if you could help me, does it run twice or does it?

Basically I want to display the data from each id, but in different pages without overlapping. As it is here, you click on a question and display it not twice.

Related

(Laravel 9) Foreach Loop is showing multiple items for one row of data and not showing other data in one view

So I have this problem with my Laravel project that I'm working on right now when I'm trying to store one data to the database but in the view, it shows five of it. And whenever I add another data. It won't stack. Kind of confusing, ain't it?
So What I'm actually trying to do is that I have 2 Models and is trying to overlap them to each other. As I search for ways to make them show in one view, I concluded in putting them into one Controller.
I made their Store CRUD separate so that it would work and this is how it looks like:
public function groupStore(Request $request)
{
$request->validate([
'title'=>'required',
'subject'=>'required',
'section'=>'required',
'team'=>'required',
'advisor'=>'required',
]);
GroupProject::create($request->all());
return redirect()->back()->with('success', 'Created Project Successfully.');
}
public function projectStore(Request $request)
{
$request->validate([
'title'=>'required',
'file'=>'required',
'description'=>'required',
]);
$file = $request->file('file');
$fileName = time().'_'.$file->getClientOriginalName();
$file->move(public_path('files'), $fileName);
$data = array(
'title'=>$request->title,
'file'=>$fileName,
'description'=>$request->description
);
Project::create($data);
return redirect()->back()->with('success', 'Posted Project Successfully.');
}
And here is how the Show CRUD looks like:
public function show(GroupProject $group_projects, Project $projects, $id)
{
$group_projects = GroupProject::find($id);
$projects = Project::find($id);
if (auth()->user()->type == 'faculty') {
return view('faculty/project', compact(['group_projects', 'projects']));
}else if (auth()->user()->type == 'office') {
return view('office/project', compact(['group_projects', 'projects']));
}else{
return view('student/project', compact(['group_projects', 'projects']));
}
}
PS: I'm trying to have Three users which makes the if else statements.
Now here's where the real problem comes from. As I make the "Group Project", I made the view with a foreach loop in order to show everything from my datastore, such as this and the corresponding program for it looks like this:
#foreach($group_projects as $key => $groupProject)
<div class="col flex">
<div class="card h-100">
<div class="card-body">
<h3 class="card-title">{{ $groupProject->title }}</h3>
<h6>{{ $groupProject->subject }}</h6>
<h6>{{ $groupProject->section }}</h6>
<h6>{{ $groupProject->team }}</h6>
<h6>{{ $groupProject->advisor }}</h6>
<div class="dropdown">
<button id="dropdownMenu" class="btn btn-secondary dropdown-toggle" type="button" data-bs-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
{{ __('Actions') }}
</button>
<ul class="dropdown-menu" aria-labelledby="dropdownMenu">
<li><a class="dropdown-item" href="{{ URL::to('project/' . $groupProject->id) }}">
{{ __('Show')}}
</a></li>
</ul>
</div>
</div>
</div>
</div>
#endforeach
On this case, there seems to be no problem at all and it works perfectly fine even if I try to add another one.
But as I try to click it and change the view, this would be how it looks like after storing a "Project" and here's its corresponding Code:
#if (is_array($projects) || is_object($projects))
#foreach($projects as $key => $project)
<div class="col flex my-2">
<div class="card">
<div class="card-body">
<h3 class="card-title">{{ $projects->title }}</h3>
<iframe src="/files/{{ $projects->file }}"></iframe>
<h6>{{ $projects->description }}</h6>
</div>
</div>
</div>
#endforeach
#endif
And after adding another "Project" it will not show up on the "Test Title 1" but instead in "Test Title 2" which is pretty frustrating.
At first I'm thinking that it might be because I made the if statement of "#if (is_array($projects) || is_object($projects))" but if I remove this part, it would show an error when I'm trying to view a "Group Project" While there's nothing in the "Project" yet.
Another is that after making the foreach loop "#foreach($projects as $key => $project)" , I still call the "$projects->title" instead of "$project->title". but the reason for this is that it shows an error of "Attempt to read property "title" on bool".
I wonder, what should I do?
EDIT:
Nevermind Guys, I actually solved it just now.
So the real problem was on my Show CRUD. Instead of listing it as
$group_projects = GroupProject::find($id);
$projects = Project::find($id);
I should've called it as
$group_projects = GroupProject::find($id);
$projects = Project::all();
And Everything will be solved lol..... Now my problem is how to overlap them into one another such as 1 "Group Project" can have multiple "Project"....

Trying to get property 'title' of non-object (View: C:\xampp\htdocs\lsapp\resources\views\posts\show.blade.php)

I am getting above error while requesting to next page but I want posts title is as page title as well
#extends('layouts.app')
#section('pageTitle', $post->title)
#section('content')
Go Back
<br> <br>
<h1>{{ $post->title }}</h1>
<div class="">
<p>{!! $post->body !!}</p>
</div>
<hr>
<small>Written on: {{ $post->created_at }}</small>
<hr>
Edit
#endsection
public function show($id)
{
$post = Post::find($id);
return view('posts.show')->with('post', $post);
}
Post::find(...) can return null. You will have to make sure that you are actually receiving a model instance, the record exists, before trying to use it. You can use something like Post::findOrFail(...) to allow this to fail when it doesn't find a record. This would allow you to continue in the code knowing $post will be a valid instance.
Because the return type should be an array,
you can use this
public function show($id)
{
$post[] = Post::find($id);
return view('posts.show')->with('post', $post);
}

Laravel show latest post on homepage

I'm trying to display the latest post, posted on my website.
I have a vague idea of how it needs to be done but I'm not 100% sure.
I think I need to do something like this in my PostController.php
public function index()
{
$laatstepost = Post::orderBy('created_at', 'desc')->take(1)->get();
return View('showposts')->with('laatsteposts', $laatstepost);
}
And then something like this in my view.
<div class="panel-body">
<h3>{{ $laatsteposts->title }}</h3>
<p>{{ $laatsteposts->text}}</p>
Lees meer...
</div>
I don't know if I'm heading the right way or that I'm completely off track. If u guys can help me out that would be great! Thanks
Here is a screenshot of where it needs to be displayed: http://imgur.com/a/c1feW
If I miss code that is needed for this, Tell me
Use the first() method to get an object instead of collection:
public function index()
{
$laatstepost = Post::latest()->first();
return view('showposts')->with('laatsteposts', $laatstepost);
}
And in the view:
<div class="panel-body">
<h3>{{ $laatsteposts->title }}</h3>
<p>{{ $laatsteposts->text }}</p>
Lees meer...
</div>
Alternatively, you can use your code to get a collection with just one element and display data in the view using first() collection method:
<div class="panel-body">
<h3>{{ $laatsteposts->first()->title }}</h3>
<p>{{ $laatsteposts->first()->text }}</p>
Lees meer...
</div>

How to check if a variable has data in laravel blade

I wanted to check if variable is there or not in blade ..for that i have used following lines:
#if(is_null($products))
<div class="alert alert-warning">
<strong>Sorry!</strong> No Product Found.
</div>
#else
#foreach($products as $product)
//
#endforeach
#endif
The problem is when there is $products on blade I could show inside of foreach loop but when i get empty variable.I couldn't show the message No Data Found instead it shows only empty space?
is there any problem of checking variable inside of blade?
Controller code :
public function productSearch(Request $request)
{
$name = $request->name;
$products = Product::where('name' , 'like', '%'.$name.'%')->get();
return view('cart.product',compact('products'));
}
I generally use PHP count() :
#if(count($products) < 1)
<div class="alert alert-warning">
<strong>Sorry!</strong> No Product Found.
</div>
#else
#foreach($products as $product)
//
#endforeach
#endif
You may also check with PHP empty() like :
#if(!empty($products))
As you can see in the documentation :
#forelse ($users as $user)
<li>{{ $user->name }}</li>
#empty
<p>No users</p>
#endforelse
This code will allow you to parse all the users and display a list of them. if the $users variables is empty, then it will display a paragraph
so for you :
#forelse ($products as $product)
//
#empty
<div class="alert alert-warning">
<strong>Sorry!</strong> No Product Found.
</div>
#endforelse
As of Laravel 5.7, You can also do this:
#empty(!$products)
<div class="alert alert-warning">
<strong>Sorry!</strong> No Product Found.
</div>
#endempty
You can check like
#if(isset($products) && !empty($products))
<div class="alert alert-warning">
<strong>Sorry!</strong> No Product Found.
</div>
#else
#foreach($products as $product)
//
#endforeach
#endif
What about checking length?
#if(count($products)) >= 1)
#foreach($products as $product)
//
#endforeach
#else
<div class="alert alert-warning">
<strong>Sorry!</strong> No Product Found.
</div>
#endif
Because empty set (i mean a data stucture with zero elements) is not null at all.
php > $a = [];
php > echo is_null($a) ? 1 : 0;
// => 0
is_null Finds whether the given variable is NULL or not. but in our case we need to check whether the value in empty or not for this you can use either isset() or empty() function both work same in your case
while isset — Determine if a variable is set and is not NULL and
empty — Determine whether a variable is empty and also tell variable is set
#if(isset($products) && !empty($products))
#foreach($products as $product)
//
#endforeach
#else
<div class="alert alert-warning">
<strong>Sorry!</strong> No Product Found.
</div>
#endif
Do this,
Check is there any records "->count() > 0" then do foreach,
else alert.
#if ($products->count() > 0 )
#foreach($products as $product)
//enter code here
#endforeach
#else
<div class="alert alert-warning">
<strong>Sorry!</strong> No Product Found.
</div>
#endif
For me I will use logic like this
if(!$products->isEmpty()){
return view('cart.product', compact('products'));
}else{
return view('pageerror', compact('products'));
}
then you can call pageerror from your view folder to display any page that does not has data
#forelse($products as $product)
<p>do some thing</p>
#empty
<p>No Products</p>
#endforelse
Refer
Try this
#forelse($products as $product)
//
#empty
<div class="alert alert-warning">
<strong>Sorry!</strong> No Product Found.
</div>
#endforelse
I found the most effective (and by far the easiest way) of accomplishing what you're trying here to be as follows.
Assumption #1: You Know The Variable Exists Within The View.
REMEMBER: an empty array will always return false.
Therefore, there is no real need to run it through a function like empty or is null.
Comparing it to null will tell you if it exists or not.
(You could by-pass this assumption by checking to see if the variable is not equal to NULL (it's kind of bloaty if you've passed that variable through to the view, so in my opinion, I would KEEP IT SIMPLE STUPID [KISS] - if you want, you can go all fancy later when it comes to further refactoring).
ANYWAY..
I would stick to pretty similar code as you have now, maybe something like this here would be the code for your view:
#if(!$products)
<div class="alert alert-warning">
<strong>Sorry!</strong> No Product Found.
</div>
#else
#foreach($products as $product)
// {{ $product . “code goes here.” }}
#endforeach
#endif
and the code for your controller would look something like this (you almost had it, remember: "perfect practice makes perfect!" - but yeah, the controller code:
public function productSearch(Request $request)
{
// Easily obtain the name submitted by the form (I assume via the request object
// dependency injection magic
$name = $request->name;
// I would consider using the DB builder tool, as follows, as there is more docs on it
// see: https://laravel.com/docs/5.6/queries - this will return a collection (iterable)
$products = DB::table(‘products’)
->where('name' , 'like', '%'.$name.’%’)
->get();
// simply passing to the view
return view('cart.product', compact('products'));
}
You would also need to include the Product model, DB (Laravel) and (as per usual) the request object, as follows:
// Laravel Dependencies
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;
// User Created Model
use App\Product;
Hopefully, this has been helpful!

Laravel Form Text Not Being Uploaded To Database

I am trying to create a comment system for posts on a blog. I created a form for uploading a comment. Both the user_id and the post_id columns are properly populated in the table, however, the body column is empty when enter text and submit it. I defined a relationship that one Post hasMany Comments. Also, I defined that one User hasMany Comments. Here is my code:
//commentcontroller.php
public function newComment(){
$id=Auth::id();
$comment = New Comment();
$comment->user_id=$id;
$comment->post_id=Input::get('post_id');
$comment->body=Input::get('body');
post->comments()->save($comment);
}
Form:
<div class="col-md-8 col-md-offset-2">
<hr>
#foreach($posts as $post)
<h3>{{ $post->title}}</h3>
<p>by {{ $post->user->name }}</p>
<img src='{{ asset($post->image_path) }}' class="img-responsive" id="blogpic"/>
<p>{{ Str::words($post->body) }}</p>
<p>Read More...</p>
<hr>
//COMMENT AREA
{{ Form::open(array('action' => 'CommentController#newComment', 'files'=>true)) }}
{{ Form::textarea('body', null, array('class'=>'form-control')) }}
{{ Form::hidden('post_id', $post->id) }}
<br>
<br>
{{ Form::submit('Post') }}
#endforeach
</div>
I am not concerned yet about displaying comments, just uploading them to the database. The user_id and post_id upload correctly in the database, the text just doesn't save. Thanks in advance.
You may try this:
public function newComment()
{
$comment = New Comment();
$comment->user_id = Auth::user()->id;
$comment->post_id = $post_id = Input::get('post_id');
$comment->body = Input::get('body');
Post::find($post_id)->comments()->save($comment);
}
Notice Auth::user()->id is used instead of Auth::id().

Categories