Error trying to get property 'users' of non-object - laravel

I have a problem, i am doing a shift history of the user logged in the application.
#foreach($eventos as $evento)
if($evento->solicitud->users->id == (Auth::user()->id))
<div class="item-timeline">
<div class="t-meta-date">
<p class="">{{$evento->fecha}}</p>
</div>
<div class="t-dot">
</div>
<div class="t-text">
<p>{{$evento->servicio->servicio}}</p>
<p>{{$evento->personal}}</p>
</div>
</div>
#endif
#endforeach
I get all shifts with:
public function perfil (){
$eventos = Eventos::All();
$data = [
'category_name' => 'users',
'page_name' => 'profile',
'has_scrollspy' => 0,
'scrollspy_offset' => '',
];
// $pageName = 'profile';
return view('users.user_profile',compact('eventos'))->with($data);
}
Model Eventos:
public function solicitud()
{
return $this->belongsTo(Solicitudes::class);
}
Model Solicitudes:
public function evento()
{
return $this->belongsTo(Eventos::class);
}
and then filter with if condition.
But it shows me error Trying to get property 'users' of non-object
dd capture: https://i.imgur.com/WUVOaO6.png
data base: https://i.imgur.com/J5YSvxQ.png
I need to get the User_id from the solicitudes table.
The relation is: Eventos table-> solicitud_id with the ID column of the Solicitudes table.

from the code which you have provided, $evento-> solicitud-> users means I assume that you have used a nested relationship and the following things are missing
there is no 'users' relation in 'solicitudes' class
you didn't call relations in controller while fetching eventos (that is $eventos=Eventos::with('solicitud.users')->get()
correct me if my assumption is wrong

Related

Product_id not being passed to function

I have this form
<form method='POST' action='/products/{{ $product->id }}/reviews'>
{{ csrf_field() }}
<div>
<textarea name = 'review' placeholder ='Post a review'>{{ old('review') }}</textarea>
</div>
<div>
<button type ='submit'>Save</button>
</div>
</form>
The data then gets passed to this function in my controller
public function store(products $product)
{
$product->addReview(request('review'));
return back();
}
The addReview method is found in my products model
public function addReview($review)
{
return reviews::create([
'product_id' => $this->id,
'review' => $review
]);
}
I think the problem lies here
'product_id' => $this->id,
Once I fill in the form and submit, no data is added to the 'product_id' field. It's not included in any of the post data.
In your Review model:
public function product() {
return $this->belongsTo(products::class);
}
I renamed it to a product because it is one result not multiple.
Then here:
public function addReview($review)
{
return reviews::create([
'product_id' => $review->product->id,
'review' => $review
]);
}
Or even better, if you are adding a review, you should have the Product selected not the review, as you are adding a review to the product, so the method should be something like this:
public function addReview($product)
{
$review = request('review');
return $product->reviews()->create([
'review' => $review
]);
}
EDIT I see that you already have this.. so this code should work. If in the reviews table you have a product_id column, the relationship should be correct.

How do i separate two error message in laravel using one error blade file?

