Invalid argument supplied for foreach with laravel 5.4 - laravel

I'm getting Invalid argument supplied for foreach() error in my view after publishing a post and the code i use for looping in my controller is this:
public function edit($id)
{
$post = Post::find($id);
$categories = Category::all();
$cats = array();
foreach ($categories as $category) {
$cats[$category->id] = $category->name;
}
$tags = Tag::all();
$tags2 = array();
foreach ($tags as $tag) {
$tags2[$tag->id] = $tag->name;
}
return view('admin.posts.edit')->withPost($post)->withCategories($cats)->withTags($tags2);
}
this is the only part i handle loops in my postcontroller edit section. And I know the issue is from Tags loop because when I remove the tags code in my view other part will show up correctly.
Oh and this is the loop i use in my view:
#extends('layouts.app')
#section('content')
<div class="col-md-8">
<div class="panel panel-default">
<div class="panel-heading">{{ $post->title }}</div>
<div class="panel-body">
<p><img src="{{ asset('uploads/' . $post->image) }}" alt="{{ $post->title }}" class="img-responsive" /></p>
<p>{!! $post->body !!}</p>
</div>
<div class="tags">
#foreach ($tags as $tag)
<span class="label label-default">{{ $tag }}</span>
#endforeach
</div>
</div>
</div>
#endsection
#section('sidebar')
<div class="col-md-4">
<div class="panel panel-primary">
<div class="panel-heading"><i class="fa fa-info"></i> Post Info</div>
<div class="panel-body">
<dl class="dl-horizontal">
<label>URL:</label>
<p>{{ url('blog/'.$post->slug) }}</p>
</dl>
<dl class="dl-horizontal">
<label>Created On:</label>
<p>{{ date('M j, Y h:ia', strtotime($post->created_at)) }}</p>
</dl>
<dl class="dl-horizontal">
<label>Last Update:</label>
<p>{{ date('M j, Y h:ia', strtotime($post->updated_at)) }}</p>
</dl>
<dl class="dl-horizontal">
<label>Posted In:</label>
<p>{{ $post->category->name }}</p>
</dl>
<hr/>
<div class="row">
<div class="col-md-6">
{!! Html::linkRoute('posts.edit', 'Edit', array($post->id), array('class' => 'btn btn-warning btn-block')) !!}
</div>
<div class="col-md-6">
{!! Form::open(['route' =>['posts.destroy', $post->id], 'method' => 'DELETE']) !!}
{!! Form::submit('Delete', ['class' => 'btn btn-danger btn-block']) !!}
{!! Form::close() !!}
</div>
</div>
<hr/>
{!! Html::linkRoute('posts.index', '<< Back to Posts', [], array('class' => 'btn btn-primary btn-block')) !!}
</div>
</div>
</div>
#endsection
PS: I'm using Laravel 5.4
Post updated view!

You can't get tags via post so Try this...
<div class="tags">
#foreach ($tags as $tag)
<span class="label label-default">{{ $tag }}</span>
#endforeach
</div>

Try:
return view('admin.posts.edit')->with("post",$post)->with("categories",$cats)->with("tags",$tags2);
and at view
<div class="tags">
#foreach ($tags as $tag)
<span class="label label-default">{{ $tag->name }}</span>
#endforeach
</div>

in your table if your primary key name if not id you have to mention in your relationship Link
2.for your post has one category so you can show this into your view like this
{{ $post->category->name }}
if you get result you can use it. but seems you need tag key and value pair so use this methods
$tags = Tag::where('post_id',$post->id)->groupBy('id')->get();
or try your way
$tags = Tag::all();
$tags2 = array();
foreach ($tags as $tag) {
$tags2[$tag->id] = $tag->name;
}
return view('admin.posts.edit',compact($post,$tags2,$cats));
in your view try this
#foreach ($tags as $key => $tag)
<span class="label label-default">{{ $tag }}</span>
#endforeach

Related

How do I change the route depending on selection in laravel

