Invalid argument supplied for foreach() - laravel 5.6 - php

newbie here practicing laravel, im making an inventory for movies using laravel 5.6.. where I can do basic CRUD functionalities.
In here, Im sorting movies by genre. however I came up with this error Invalid argument supplied for foreach();
here is my Route: web.php
Route::resource('movies', 'MoviesController');
Route::get('movies/year/{movie}', 'MoviesController#released');
Route::get('movies/genre/{genre}', 'MoviesController#getgenre');
here is my controller: MoviesController.php
public function getgenre($genre){
$movies = Movie::where('genre', $genre)->whereIn('status', [1])->orderBy('title', 'asc')->get();
return view('genre', compact('movies'));
}
here is my view: genre.blade.php
#extends('layouts.app')
#section('content')
<div class="row">
<div class="col-md-10">
#if($movies->count() < 1)
<h1 style="text-align: center">No Movie Found</h1>
#else
#foreach($movies as $movie)
<div class="card" style="margin-bottom: 10px;">
<div class="card-body">
<div class="card-title">
{{ ucwords($movie->title) }}
</div>
<div class="card-text">
{{ ucfirst($movie->genre) }} | {{$movie->released}} |
#if($movie->seen == 1)
Seen: Yes
#else
Seen: No
#endif
<div style="margin-top: 5px">
{{ Form::open(['route' => ['movies.edit', $movie->id], 'class' => 'formupdate', 'method' => 'GET']) }}
{{ Form::submit('Update', ['class' => 'btn btn-primary col-md-2']) }}
{{ Form::close() }}
</div>
<div style="margin-top: 5px">
{{ Form::open(['route' => ['movies.destroy', $movie->id], 'class' => 'formdelete', 'method' => 'DELETE']) }}
{{ Form::hidden('hidden', 'hidden') }}
{{ Form::submit('Delete', ['class' => 'btn btn-danger col-md-2']) }}
{{ Form::close() }}
</div>
</div>
</div>
</div>
#endforeach
<div class="pagination" style="margin-top: 10px; text-align: center;">
{{ $movie->links() }}
</div>
#endif
</div>
<div class="col-md-2">
</div>
</div>
#stop
I tested it dd(): and it has results:
tried testing it using dd()
here is the error:
here is the error
thanks,

you have two issues:
1- Update this whereIn expects array and you use pagination in view and you do not return the data as pagination
$movies = Movie::where('genre', $genre)->whereIn('status', [1])>orderBy('title', 'asc')->paginate(10);
2- in the view you written $movie->links(); update it to
$movies->links();

Update this line, whereIn expects array
$movies = Movie::where('genre', $genre)->whereIn('status', [1])->orderBy('title', 'asc')->get();

Related

laravel error: Trying to get property of non-object (\show.blade.php)