Say,i have two form in one page.I have included one error blade file bellow both of the form. Now when i make wrong in one form & submit it the error message is showing bellow the both form.Its normal.But my question is, how do i separate this two error message,how can i differentiate by giving them two different name?
Give this a try
return redirect()->back()->withErrors([
'form1.name' => 'name is required in Form 1',
'form1.email' => 'email is required in Form 1',
'form2.city' => 'city is required in form 2'
]);
in your view
#if($errors->any())
#foreach ($errors->get('form1.*') as $error) {
{{ $error }}
#endforeach
#endif
So you can group errors by form using array notation form.name and get all with $errors->get('form.*).
Read more about errors here: https://laravel.com/docs/5.4/validation#working-with-error-messages
If you're using Form Request Validation, you can change the errorBag property to get a unique array of errors for your view file.
In your Request file:
class MyFormRequest {
protected $errorBag = 'foobar';
public function rules() { // ... }
}
In your controller:
public function store(MyFormRequest $request) {
// Store entry.
}
Then in your view file:
#if ($errors->foobar->isNotEmpty())
// Work with the errors
#endif
You can use the named error bags.
$validator = Validator::make($request->all(), [
'field1' => 'required',
'field2' => 'required|digits:1',
]);
if ($validator->fails()) {
return back()
->withErrors($validator, 'form1error')
->withInput();
}
To print the error in blade file use-
#if(count($errors->form1error)>0)
<ul>
#foreach($errors->form1error->all() as $error)
<li>{{$error}}</li>
#endforeach
</ul>
#endif

Missing required parameters for in a Update Form Laravel 5.2

I've been working on a webapp recently in laravel and i wanted to have a eddit function within tthe application. but im getting this error Missing required parameters for [Route: producten.update] [URI: producten/{producten}], and i dont know what i've done wrong.
This is the Routes im using:
Route::resource('producten', 'ProductenController', ['only' => ['index', 'store', 'update', 'delete', 'edit', 'destroy', 'create']]);
This is the controller function im using for showing the edit page and updating.
The Edit function
public function edit(Request $request, Product $product)
{
// $product = Product::FindorFail($id);
// Product is a table with all products, with sellprice and buy price
// fabriek = table that has a foreign key attached to the product table
return view('producten.edit', [
'model' => $product,
'fabrieks' => Fabriek::lists('Id')
]);
}
The Update Function:
public function update(Request $request, Product $product)
{
$product->update($request->all());
return redirect(Route('producten.index'));
}
and this is the view i use for it.
{{Form::model($model, ['method' => 'PATCH', 'action' => 'ProductenController#update', $model ]) }}
{{ Form::label('naam:')}}
{{ Form::text('naam') }} <br>
{{ Form::label('inkoopPrijs:')}}
{{ Form::text('inkoopPrijs') }} <br>
{{ Form::label('verkoopPrijs:') }}
{{ Form::text('verkoopPrijs') }} <br>
{{Form::label('Fabrieken', 'Fabrieken Id:') }}
{{ Form::select('Fabrieken_Id', $fabrieks)}} <br>
{{ Form::submit('edit')}}
{{ Form::close() }}
if there is anything else that i need to add to the question just let me know and i'll add it
Missing thing is the id you are not getting id there in your edit function
your edit function should as i am assuming that you are just showing the form from this method where user can edit
public function edit($id)
{
$product = Product::FindorFail($id);
//Product is a table with all products, with sellprice and buy price
//fabriek = table that has a foreign key attached to the product table
return view('producten.edit', [
'model' => $product,
'fabrieks' => Fabriek::lists('Id')
]);
}
your update method should seem like this
public function update(Request $request, $id)
{
$product->update($request->all());
return redirect(Route('producten.index'));
}
your routes should like this no need for only
Route::resource('/producten', 'productionController');
edit route will be as
<a href="{{ route('production.edit', $model->id) }}">
Try this hope it will help

Is there any way to return the value of request field from request class instead of checking validations in laravel 5

I am using laravel 5. If the validation of any field fails, I want to get the value of a particular field from the request class which I have created and it can be displayed in the view class like displaying error messages. Does anyone knows how to code for that?
above photo, for the id part how to make the syntax to return the value?
Controller :
public function edit(Requests\EventRequest1 $request){
$date=$_POST['eventDate'];
$title=$_POST['title'];
$id=$_POST['id'];
$events=EventCal::findOrFail($id);
$events->update($request->all());
DB::table('event_cals')
->where('id',$id)
->update(['title' => $title,'eventDate' => $date]);
return redirect('/dcalendar');
}
Model :
class EventCal extends Model {
protected $fillable = [
'title',
'eventDate',
];
}
View :
#if($errors->has('title') )
<td><ul class="alert alert-danger" style="width: 250px;height: 40px"> {{$id}}</ul></td>
#endif
#if($errors->has('eventDate'))
<td><ul class="alert alert-danger" style="width: 250px;height: 40px"> {{$errors->first('eventDate')}}</ul></td>
#endif
EventRequest1(Request Class) :
public function rules()
{
return [
'title' => 'required',
'eventDate' => 'required|date|after:yesterday',
'id' => Request::get('id')
];
}
public function messages(){
return [
'title.required' => 'Title is required.',
'eventDate.after' => 'Event Date is passed.',
'eventDate.required' => 'Event Date is required.',
];
}
I want to return the id for view page. In the view page {{$id}} should print the id value.Is there any way? I'm not sure how to return the value of id from request. That's the only thing I needed to know.
Inside of your request class you must override the response() function:
public function response(array $errors)
{
return $this->redirector->back()
->withInput($this->except($this->dontFlash))
->withErrors($errors)
->with('id', $this->get('id'));
}

search form using laravel shows 'Call to a member function getNumCommentsStr() on a non-object'

i have made a search bar using laravel, but it did not succeed. it shows the error as said below. And it seems that something wrong with my post object. But i do not know where.
source code as follows, thanks for helping.
//the searchController for seach code
public function search(){
$keyword = Input::get('keyword');
if(empty($keyword)){
return Redirect::route('/');
//->with('message',array('type' => 'alert', 'content' => '不能为空'))
}
$posts = Post::where('content', 'like', '%'.$keyword.'%')->orderBy('created_at', 'desc')->paginate(10);
$tags = Tag::where('count','>','0')->orderBy('count','desc')->orderBy('updated_at', 'desc')->take(20)->get();
return Redirect::route('searchResults')->with('posts', $posts->toArray())->with('tags',$tags);
}
public function searchResults(){
return View::make('frontend.search.search',['posts' => Session::get('posts'),'tags' => Session::get('tags')]);
}
//search bar route
Route::get('/searchResults', array(
'uses' => 'SearchController#searchResults',
'as' => 'searchResults'
));
Route::post('/search', array(
'before' => 'csrf',
'uses' => 'SearchController#search',
'as' => 'search'
));
//search from
{{ Form::open(array('url'=>'/search','method' => 'post','class'=>''))}}
{{ Form::token()}}
<label for="docSearch">
<i class="fa fa-search"></i>
</label>
<div class="searchInput">
{{Form::text('keyword', '', array('class'=>'docsSearch', 'placeholder'=>'搜索论坛动态...'))}}
{{ Form::submit('提交',array('class'=>''))}}
{{Form::close()}}
//now i just wanna to get it like this:
#if(!$posts)
{{'<section class="oneQuestion">sorry,no content...</section>'}}
#else
#foreach($posts as $post)
<section class="oneQuestion">
<div class="askResult">
<!-- <i class="fa fa-question notSolved"></i>
<i class="fa fa-check solved" style="display:none;"></i> -->
#if($post->getNumCommentsStr() == 0)
<a href="{{URL::route('viewPost', array('id' => $post->id))}}#reviews" class="notSolved"><span class="post_comment_Num">{{$post->getNumCommentsStr()}}</span>
<span> 回答</span>
</a>
#else
<a href="{{URL::route('viewPost', array('id' => $post->id))}}#reviews" class="solved"><span class="post_comment_Num">{{$post->getNumCommentsStr()}}</span>
<span> 回答</span>
</a>
#endif
</div><!--
--><div class="titlePart">
<span>
{{$post->user->username}}
{{$post->created_at->diffForHumans()}}
</span>
<a href="{{ URL::route('viewPost', $post->id)}}">
{{-- {{ substr($post->content,0,200) }}... --}}
{{$post->title}}
</a>
<div class="tagWrapper">
#foreach ($post->tags as $tag)
<span class="askTag" title="">{{$tag->name}} </span>
#endforeach
</div>
</div>
</section>
#endforeach
#endif
<div class="forumLink">
{{$posts->links()}}
</div>
//it showed me an error:
**Call to a member function getNumCommentsStr() on a non-object**
and my getNumCommentsStr like:
public function getNumCommentsStr()
{
$num = $this->reviews()->count();
// if($num == 1){
// return "1";
// }
return $num;
}
code seems a lot but i wanna to make it clear so you can find any errors. Thanks again.
Edit 2
Thanks for NightMICU's suggest and I change
Redirect::route('searchResults')->with('posts', $posts->toArray())->with('tags',$tags);
to the following:
Redirect::route('searchResults')->with('posts')->with('tags',$tags);
THE result is without any alert any more, it just shows: sorry, no content...
And did not show any search result, any problem? Thanks
EDIT TWO
//delete the searchResult method, all in one search method so that i can return the view in right in the search method.
public function search(){
$keyword = Input::get('keyword');
if(empty($keyword)){
return Redirect::route('developer');
//->with('message',array('type' => 'alert', 'content' => '不能为空'))
}
$posts = Post::where('content', 'like', '%'.$keyword.'%')->orderBy('created_at', 'desc')->paginate(10);
$tags = Tag::where('count','>','0')->orderBy('count','desc')->orderBy('updated_at', 'desc')->take(20)->get();
return View::make('frontend.search.search',['posts' => $posts,'tags' => $tags]);
}
EDIT 3
there are two questions exsiting here.
ONE is that when i change to that ,it can output the result but all the result the database has. Not the keyword results.
Two is that when there are extra page, once i open the link http://localhost/html5lav/public/search?page=2, it just show an error:
No query results for model [Post].
The initial issue most likely has to do with the unusual way you are displaying the search results; by passing the Eloquent collections via session to another method, only to display the View. You were also converting the Post Eloquent collection to a regular array with ->toArray(), pagination requires a collection rather than an array.
The solution for that part:
public function search(){
$keyword = Input::get('keyword');
if(empty($keyword)){
return Redirect::route('/');
//->with('message',array('type' => 'alert', 'content' => '不能为空'))
}
$posts = Post::where('content', 'like', '%'.$keyword.'%')->orderBy('created_at', 'desc')->paginate(10);
$tags = Tag::where('count','>','0')->orderBy('count','desc')->orderBy('updated_at', 'desc')->take(20)->get();
return View::make('frontend.search.search')->with('posts', $posts)->with('tags', $tags);
}
After taking care of the initial issue, you reported that the pagination links are not working as expected - you click on Page 2 and do not have any Post results. If the route for the page where the user inputs a search term is also /search, there is a conflict. Instead, change the route that the search form posts to, perhaps /searchResults (which then loads the results using the search method). You may also want to consider using a GET rather than POST request, allowing users to bookmark their search results or share a link.
Regarding the issue of displaying all of the entries from the posts table, you need to review MySQL raw queries in Laravel. Swing by the documentation and look them up.

Resources