I'm trying to create a page that lets the user select a product and then when they press "add to cart" that product then gets sent to the cart page.
On my product page I can have the same item that has 2 or more codes attached to it, so I've created a selection that has the codes and the user then has to pick one of them
and then press "add to cart" button to go to the cart page.
So the way I have it at the moment is that the form grabs the id of the product page and not of the selection box.
What I would like to know is how would I go about changing the route depending on what I've selected.
Here is my code
<form action="{{ route('product.addToCart', ['id' => $product->id]) }}" method="POST">
{{ csrf_field() }}
<div class="row">
<div class="col-lg-12 pl-0">
<select class="form-control mb-2" id="supplier_code" name="supplier_code">
#foreach($parent_product as $parent)
<option value="{{ $parent->supplier_code }}">{{ $parent->supplier_code }}</option>
#if(count($parent->parent))
#foreach($parent->parent as $child)
<option value="{{ $child->supplier_code }}">{{ $child->supplier_code }}</option>
#endforeach
#endif
#endforeach
</select>
</div>
</div>
{{ Form::submit('Add to Cart', array('class' => "btn btn-dark btn-lg btn-block")) }}
</form>
This is my function
public function getAddToCart(Request $request, $id)
{
$menus_child = Menu::where('menu_id', 0)->with('menusP')->get();
$contacts = Contact::all();
$product = Product::find($id);
$supplier_code = $request->supplier_code;
$oldCart = Session::has('cart') ? Session::get('cart') : null;
$cart = new Cart($oldCart);
$cart->add($product, $product->id, $supplier_code);
$request->session()->put('cart', $cart);
return view('public.shopping-cart', ['products' => $cart->items, 'totalPrice' => $cart->totalPrice, 'menus_child' => $menus_child, 'contacts' => $contacts, 'supplier_code' => $supplier_code]);
}
This is my product list page where the user will click on a product to get its details.
<div class="col-xl-9 col-lg-8 col-md-12 product-list">
<div id="parent">
<div class="row grid-container">
#foreach($products as $product)
<?php
$cat_slug = "";
?>
#foreach($product->category as $category)
<?php
$cat_slug .= " ".$category->slug
?>
#endforeach
<?php
$product_image = getImagesArray($product->image);
?>
<div class="product_items col-xl-2 col-lg-4 col-md-4 col-sm-4 {{ $cat_slug }}">
<a href="{!! route('product.item', [$product->slug]) !!}">
<div>
#if(!empty($product_image))
<img src={!! "product_images/products/$product_image[0]" !!}>
#endif
<p>
{!! $product->title !!}
</p>
</div>
</a>
</div>
#endforeach
</div>
</div>
</div>
I'm not sure if I need to add anything else, so if I do need to please let me know
Change this:
<a href="{!! route('product.item', [$product->slug]) !!}">
to this:
<a href="{{ route('product.item', $product->id) }}">

Pass data from form submit to controller via get Method

can anyone tell, what is wrong with the following way to pass the data from view->route->controller. Currently I get Missing required parameters for [Route: show.exclusion] [URI: exclusion/create/{id}]
This is my view part:
<div class="col-md-8 col-md-offset-2">
<div class="panel panel-default">
<div class="panel-heading">In welcher Gruppe möchten Sie User einladen?</div>
<div class="panel-body">
{!! Form::open(array('route'=>'show.exclusion', 'method'=>'get', 'id'=>'$group->idgroup')) !!}
<div class="form-group">
{{Form::label('choosegroup', 'Wähle eine Gruppe')}}
<select class="form-control m-bot15" name="idgroup">
#foreach($groups as $group)
<option id="{{ $group->idgroup }}">{{ $group->groupname }}</option>
#endforeach
</select>
<!--{{ csrf_field() }}-->
</div>
<div>
{{Form::submit('Search',['class' => 'btn btn-primary'])}}
<a class="btn btn-default btn-close" href="{{ route('home') }}">Cancel</a>
</div>
{!! Form::close() !!}
</div>
</div>
</div>
</div>
This is my route...
Route::get('exclusion/create/{id}', 'ExclusionController#show')->name('show.exclusion');
And here you can see my controller function...
public function show($id)
{
$groupid = $id;
$members = V_Exclusion::where([['idgroup', $groupid],['groupadmin', Auth::id()]])->get();
$groups = V_Exclusion::where('groupadmin', Auth::id())->get();
return view('exclusions.createexclusion')
->with('members', $members)
->with('groups', $groups);
}
Try this.
In Route
Route::get('exclusion/create/{id}', 'ExclusionController#show');
{!! Form::open(array('route'=>['exclusion/create',$group->idgroup], 'method'=>'get', 'id'=>'$group->idgroup')) !!}

