how to get current user data only in laravel - laravel

i am working on laravel and want to get only login user data but when i change code it give error in my view
public function index(){
$users = User::all();//Auth::user();//
//dd($users);
return view ('profile.index',compact('users'));
}
this is the code that give output and show all user data
when i change the code the error it give me no output
this is image
this is view i am using
<div class="container">
<div class="row">
<div class="container" >
<h2>Basic Details<h2>
<form>
#foreach($users as $user)
<image src=" {{$user['image']}}" class="img-circle">
<div class="form-group col-lg-3">
<span class="input-group-addon"><i class="glyphicon glyphicon-user"></i></span>
<h4>Name:</h4>
<input type="text" value="{{$user['name']}}" class="form-control" id="text" name="text"
readonly="true">
</div>
<div class="form-group col-lg-3">
<h4 for="Email">Email:</h4>
<input type="email" value="{{$user['email']}}" class="form-control" id="email" name="email"
readonly="true">
</div>
#endforeach
</form>

There are several issues with your code and, as #pseudoanime commented, you can't directly interchange the single user case vs. all users because of the returned data types. However, if you REALLY want to do this, you could change things up so that both situations return a collection, as shown below:
public function index(){
$users = collect(Auth::user());
return view ('profile.index',compact('users'));
}
I'm not sure why you would want to do this rather than simply returning a different view, but I'll leave that up to you. Please note that I would suggest re-evaluating your problem and taking a different approach, as it makes no sense to loop through a collection you will know only has a single member.
Additionally, you should note that you are not accessing the user model properly. You are using array syntax in the view (for example, $user['email']) when you should be using object syntax ($user->email). There are other issues with the code that may still cause issues, but this is the most obvious problem I see.

Related

Filtering page results Laravel many to many, many ids to find one entry

I have a page that displays all the records from the 'Receita' table like this:
public function mostrarTodos()
{
$receitas = Receita::all()->toArray();
$ingredientes = Ingrediente::all()->toArray();
return view('home', compact('receitas', 'ingredientes'));
}
on the top of the page there is a form with many checkboxes that will filter the results displayed on the front page:
<div class="col-span-2 border p-2">
<form action="filtro" class="grid grid-cols-4" method="GET">
#foreach ($ingredientes as $ingrediente)
<div>
<label for="{{ $ingrediente['id'] }}">{{ $ingrediente['nome'] }}</label>
<input type="checkbox" name="ingrediente[]" id="{{ $ingrediente['id'] }}" value="{{ $ingrediente['id'] }}">
</div>
#endforeach
<button class="rounded p-2 bg-purple-200 col-span-4" type="submit">Filtrar</button>
</form>
</div>
The question is, how can I use that form to filter the results that are displayed on the page since each entry can have one or many of those checkboxes? In other words, show me only the entries that have the checked checkboxes.

handling empty table when displaying view of data

I have a laravel project. it has a table that I want to fill with data from a form. Currently it populates the form with any data that may exist in the table.
I'm using #foreach to iterate through the data object. This works fine when there is data in the table, but when there's no data obviously the #foreach data object will be empty.. How do folk handle this so that the form still shows with default values?
#foreach($pricing as $price)
<div class="form-row align-items-center">
<div class="col-12">
<p><strong>Rate</strong></p>
</div>
<div class="col-12">
<div class="row">
<div class="col-md-2">
<label for="hirePrice" class="">Hire Price</label>
</div>
<div class="col-md-4">
<input type="text" name="hire" class="form-control" placeholder="1200" aria-label="hireprice" id="hirePrice" value="{{ $price->hire}}">
Currently, if I empty the table, the page just displays the header and none of the html above, including the form fields.
edit: The table will always only have 1 ROW !! not sure if this makes it any easier.
You can use
#isset($pricing)
#foreach($pricing as $price)
<div class="form-row align-items-center">
<div class="col-12">
<p><strong>Rate</strong></p>
.................................
//your code
#endforeach
#endisset
Or, You can use if else condition like this:
#if($pricing != Null)
#foreach($pricing as $price)
<div class="form-row align-items-center">
<div class="col-12">
<p><strong>Rate</strong></p>
.....................
//code
#endforeach
#else
<div>No data</div>
#endif
Though i can not get your actual scenario,i can give some advice.
You can add one line condition inside of input tag like this:
HTML:
<input type="text" #if($data->variable) value="{{ $data->variable }}" #else value=" " #endif >
Otherwise, You can put same code within foreach loop into else condition. So, when data exists in the table, it shows the data in the form otherwise same form with empty value will appear.

