Repeating Form Fields In Laravel - php

I have a form which is submitting data to 2 separate models.
The model SalesItem belongs to Sale. A Sale can have many SalesItems.
I know I need to get the repeating fields into an array, but I'm not entirely sure how I should go about doing that. I though I had the right idea, but my controller isn't catching the array as the variable I was trying to set it up as.
Can see relevant code here: http://laravel.io/bin/Qzk24
All help is greatly appreciated!
/*** Sale Model ***/
class Sale extends \Eloquent {
public function user(){
return $this->belongsTo('User');
}
public function salesItem()
{
return $this->hasMany('SalesItem');
}
}
/*** SalesItem Model ***/
class SalesItem extends \Eloquent {
protected $table = 'SalesItems';
public function sale()
{
return $this->belongsTo('Sale');
}
}
/**** SalesController#store ****/
public function store()
{
$sale = new Sale();
if(Auth::user()){
$userID = Auth::user()->id;
$sale->user_id = $userID;
}
$sale->invoice_number = Input::get('invoice_number');
$sale->name_of_purchaser = Input::get('name_of_purchaser');
$sale->date_of_sale = Input::get('date_of_sale');
// For each saleItem that exists
foreach($items as $item)
{
//Create new salesitem
$saleItem = new SalesItem();
//Save attributes
$saleItem->product_id = $item['equipment'];
$saleItem->selling_price = $item['selling_price'];
$saleItem->serial_number = $item['serial_number'];
$saleItem->save();
//associate with the sale
$sale->salesItem()->associate($salesItem);
}
$sale->save();
return "Sale Saved";
}
/**** sales/create.blade.php *****/
{{ Form::open(array('action'=>'SalesController#store')) }}
<ul>
<li>
{{ Form::label('invoice_number','Dealer Invoice Number:')}}
{{ Form::text('invoice_number')}}
{{ $errors->first('invoice_number','<small class="error">:message</small>')}}
</li>
<li>
{{ Form::label('name_of_purchaser','Name of Purchaser:')}}
{{ Form::text('name_of_purchaser')}}
{{ $errors->first('name_of_purchaser','<small class="error">:message</small>')}}
</li>
<li>
{{ Form::label('date_of_sale','Date of Sale:')}}
{{ Form::text('date_of_sale')}}
{{ $errors->first('date_of_sale','<small class="error">:message</small>')}}
</li>
<li>
<h2> Sale Items </h2>
<ul class="repeatable">
<li>
{{ Form::label('items[0][equipment]','Equipment:')}}
{{ Form::text('equipment[0]', Input::get('equipment'), array('class' => 'form-control clone'))}}
{{ $errors->first('equipment','<small class="error">:message</small>')}}
</li>
<li>
{{ Form::label('selling_price[0]','Selling Price:')}}
{{ Form::text('selling_price[0]', Input::get('selling_price'), array('class'=>'form-control clone'))}}
{{ $errors->first('selling_price','<small class="error">:message</small>')}}
</li>
<li>
{{ Form::label('serial_number[0]','Serial Number:')}}
{{ Form::text('serial_number[0]', Input::get('serial_number'), array('class'=>'form-control clone'))}}
{{ $errors->first('serial_number','<small class="error">:message</small>')}}
</li>
<li>
<button href="#" class="add" rel=".clone"><i class="fa fa-plus-square"></i> Add Item</button>
</li>
</ul>
</li>
<li>
{{ Form::submit($buttonText) }}
</li>
</ul>
{{ Form::close(); }}
/**** Getting this error Undefined variable: items
* /app/controllers/SalesController.php
****/

Well you have a few errors in your code, but I'll try to give you a direction..
Replace the input fields with something like this:
{{ Form::text('items[0]["equipment"]', array('class' => 'form-control clone'))}}
....
{{ Form::text('items[0]["selling_price"]', array('class' => 'form-control clone'))}}
....
Grab the items using $items = Input::get('items'); (btw this is the point where php threw an error: you never got the $items from the request)
Iterate over the items array and add every single one of it to your Sale model..

Related

I got an error while creating sub menu in my database mysql

I am new to laravel. I want to create submenu for my website using the eloquent. However it gives me and error saying that
Base table or view not found: 1146 Table 'shopping.sub_menus' doesn't exist (SQL: select * from sub_menus where sub_menus.menu_id = 1 and sub_menus.menu_id is not null)
my model menu
Menu.php
class Menu extends Model
{
public function submenu()
{
return $this->hasMany(SubMenu::class);
}
}
// SubMenu Model
class SubMenu extends Model
{
public function menu()
{
return $this->belongsTo(Menu::class);
}
}
and below is blade
side-nav.blade.php
<ul>
#foreach ($menu as $_menu)
<li>
<a href="{{ route($_menu->route) }}" id={{ $_menu->id }} class="side-menu">
#if ($_menu->submene->count())
<ul>
#foreach ($_menu->submenu as $_submenu)
<li><a href="{{ route($_menu->route) }}" id={{ $_menu->id }}>{{$_submenu->$_menu}} </a></li>#endforeach
<div class="side-menu__icon"> <i data-feather={{ $_menu->icon_name }}></i> </div>
<div class="side-menu__title"> {{ $_menu->menu_name }} </div>
</a>
</li>
#endforeach