Several updates on the same view Laravel

In a setup process I want to:
select langs of the application (1 or more) ...
Update the DB
Select the default language
Update again the DB...
For this i created 3 routes.
Route::get('/home/setup', 'BackOffice\FirstconnectionController#initLang');
Route::patch('/home/setup', 'BackOffice\FirstconnectionController#initLangUpdate')->name('setup.setLang');
Route::patch('/home/setup', 'BackOffice\FirstconnectionController#setDefaultLang')->name('setup.setDefaultLang');
The first is the home page where i make eloquent requests
The second route display the list of languages
The third route displays the list of languages which are published ...
Here is my view :
#if ($message = Session::get('success'))
<div class="alert alert-success">
<p>{{ $message }}</p>
</div>
#endif
{{-- IF NO LANGS ARE PUBLISHED I CAN CHOOSE HERE --}}
#if ($langsCount == 0)
{!! Form::model($langs, [
'method' => 'PATCH',
'route' => 'setup.setLang'
])
!!}
#foreach($langs as $lang)
<div class="form-group">
{{--<label class="col-md-4"> {{ $lang->langname }} </label>--}}
{{--<input id="{{ $lang->langisocode }}" type="checkbox">--}}
{!! Form::label($lang->langname, $lang->langname ) !!}
{!! Form::checkbox( 'lang[]', $lang->id ) !!}
</div>
#endforeach
<div class="col-xs-12 col-sm-12 col-md-12 text-center">
<button type="submit" class="btn btn-primary">Valider</button>
</div>
{!! Form::close() !!}
{{-- NOW I SELECT DEFAULT LANGUAGE... --}}
#else
{!! Form::model($langs, [
'method' => 'PATCH',
'route' => 'setup.setDefaultLang'
])
!!}
#foreach($pubLangs as $pubLang)
{!! Form::label($pubLang->langname, $pubLang->langname ) !!}
{!! Form::radio( 'lang', $pubLang->id ) !!}
<br>
#endforeach
<div class="col-xs-12 col-sm-12 col-md-12 text-center">
<button type="submit" class="btn btn-primary">Valider</button>
</div>
{!! Form::close() !!}
#endif
Here is my controller :
// I display the info here
public function initLang()
{
$langs = Lang::onlyTrashed()->get();
$langsCount = Lang::count();
$pubLangs = Lang::all();
return view('admin.firstConnection', compact('langs', 'langsCount', 'pubLangs'));
}
public function initLangUpdate(Request $request) {
$request = $request->input('lang');
foreach ($request as $entry) {
Lang::withTrashed()->find($entry)->restore();
}
return redirect('admin/home/setup')->with('success', 'OK');
}
public function setDefaultLang(Request $request) {
$request = $request->input('lang');
return $request;
}
I will update the setDefaultLang after ...
I have this error message :
Route [setup.setLang] not defined

using Pagination with orderBy Eloquent Model