I'm making a discussion forum app with laravel and i face this error:
Trying to get property of non-object (View:
C:\xampp\htdocs\fourm\resources\views\discussion\show.blade.php) at
PhpEngine->evaluatePath('C:\xampp\htdocs\fourm\storage\framework\views/a2f2c494b8859e0552bfa22c40ceb4065b2efbe5.php',
array('__env' => object(Factory), 'app' => object(Application),
'channels' => object(Collection), 'errors' => object(ViewErrorBag),
'd' => null, 'best_answer' => null))in CompilerEngine.php (line 59)
This is my controller code:
public function show($slug)
{
$discussion = Discussion::where('slug', $slug)->first();
$best_answer = Reply::where('best_answer', 1)->first();
return view('discussion.show')->with('d', $discussion)->with('best_answer', $best_answer);
}
This is my view code:
#extends('layouts.app')
#section('content')
<div class="panel panel-default">
<div class="panel-heading">
<img src="{{ $d->user->avatar }}" alt="" width="40px" height="40px">
<span>{{ $d->user->name }}, <b>( {{ $d->user->points }} )</b></span>
#if($d->is_being_watch_by_user())
unwatch
#else
watch
#endif
</div>
<div class="panel-body">
<h4 class="text-center">
<b>{{ $d->title }}</b>
</h4>
<hr>
<p class="text-center">
{{ $d->content }}
</p>
<hr>
#if($best_answer)
<div class="text-center" style="padding: 40px;">
<h3 class="text-center">BEST ANSWER</h3>
<div class="panel panel-success">
<div class="panel-heading">
<img src="{{ $best_answer->user->avatar }}" alt="" width="40px" height="40px">
<span>{{ $best_answer->user->name }} <b>( {{ $best_answer->user->points }} )</b></span>
</div>
<div class="panel-body">
{{ $best_answer->content }}
</div>
</div>
</div>
#endif
</div>
<div class="panel-footer">
<span>
{{ $d->replies->count() }} Replies
</span>
{{ $d->channel->title }}
</div>
</div>
#foreach($d->replies as $r)
<div class="panel panel-default">
<div class="panel-heading">
<img src="{{ $r->user->avatar }}" alt="" width="40px" height="40px">
<span>{{ $r->user->name }} <b>( {{ $r->user->points }} )</b></span>
#if(!$best_answer)
#if(Auth::id() == $d->user->id)
Mark as best answer
#endif
#endif
</div>
<div class="panel-body">
<p class="text-center">
{{ $r->content }}
</p>
</div>
<div class="panel-footer">
#if($r->is_liked_by_user())
Unlike <span class="badge">{{ $r->likes->count() }}</span>
#else
Like <span class="badge">{{ $r->likes->count() }}</span>
#endif
</div>
</div>
#endforeach
<div class="panel panel-default">
<div class="panel-body">
#if(Auth::check())
<form action="{{ route('discussion.reply', ['id' => $d->id ]) }}" method="post">
{{ csrf_field() }}
<div class="form-group">
<label for="reply">Leave a reply...</label>
<textarea name="reply" id="reply" cols="30" rows="10" class="form-control"></textarea>
</div>
<div class="form-group">
<button class="btn pull-right">Leave a reply</button>
</div>
</form>
#else
<div class="text-center">
<h2>Sign in to leave a reply</h2>
</div>
#endif
</div>
</div>
#endsection
You're getting this error because both queries return null:
$discussion = Discussion::where('slug', $slug)->first();
$best_answer = Reply::where('best_answer', 1)->first();
So, you need to check for empty result manually with is_null() or empty() or just:
if (!$discussion) {
abort(404);
}
Or use findOrFail() to throw an exception if no record found.
You are trying to access property with null objects, and that's why you got the error like "Trying to get property of null object".
As per our discussion in comments, you are getting null values in both queries and that's the reason for error!
Try to add if..else condition like below:
if (!$d) {
session()->flash('error', 'Discussion not found.');
return redirect()->back();
} else {
return view('discussion.show')->with('d', $discussion)->with('best_answer', $best_answer);
}
Hope this helps you!
Make sure you're not returning an object and accessing it as an array. It can be a common error.
I solved mine by adding: <?php error_reporting(0);?> on page where i got error. :D

Missing required parameters for [Route: ticket.edit] [URI: ticket_ads/edit/{ad}]

I am trying to edit a record in a table. I have created a route and the form, but I can't get past this error. I have figured out the problem but I can't find a fix. Am I correct in thinking that the edit.blade.php file needs the $ad->id passing?
The $ad->id is an ID of a specific add in a List View. The list view has all the tickets displayed from a table, and the below link is meant to edit that one item.
The edit route is accessed using following code:
Edit
I have one route that is supposed to open up the edit view form:
Route::get('/ticket_ads/edit/{ad}', 'TicketAdsController#editTicketAdForm')->name('ticket.edit');
The above route points to this in the controller:
public function editTicketAdForm($id)
{
//$ad = DB::table('ticket_ads')->where('id', $id)->value('id');
return view('Ads.edit')->with('id', $id);
}
This is the view called by the above function:
#extends('Shared.Layouts.MasterWithoutMenus')
#section('title')
Edit a ticket ad
#stop
#section('content')
<div class="container">
<div class="row">
<div class="col-md-8 col-md-offset-2">
<div class="panel panel-default">
<div class="panel-heading"><h2>Edit your ticket ad</h2></div> <br/>
#if ($errors->any())
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
{{ Form::open(array('route' => 'ticket.edit', $id = 'id')) }}
<div class="form-group">
{{ Form::label('title', 'Title') }}
{{ Form::text('title', Input::old('title'), array('class' => 'form-control')) }}
</div>
<div class="form-group">
{{ Form::label('comment', 'Comment') }}
{{ Form::text('comment', Input::old('comment'), array('class' => 'form-control')) }}
</div>
{{ Form::submit('Submit', array('class' => 'btn btn-primary')) }}
{{ Form::close() }}
</div>
</div>
</div>
</div>
#endsection
This is the line that throws the error
{{ Form::open(array('route' => 'ticket.edit', $id = 'id')) }}
The ID displays normally in the URL as ticket_ads/edit/7 for example.
How do I get past this?
Change this line:
{{ Form::open(array('route' => 'ticket.edit', $id = 'id')) }}
to this:
{{Form::open(array('route' => array('ticket.edit', $id)))}}
This
{{ Form::open(array('route' => 'ticket.edit', $id = 'id')) }}
is wrong. Correct syntax is:
{{ Form::open(['route' => ['ticket.edit', $id]]) }}
also you should safely ditch using array() in favor of [] syntax as Laravel requires PHP 5.4+ anyway (unless you are using ancient version of Laravel, like v4?)
The correct syntax for calling route is.
{{ route('/cardetails', ['121','cars'] ) }}
In URL it will be like this below line.
127.0.0.1:8000/cardetails/121/cars