How to pass parameter to model function from view?

I have tree structure of categories. Now I have to display only that categories which is not applied in a particular business.
Code in Controller
public function edit($id)
{
try
{
$id=Crypt::decrypt($id);
$business=Business::findOrFail($id);
$business_contact_details=BusinessContactDetails::where('business_id',$id)->select('contact_no','id')->get();
$business_working_hours=BusinessWorkingHours::where('business_id',$id)->get();
$business_categories=BusinessCategories::leftJoin('categories','categories.id','=','category_id')->where('business_id',$id)->where('categories.parent_id','0')->select('categories.name as name','approved','category_id','business_categories.id as id')->get();
$categories = Categories::where('parent_id', '=', 0)->get();
return view('admin.businesses.edit',compact('business','business_contact_details','business_working_hours','categories','category_counter','business_categories'));
}
catch(DecryptException $e)
{
return view('errors.404');
}
}
Code in Model
public function subChilds(){
return $this->hasMany('App\Categories','parent_id','id')->whereNotExists(function($query){
$query->from('business_categories')->whereRaw('categories.id=business_categories.category_id')->where('business_id',2);
});
}
Code in edit View
<div class="col-md-6">
<ul id="tree1">
#foreach($categories as $category)
<li>
<input type="checkbox" value="{{$category->id}}" name="categories[]">
{{ $category->name }}
#if(count($category->subChilds($business->id)))
#include('admin.businesses.manageChildSub',['subChilds' => $category->subChilds($business->id)])
#endif
</li>
#endforeach
</ul>
</div>
Code in manageChildSub View
<ul>
#foreach($subChilds as $child)
<li>
<input type="checkbox" value="{{$child->id}}" name="categories[]">
{{ $child->name }}
#if(count($child->childs))
#include('manageChildSub',['subChilds' => $child->subChilds($business->id)])
#endif
</li>
#endforeach
</ul>
Here, You can see that I have passed business_id as 2, but I have to pass it as my current business ID. Basically I need to call the model function with ID.
After changing to this, I am not getting any subcategories.
You can try this:
public function subChilds($business_id){
return $this->hasMany('App\Categories','parent_id','id')
->whereNotExists(function($query) use ($business_id){
$query->from('business_categories')
->whereRaw('categories.id=business_categories.category_id')
->where('business_id', $business_id);
});
}

Trying to delete record by CRUD route::delete method(Laravel 5.3)