The PUT method is not supported for this route. Supported methods: GET, HEAD

I'm trying to learn Laravel, and I'm following a series of tutorials called laracast. I'm at episode 24, "Forms that submit PUT requests. The short story is that the markup uses a hidden value to set the method to PUT, although the forms method is set to POST. Still, when I do this, I get the error message from the title:
Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException
The PUT method is not supported for this route. Supported methods: GET, HEAD.
From the tutorials, I'd expect POST to also be a supported method. However, when I try to fix this, all resources I can find simply tells me what I already know. PUT is not supported, but I can fake it/override it, and then they refer to what I have already done... Are there any other reasons why I might get this error message?
HTML Form:
<form method="POST" action="/competition-categories">
#csrf
#method('PUT')
<div class="form-group row">
<label for="competition-category-name-input" class="col-4 col-form-label">Name</label>
<div class="col-8">
<input id="competition-category-name-input" name="competition-category-name-input" type="text" class="form-control" required="required" value="{{ $competitionCategory->name }}">
</div>
</div>
<div class="form-group row">
<label for="competition-category-abbreviation-input" class="col-4 col-form-label">Abbreviation</label>
<div class="col-8">
<input id="competition-category-abbreviation-input" name="competition-category-abbreviation-input" type="text" class="form-control" required="required" value="{{ $competitionCategory->abbreviation }}">
</div>
</div>
<div class="form-group row">
<div class="offset-4 col-8">
<button name="submit" type="submit" class="btn btn-primary">Submit</button>
</div>
</div>
</form>
web.php snippet:
//Competition Categories
Route::get('/competition-categories', 'CompetitionCategoryController#index');
Route::get('/competition-categories/create', 'CompetitionCategoryController#create');
Route::get('/competition-categories/{competitionCategory}', 'CompetitionCategoryController#show');
Route::get('/competition-categories/{competitionCategory}/edit', 'CompetitionCategoryController#edit');
Route::post('/competition-categories/{competitionCategory}', 'CompetitionCategoryController#store');
Route::put('/competition-categories/{competitionCategory}', 'CompetitionCategoryController#udpate');
Route::delete('/competition-categories/{competitionCategory}', 'CompetitionCategoryController#destroy');
Snippet from the controller:
public function update(Request $request, CompetitionCategory $competitionCategory)
{
$competitionCategory->update($this->validateCompetitionCategory());
return redirect()->route('competition-categories' , [$competitionCategory]);
}
You're forgetting the id in form, this should fix your problem:
action="/competition-categories/{{$competitionCategory->id}}"
The most common thing that this happens is your cache. When you add a new route or change something in your routes, always run after php artisan optimize to refresh you cache.
I recommend using the named-routes for more informations and messages see =>
https://laravel.com/docs/7.x/routing#named-routes

Laravel Request hasFile returns false despite file actually attached

I'm using a nice HTML template which features a preview of the picture selected by my HTML file input. This is the HTML:
<div class="fileinput fileinput-new" data-provides="fileinput">
<div class="fileinput-new img-thumbnail text-center">
<img src="#" data-src="holder.js/100%x100%" alt="not found"></div>
<div class="fileinput-preview fileinput-exists img-thumbnail"></div>
<div class="m-t-20 text-center">
<span class="btn btn-primary btn-file">
<span class="fileinput-new">choose</span>
<span class="fileinput-exists">change</span>
<input type="file" id="pb" name="pb" accept="image/*" class="form-control"></span>
<a href="#" class="btn btn-warning fileinput-exists"
data-dismiss="fileinput">Entfernen</a>
</div>
</div>
I chose pb as name for the actual file input. This is the controller function:
public function addUser(Request $request) {...}
Everything fine so far, echo $request->pb also echoes the filename as desired. HOWEVER, Laravel doesn't recognise this as a file apparently:
$request->file('pb')
returns null (yes, I have tried to display all files of $request, also $request->hasFile() returns false/null). I wonder why? Unfortunately, I cannot directly access $_FILE which would make things easier despite not being in the right order with Laravel in general.
Make sure your form has:
enctype="multipart/form-data"