MethodNotAllowedHttpException

I'm trying to update the fields in the database, but I couldn't
here is my routes :
Route::get('orders', [
'uses' => 'OrderController#postOrder',
'as' => 'order.show'
]);
here the controller:
public function postOrder()
{
$this->orderForm->validate(Input::all());
$order = $this->orders->getNew([
'link' => Input::post('link'),
'size' => Input::post('size'),
'color' => Input::post('color')
]);
$this->orders->save($order);
return Redirect::back()->withMessage('Order has been updated');
}
here is the blade:
{{ Form::open() }}
<div class="box-body">
<div class="row">
<div class="col-lg-6">
<div class="form-group">
{{ Form::label('title', 'Product:') }}
{{ Form::text('title', $order->title, ['class' => 'form-control', ]) }}
</div>
</div>
<div class="col-lg-6">
<div class="form-group">
{{ Form::label('link', 'Link:') }}
{{ Form::text('link', $order->link, ['class' => 'form-control']) }}
</div>
</div>
</div>
<div class="row">
<div class="col-lg-6">
<div class="form-group">
{{ Form::label('size', 'Size:') }}
{{ Form::text('size', $order->size, ['class' => 'form-control']) }}
</div>
</div>
<div class="col-lg-6">
</div>
</div>
<div class="box-footer">
{{ Form::submit('Save', ['class' => 'btn btn-primary']) }}
</div>
{{ Form::close() }}
so each time I try to update the order I got error "MethodNotAllowedHttpException ", I tried a lot of methods but I'm lost. I'm still beginner in php and this problem drive me crazy, so I'll be glad if you can help guys.
thanks
*** I've updated the code
So you're posting to the route, /orders. Therefor you need a HTTP POST request. You're now assigning a GET request to the /orders route.
You need to change your code to:
Route::post('orders', [
'uses' => 'OrderController#postOrder',
'as' => 'order.show'
]);
Also you need to add a CSRF Token, this can be done through adding {!! csrf_field() !!} in your blade (inside your Form open and close).
{{ Form::open() }}
{!! csrf_field() !!}
<div class="box-body">
<div class="row">
<div class="col-lg-6">
<div class="form-group">
{{ Form::label('title', 'Product:') }}
{{ Form::text('title', $order->title, ['class' => 'form-control', ]) }}
</div>
</div>
<div class="col-lg-6">
<div class="form-group">
{{ Form::label('link', 'Link:') }}
{{ Form::text('link', $order->link, ['class' => 'form-control']) }}
</div>
</div>
</div>
<div class="row">
<div class="col-lg-6">
<div class="form-group">
{{ Form::label('size', 'Size:') }}
{{ Form::text('size', $order->size, ['class' => 'form-control']) }}
</div>
</div>
<div class="col-lg-6">
</div>
</div>
<div class="box-footer">
{{ Form::submit('Save', ['class' => 'btn btn-primary']) }}
</div>
{{ Form::close() }}
Hope this works!
You must specify the method in the Form::open method.
{{ Form::open(array('method' => 'post')) }}
Just added this in the repository:
public function updateOrder($id, array $data)
{
$orders = $this->getById($id);
if (!empty($data['title'])) {
$orders->title = $data['title'];
}
if (!empty($data['link'])) {
$orders->link = $data['link'];
}
(AND SO ON)
$orders->save();
and in the controller:
public function postOrder($id)
{
$this->orders->updateOrder($id, Input::all());
return Redirect::back()->withMessage('Updated');
}
and that's it

How to update data from a form in Laravel 5.2

Hi I am having problems on editing and updating data from my form. I already tried to get the data from the form but when I try to edit and update it, it will make another data. Thanks!
Controller:
public function registerPackage()
{
$activity_packages = Chap_activity_packages::all();
return view('admin.registerPackage',compact('activity_packages'));
}
public function savePackage(Request $request)
{
$this->validate($request,[
'chap_activity_packages_name'=>'required|Min:4|unique:chap_activity_packa ges',
'chap_activity_packages_price'=>'required|numeric'
]);
$values = $request->all();
Chap_activity_packages::create($values);
return view('admin.registerPackage');
}
public function editPackage($id)
{
$act = Chap_activity_packages::find($id);
$activity_packages=Chap_activity_packages::all();
return view('admin.registerPackage',compact('act','activity_packages'));
}
<h4 class="page-header">Packages Management</h4>
<div class="row">
<div class="col-xs-5">
<div class="panel panel-success">
<div class="panel-heading">
<h3 class="panel-title">Register New Package</h3>
#if($errors->any())
<div class="alert alert-danger">
#foreach($errors->all() as $error)
<div>{{ $error }}</div>
#endforeach
</div>
#endif
#if(Session::has('flash_message'))
<div class="alert alert-success">
{{ Session::get('flash_message') }}
</div>
#endif
</div>
<div class="panel-body">
{{ Form::open(array('url' => 'admin/registerPackage')) }}
<div class="form-group">
{{ Form::label('chap_name','Package Name:') }}
{{ Form::text('chap_activity_packages_name',isset($act)? $act->chap_activity_packages_name:null,['class' => 'form-control', 'placeholder' => 'Enter package name']) }}
</div>
<div class="form-group">
{{ Form::label('chap_price','Package Price:') }}
{{ Form::text('chap_activity_packages_price',isset($act)? $act->chap_activity_packages_price:null,['class' => 'form-control', 'placeholder' => 'Enter package price']) }}
</div>
<div class="form-group">
{{ Form::submit('Register Package',['class' => 'btn btn-success btn-block']) }}
</div>
{{ Form::close() }}
</div>
</div>
</div>
</div>
#stop
#section('content2')
<div class="panel panel-success">
<div class="panel-heading">
<h4 class="panel-title">Available Packages</h4>
</div>
<div class="panel-body">
<table class="table table-striped table-hover">
<thead>
<tr>
<th>Package Name</th>
<th>Package Price</th>
<th>Action</th>
</tr>
</thead>
<tbody>
#foreach($activity_packages as $activity_package)
<tr>
<td> {{ $activity_package->chap_activity_packages_name }} </td>
<td> {{ $activity_package->chap_activity_packages_price }} </td>
<td>
</span>
<span class="glyphicon glyphicon-trash"></span>
</td>
</tr>
#endforeach
</tbody>
</table>
</div>
</div>
#stop
These are my codes for both the controller and the view. please let me know if what is wrong. thanks a lot!
I don't see the method for updating data in you controller, it should be look like below:
// YourController.php, use implicit route model binding
public function update(App\Chap_activity_packages $model)
{
// do your validation here
// $this->validate(blahblahblah...)
// ...
$model->update(request()->all());
return redirect()->back()->with('msg', 'Update success.');
}
// routes.php
Route::put('your/route/to/model/{model}', 'YourController#update');
// yourTemplate.blade.php
// remember to use method spoofing
{{ Form::open(['url' => 'your/route/to/model/' . $model->id, 'method' => 'put']) }}
Information about route model binding can be found here. Good luck!

Simple variable passing through controller showing error in Laravel 4.2

I am trying to pass a simple $name variable via controller.
Controller file:
if($validator->fails())
{
$this->layout->content = View::make('admin.login' )->with('name',$name);
}
Note:
protected $layout = 'admin.layout.login_master';
$layout is class member for login page layout
View file:
#section('content')
<h1>Admin Login</h1>
{{ Form::open(array('url' => 'admin/login','method'=>'post')) }}
<div style="color:red">
{{ $name }}
</div>
<div id="row">
<div class="form-group">
{{ Form::label('username', 'Username') }}
{{ Form::text('username', '', array('class' => 'form-control')) }}
</div>
</div>
<div id="row">
<div class="form-group">
{{ Form::label('password') }}
{{ Form::password('password', array('class' => 'form-control')) }}
</div>
</div>
<div id="row">
<div class="form-group">
{{ Form::submit('Login',array('class'=>'btn btn-default')) }}
</div>
</div>
{{ Form::close() }}
#stop
it's showing an error in the log file:
Next exception 'ErrorException' with message 'Undefined variable: name (View: C:\xampp\htdocs\portfolio\app\views\admin\login.blade.php)' in C:\xampp\htdocs\portfolio\app\storage\views\94976abb04474489c25123342a2993a1:7
Stack trace:
and in the browser it's showing:
Whoops, looks like something went wrong.
If this is not working, there are other ways also to pass variables from controller to view in Laravel
if you have $name variable defined and want to access in views with $name then u can try any of following
$this->layout->content = View::make('admin.login' )->withName($name);
$this->layout->content = View::make('admin.login' )->with(compact('name'));
$this->layout->content = View::make('admin.login', array('name'=>$name) )

Categories