I have a problem with Larave's framework program with deleting by CRUDS method DELETE.
My route method is:
Route::delete('cats/{cat}/delete', function(Furbook\Cat $cat){
$cat->delete(); return redirect('cats.index')
->withSuccess('Cat
has been deleted.'); });
My view with delete url:
#extends('layouts.master')
#section('header')
Back to the overview
<h2>
{{ $cat->name }}
</h2>
<a href="{{ url('cats/'.$cat->id.'/edit') }}">
<span class = "glyphicon glyphicon-edit"></span>
Edit
</a>
<a href ="{{ url('cats/'.$cat->id.'/delete') }}">
<span class ="glyphicon glyphicon-trash"></span>
Delete
</a>
<p>Last edited: {{ $cat->updated_at }}</p>
#endsection
#section('content')
<p>Date of Birth: {{ $cat->date_of_birth }} </p>
<p>
#if ($cat->breed)
Breed:
{{ url('cats/breeds/'.$cat->breed->name) }}
#endif
</p>
#endsection
My Cat model:
<?php
namespace Furbook;
use Illuminate\Database\Eloquent\Model;
class Cat extends Model {
// We specified the fields that are fillable in the Cat model beforehand
protected $fillable = ['name','date_of_birth','breed_id'];
// informacja o tym, żeby nie uaktualniać update_at w tabeli kotów
public $timestamps = false;
public function breed(){
return $this->belongsTo('Furbook\Breed');
}
}
?>
When I'm clicking on delete link, there is an error like this:
MethodNotAllowedHttpException in RouteCollection.php line 233:
I don't know what's wrong. Could you somoene help me with solving problem?
Could someone help me with this problem?
I would be very grateful, greetings.
This is to do with the Request you are making. You must either create form with the delete method like so
<form action="{{ url('cats/'.$cat->id.'/delete') }}" method="DELETE">
<button class ="glyphicon glyphicon-trash">Delete</button>
</form>
OR change your route to a get
Route::get('cats/{cat}/delete', function(Furbook\Cat $cat){
$cat->delete();
return redirect('cats.index')->withSuccess('Cat has been deleted.');
});
If you go the form route don't for get to add the {{ csrf_field() }}
https://laravel.com/docs/5.4/csrf
Using Route::delete(), you cannot place it in an anchor. Make a form with DELETE method.
{!! Form::model($cat, ['method' => 'DELETE', 'url' => 'cats/'.$cat->id.'/delete']) !!}
<button type="submit">Delete</a>
{!! Form::close() !!}

Update multible rows in laravel 4

I wanted to update multiple rows in the database and have found a way to do it. but it does not seem like the best way to do it, since it is doing it in multiple calls at the moment.
I wanted to now if there is a better way to do this.
The homecontroller with the updatePersons function:
<?php
class HomeController extends BaseController {
public function index()
{
$persons = Person::get();
return View::make('hello')
->with(compact('persons'));
}
public function updatePersons()
{
$persons = Person::get();
foreach ($persons as $person) {
$person->fname = Input::get('fname'.$person->id);
$person->lname = Input::get('lname'.$person->id);
$person->save();
}
return Redirect::route('home')->with('succes', 'Siden er opdateret');
}
}
the view with the form
#extends('layouts.master')
#section('content')
<div class="container">
<ul class="list-group">
{{ Form::open(array('route'=>'personUpdate', 'method' => 'post')) }}
#foreach ($persons as $person)
<li class="list-group-item">
{{ Form::text('fname'.$person->id,$person->fname,array('class'=>'form-control', 'placeholder'=>'fname')) }}
{{ Form::text('lname'.$person->id,$person->lname,array('class'=>'form-control', 'placeholder'=>'lname')) }}
</li>
#endforeach
<li class="list-group-item">
<div class="box-footer">
<button type="submit" class="btn btn-primary">Update</button>
</div>
</li>
{{ Form::close() }}
</ul>
</div>
</div>
#stop
The routes:
<?php
Route::get('/', array('as'=>'home', 'uses'=>'HomeController#index'));
Route::post('/', array('as'=>'personUpdate', 'uses'=>'HomeController#updatePersons'));
I have tried to use the savemany() function on $persons after the foreach loop in updatePersons() but with no results.
If you're updating many rows with each with different values, there's no easier way to do it.
Could you think of how you'd write this in SQL?

How to make menu and submenu dynamic Laravel

I want to make menu and submenu dynamic .I made menu with their link but unable to make submenu,please help me my database structure
table name:menu
id menu_name url timestamps
table:sub_menu
id submenu_name link menu_id timestamps
my query is like this
public function menu()
{
$sql=\DB::table('menu')->rightjoin('sub_menu','menu.id','=','sub_menu.menu_id')
->select('submenu_name','link','url','menu_id','menu_name','menu.id')->get();
return view('products.show.menu',compact('sql'));
}
view
<ul>
#foreach($sql as $key => $nav)
#if($key > 0)
<li>
{{$nav->menu_name}}
#if (count($nav->submenu_name) > 0 )
<ul>
#foreach($nav->submenu_name as $child)
<li>{{$child->submenu_name}}</li>
#endforeach
#endif
</ul>
</li>
#endif
#endforeach
</ul>
Have you set up models for these tables? Your query will return multiple rows for each menu/submenu combination, meaning you can't just iterate over it as you are. There's no need to use the query builder here.
Assuming your models are set up as follows (you will need to check the namespace used in the relationships):
class Menu extends Eloquent
{
protected $table = 'menu';
public function submenu()
{
return $this->hasMany('App\SubMenu');
}
}
class SubMenu extends Eloquent
{
protected $table = 'sub_menu';
public function menu()
{
return $this->belongsTo('App\Menu');
}
}
In your controller, you can do:
public function menu()
{
$menu = Menu::with('submenu')->get();
return view('products.show.menu', compact('menu'));
}
Then in your view:
<ul>
#foreach($menu as $menuItem)
<li>
{{ $menuItem->menu_name }}
#if( ! $menuItem->submenu->isEmpty())
<ul>
#foreach($menuItem->submenu as $subMenuItem)
<li>{{ $subMenuItem->submenu_name }}</li>
#endforeach
</ul>
#endif
</li>
#endforeach
</ul>
You can use it without controller
`#foreach(App\Menu::get() as $menuItem)
#if( ! $menuItem->submenu->isEmpty() )
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false">
{{ $menuItem->menu_name }}
</a>
#else
<li>
{{ $menuItem->menu_name }}
#endif
#if( ! $menuItem->submenu->isEmpty())
<ul class="dropdown-menu" role="menu">
#foreach($menuItem->submenu as $subMenuItem)
<li>{{ $subMenuItem->submenu_name }}</li>
#endforeach
</ul>
#endif
</li>
#endforeach`

Categories