Populating a DropDown Menu From a MySQL Database Using Hibernate in Spring MVC

I've looked into many sources to find the exact answer that I need, but unfortunately, I couldn't understand or they never hit the exact spot that I need.
Basicly, I am developing a spring-mvc web application and I am going to allow user to add post to the website. While adding this post, he/she is going to identify some features of the post, and one of the feature is category. Everything is working fine but category. I've tried to implement this category field with a dropdown menu, but I get nothing populated in dropdown when I run the project.
Here is my jsp page:
<%#taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%#include file="/WEB-INF/views/template/header.jsp" %>
<div id="page">
<div id="main">
<div class="row">
<div class="three columns"></div>
<div class="six columns">
<form:form action="${pageContext.request.contextPath}/addPost" method="post" commandName="post"
enctype="multipart/form-data">
<div class="form-group">
<label>Kategori</label>
<form:select path="category" id="category">
<form:option value="NONE" label="--- Seçiniz ---"/>
<form:options items="${category}"></form:options>
</form:select>
<!--select name="category">
<option name="category_id" value="0">Seçiniz</option>
</select-->
</div>
<div class="form-group">
<label>İlan Başlığı</label> <form:errors path="postTitle" cssStyle="color: #ff0000"/>
<form:input path="postTitle" id="title" class="form-Control"/>
</div>
<div class="form-group">
<label>İlan Açıklaması</label>
<form:input path="description" id="description" class="form-Control"/>
</div>
<!--div class="form-group">
<label>Etiketler</label>
<input type="text" class="asdasd" name="title" placeholder="İlanınız ile ilgili etiketler" required>
</div-->
<div class="form-control">
<label>Fiyat</label> <form:errors path="price" cssStyle="color: #ff0000"/>
<form:input path="price" id="price" class="form-Control"/>
</div>
<div class="form-group">
<label>Lokasyon</label>
<form:input path="postAddress" id="address" class="form-Control"/>
</div>
<div class="form-group">
<label class="control-label" for="postImage">Fotoğraf Yükle</label>
<form:input name="file" path="postImage" id="postImage" type="file" class="form:input-large"/>
</div>
<div class="form-group">
<button type="submit" value="submit" class="btn btn-send-message pull-right">İLAN OLUŞTUR</button>
</div>
</form:form>
</div>
<div class="three columns"></div>
</div>
</div>
And here is my Controller function:
#RequestMapping(value= "/addPost", method = RequestMethod.GET)
public String addPost(Model model) {
Post post = new Post();
post.setActive(true);
List<Category> category = categoryService.getAllCategories();
model.addAttribute("category", category);
model.addAttribute("post", post);
return "addPost";
}
What I want to do here is, I want to get the necessary data from the database table that I've created by the help of Hibernate, and send it to dropdown menu.
Many examples here in SO and some other blogs shows that feature like filling the dropdown menu from the controller by manually. This is the one that I don't want. So far, the closest answer that I can find is this. But since I am new in Spring, I couldn't get it.
If anyone can even point me in the right direction on how to set this up that would be a great help.
Thanks in advance.
From what I can see, it looks like you have two model attributes, the post and list of categories. The JSP has a form, this form is bound to the post bean, and you want to have the list of categories appear in a dropdown on the form.
As far as I know, and google this is not possible, as long as you have two separate model attributes. The problem is that <form:select path="category"..>
is scoped by your commandName bean, so it is looking for category as a property on post, and not in the view model.
I think you need to make a new class FormBean which has two properties, category and post, and then bind that to the from using commandName="formBean", and then use path="post.postTitle" for a single property on the post object, and <form:select path="category"...> for the dropdown.
Hope this helps

Resources