I have a function witch is getting all properties joining the images tables with orderBy and need to add paginate
here is my function
public function show_all()
{
$properties = PropertyDetail::where('active', 1)->with('propImages')->paginate(15)
->orderBy('id', 'DESC')
->get();
return View::make('portal.properties.view_all', compact('properties'));
}
in my view I got
call_user_func_array() expects parameter 1 to be a valid callback,
class 'Illuminate\Support\Collection' does not have a method 'orderBy'
another thing when I removed the orderBy('id', 'DESC')->get() and I try
it works but when I try to put {{ $prop->links() }} in the view I got
Call to undefined method Illuminate\Database\Query\Builder::links()
here is how my view looks like
#foreach($properties as $prop)
<div class="property col-xs-12 col-sm-6 col-md-4">
<div class="image">
<div class="content imgContainer">
{{ HTML::link('property-details/'.$prop->id, '') }}
#foreach($prop->propImages->slice(0, 1) as $image)
{{ HTML::image('images/propertyImages/'.$image->image, $prop->title) }}
#endforeach
</div>
<div class="price"> OMR. <span class="priceNumber"> {{ $prop->price }}</span></div>
</div>
<div class="title">
<h2>{{ HTML::link('', $prop->title, array('title'=>'$prop->title')) }}</h2>
</div>
<div class="location">{{ trans('location.'.$prop->propLocation->city) }}</div>
<div class="bathrooms">
<div class="content">{{ $prop->bathroom }}</div>
</div>
<div class="bedrooms">
<div class="content">{{ $prop->bedroom }}</div>
</div><!-- /.bedrooms -->
<div class="receptionRoom">
<div class="content">{{ $prop->dining_room }}</div>
</div>
</div>
#endforeach
{{ $prop->links() }}
The correct syntax is:
$properties = PropertyDetail::where('active', 1)
->with('propImages')
->orderBy('id', 'desc')
->paginate(15);

Blade from Database not working properly

I am using voyager backoffice with laravel, and i'm having a problem with the blade coming from the database, all the code works except the blade, all the blade code outside the database works well.
I've already used {{ }}, {!! !!}, {{{ }}}, Html_entity_decode () but nothing works.
Any help is appreciated.
Thank you
View:
#extends ('layout')
#section ('content')
#foreach ($pageContent as $page)
{!! $page->slug !!}
{!! $page->title !!}
{!! $page->body !!}
#endforeach
#endsection
body that came from db:
<div class="container contacts_content_container">
<div class="row">
<div class="col-sm-12 text-center">
<div class="content">
<h1>Contact US Form</h1>
#if(Session::has('success'))
<div class="alert alert-success">
{{ Session::get('success') }}
</div>
#endif
{!! Form::open(['route'=>'contactus.store']) !!}
<div class="form-group {{ $errors->has('name') ? 'has-error' : '' }}">
{!! Form::label('Name:') !!}
{!! Form::text('name', old('name'), ['class'=>'form-control', 'placeholder'=>'Enter Name']) !!}
<span class="text-danger">{{ $errors->first('name') }}</span>
</div>
<div class="form-group {{ $errors->has('email') ? 'has-error' : '' }}">
{!! Form::label('Email:') !!}
{!! Form::text('email', old('email'), ['class'=>'form-control', 'placeholder'=>'Enter Email']) !!}
<span class="text-danger">{{ $errors->first('email') }}</span>
</div>
<div class="form-group {{ $errors->has('message') ? 'has-error' : '' }}">
{!! Form::label('Message:') !!}
{!! Form::textarea('message', old('message'), ['class'=>'form-control', 'placeholder'=>'Enter Message']) !!}
<span class="text-danger">{{ $errors->first('message') }}</span>
</div>
<div class="form-group">
<button class="btn btn-success">Contact US!</button>
</div>
{!! Form::close() !!}
</div>
</div>
</div>
</div>
Controller:
<?php
namespace App\Http\Controllers;
use App\Page;
use Illuminate\Routing\Controller;
class PageController extends Controller {
/**
* Display a listing of the resource.
*
* #return Response
*/
public function index()
{
// get all the pages
$pages = Page::all();
// load the view and pass the pages
return view('public.about')
->with('pages', $pages);
}
public function slug($slug)
{
// get page where slug
$pageContent = Page::where('slug', $slug)->get();
// load the view and pass the page content
return view('public.' . $slug)
->with('pageContent', $pageContent);
}
}
Routes:
//Pages Routing With slug
Route::get('/{slug}','PageController#slug');
I'd say keeping templates in a DB is not a good idea, but if you really need it you can parse Blade template manually. There are multiple ways to do that and one of these is using compileString() method:
$html = Blade::compileString($page->template);
May be compileString() might help you.Try this
Blade::compileString('Your blade syntax from db {!! $variable !!}');

Resources