I am new to Laravel and I am trying to call the destroy function in the controller passing in two parameters but I get the error: exception missing argument 2 for GradoController::destroy().
I have grades from 1 (first) through 6 (sixth) and each has subjects associated with it. The grades are listed on the page in tabs and by clicking the tab you get a list of the subjects that go with the grade. I put a delete button next to each subject so the user can click delete and detach the subject from the grade.
I am trying to pass both the gradeId and the subjectId to the destroy method in GradoController
My view file index.blade.php:
<html>
<head>
{{HTML::script('assets/js/jquery-1.11.1.js'); }}
{{HTML::script('assets/js/jquery-ui.js'); }}
{{HTML::script('assets/js/jquery-ui.min.js'); }}
{{HTML::style('assets/css/jquery-ui.min.css'); }}
<script>
$(function() {
$( '#tabs' ).tabs();
});
</script>
</head>
<body>
<h1>Lista Materias por Grado</h1>
<?php
$year = date("Y");
$month = date("m");
if($month < 8){
$year = $year - 1;
} ?>
<h2>{{$year}}-{{$year+1}}</h2>
<div id="tabs">
<ul> <?php $i=1; ?>
#foreach($grados as $grado)
<li>Grado:{{ $grado->name_grados}} </li>
<?php $i++; ?>
#endforeach
</ul>
<?php $i = 1; ?>
#foreach($grados as $grado)
<div id="tabs-{{$i}}" >
#if($grado->subject->count())
#foreach($grado->subject as $subject)
<li> {{ $subject->name_subjects }}
{{Form::open(array('method' => 'DELETE', 'route' => array('grados.destroy', $grado->id_grados, $subject->id_subjects))) }}
{{ Form::submit('Delete',array('class' => 'btn btn-danger')) }}
</li>
#endforeach
#else
No hay materias asociadas
#endif
</br></br>
{{ link_to_route('grados.edit', 'Agregar Materias',
array($grado->id_grados), array('class' => 'btn btn-info')) }}
<?php $i++; ?>
</div>
#endforeach
</div>
My GradoController's destroy function:
public function destroy($gradoId, $subjectId)
{
$grado = Grado::find($gradoId);
$year = 2014;
$grado->subject()->detach($subjectId, array('year_grado_subject'=>$year));
return Redirect::route('grados.index');
}
In routes I have:
Route::get('grados/{id_grados}/{id_subjects}/destroy', 'GradoController#destroy');
Route::resource('grados', 'GradoController');
Thanks!
What I can imagine is that the Form uses the action via
Route::resource('grados', 'GradoController');
and the "default DELETE" (see http://laravel.com/docs/4.2/controllers#restful-resource-controllers) only uses one parameter (/grados/{parameter}), so the second parameter gets lost and is not passed on to the Controller action. This is because there is no route set on
Route::get('grados/{id_grados}/{id_subjects}/destroy','GradoController#destroy');
AND it doesn't use Route::delete but rather Route::get.
So changing it to
Route::delete('grados/{id_grados}/{id_subjects}/destroy',['as' => 'grados.destroy', 'uses' => 'GradoController#destroy']);
will hopefully do the trick. Plus I would avoid defining the same routes twice. E.g. you can use this:
Route::resource('grados', 'GradoController', array('except' => array('destroy')));
Related
I'm working with Laravel 5.1
I have a template for a page that was previously working fine. I could hit my route and the page would be rendered as expected. At some point the page started just displaying the text contained in the blade template rather than rendering my page. To my knowledge nothing had changed in my routes file, controller or blade. Is there anything that is known to cause this to happen? I've tried updating permissions, using a different method to call the view and creating a new view file all together.
The route:
Route::group(['prefix' => '/admin'], function() {
Route::group(['prefix' => '/reactor-rules'], function() {
Route::get('/visual-rules/{track_id?}', [
'as' => 'broker_visual_reactor_rules',
'uses' => 'ReactorRulesController#visualRules'
]);
});
});
ReactorRulesController#visualRules:
public function visualRules(IReactorTrackDAO $reactorTrackDAO, $id = 0)
{
$export = new ReactorExport();
$tracks = $export->getReactorTracks();
if ($id == 0) {
$eventsArray = [];
}
else {
$eventsArray = $export->getArrayForTrack($id);
}
return $this->renderView('enterpriseBroker::reactor-rules.visual-rules', compact('eventsArray','tracks','reactorTrackDAO'));
}
My blade:
#extends($layout)
{{ SEO::setPageTitle(trans('enterpriseBroker::reactorRules.title'), false) }}
#section('content')
<br>
<br>
#if(empty($eventsArray))
<p>Please select a track below to view/export rules.</p>
#foreach($tracks as $track)
{{$track->name}}<br>
#endforeach
#else
#foreach($eventsArray as $track => $events)
<h4>{{$track}}</h4>
<a href="{{url().'/admin/visual-rules/'.$reactorTrackDAO->findByName($track)->id.'/download'}}" class="btn btn-primary" download>Export</a><br>
#foreach($events as $id => $event)
#if (count($event['rules']) > 0)
<div id="{{$track.'-'.str_replace(' ','_',$event['name'])}}">
<div class="col-lg-12">
<hr/>
<div class="col-lg-2">
<h4>{{$event['name']}}</h4>
</div>
<div class="col-lg-10 border border-primary">
#foreach($event['rules'] as $ruleId => $rule)
<h5>{{$rule['name']}}</h5>
<div class="col-lg-6">
<h6>Conditions to be met:</h6>
#foreach($rule['conditions'] as $condition)
<p>{{$condition}}</p>
#endforeach
</div>
<div class="col-lg-6">
<h6>Actions to run:</h6>
#foreach($rule['actions'] as $action)
<p>{!!$action!!}</p>
#endforeach
</div>
#endforeach
</div>
</div>
</div>
#endif
#endforeach
#endforeach
#endif
#endsection
#section('scripts')
#endsection
This is how it originally appeared:
This is how it currently appears:
It seems to be error with $layout
Try to test it using a hard coded value as below:
#extends('layouts.app')
and run below command
php artisan view:clear
I resolved the issue by creating a new blade file, pasting the contents of the old one in and pointing my controller to the new view. I'm not sure how this resolved the issue.
I'm trying to pass anINT from this URL: myapp.build/courses/anINT (implemented in the CoursesController) to $id in the Lesson_unitsController function below. I've tried a lot of solutions, but I can't seem to get it right.
The function in the CoursesController which implements the url is:
public function show($id)
{
$course = Course::find($id);
return view('courses.show')->with('course', $course);
}
Part of the show.blade.php file is:
#if(!Auth::guest())
#if(Auth::user()->id == $course->user_id)
Edit Course
Lesson Units
{!!Form::open(['action'=> ['CoursesController#destroy', $course->id], 'method' => 'POST', 'class' => 'float-right'])!!}
{{Form::hidden('_method', 'DELETE')}}
{{Form::submit('Delete', ['class' => 'btn btn-danger'])}}
{!!Form::close()!!}
#endif
#endif
The Lesson_unitsController functions are:
public function index()
{
$lesson_units = Lesson_unit::orderBy('title','asc')->paginate(10);
return view('lesson_units.index')->with('lesson_units', $lesson_units);
}
public function specificindex($id)
{
$course = Course::find($id);
return view('lesson_units.specificindex')->with('lesson_units', $course->lesson_units);
}
And the specificindex.blade.php file is:
#extends('layouts.app')
#section('content')
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card">
<div class="card-header">Dashboard</div>
<div class="card-body">
Create lesson unit
<p>
<h3>Your lesson_units</h3>
#if(count($lesson_units) > 0)
<table class="table table-striped">
<tr><th>Title</th><th></th><th></th></tr>
#foreach($lesson_units as $lesson_unit)
<tr><td>{{$lesson_unit->title}}</td>
<td>Edit</td>
<td>
{!!Form::open(['action'=> ['Lesson_unitsController#destroy', $lesson_unit->id], 'method' => 'POST', 'class' => 'float-right'])!!}
{{Form::hidden('_method', 'DELETE')}}
{{Form::submit('Delete', ['class' => 'btn btn-danger'])}}
{!!Form::close()!!}
</td>
</tr>
#endforeach
</table>
#else
<p>You have no lesson unit.</p>
#endif
#if (session('status'))
<div class="alert alert-success" role="alert">
{{ session('status') }}
</div>
#endif
You are logged in!
</div> </div> </div> </div> </div>
#endsection
The routes in web.php are:
Route::resource('courses', 'CoursesController');
Route::resource('lesson_units', 'Lesson_unitsController');
Route::get('/courses/{id}', 'Lesson_unitsController#specificIndex');
I want that when the link for Lesson Units is clicked on the page, the id in the url is passed to the specificindex function in the Lesson_unitsController. Now, I get just a blank page. What am I doing wrong?
Try to understand the concept of RESTful and CRUD.
By using Route::resource('courses', 'CoursesController');, Laravel has helped you to register the following routes:
Route::get('courses', 'CoursesController#index');
Route::get('courses/create', 'CoursesController#create');
Route::post('courses/{course}', 'CoursesController#store');
Route::get('courses/{course}/edit', 'CoursesController#edit');
Route::put('courses/{course}', 'CoursesController#update');
Route::delete('courses/{course}', 'CoursesController#destroy');
Then, when you make GET request to myapp.build/courses/123, Laravel will pass the request to the show function of your CoursesController like:
public function show(Course $course)
{
return view('lesson_units.index')->with('lesson_units', $course->lesson_units);
}
Laravel will automatically resolve the Course from your database using the parameter passed into the route myapp.build/courses/{course}.
Note: The variable name $course has to match with the one specify in route /{course}.
You don't have a route set up to handle the $id coming in. The resource method within the Route class will provide a GET route into your Lesson_unitsController controller without an expectation of any variable. It is the default index route, and by default doesn't pass a variable.
There are a couple of ways to do this, but the easiest is to just create a new route for your specific need:
Route::get('lesson_units/{id}', 'Lesson_unitsController#specificIndex');
And then make your specificIndex function in your controller with an incoming variable:
public function specialIndex($id)
{
$course = Course::find($id);
// return view to whatever you like
}
HTH
I have a method to get an author and display it on a form. It also retrieves the number of quotes attributed to that author. Being pedantic I do not wish to have "1 quotes" so I wrote the following in my layout:
#extends('layouts.dashboardmaster')
$quotetext = "quotes";
if ( $quotes == 1)
{ $quotetext = "quote"; }
#section('pageheading')
<div class="well">
<h2><i class = "fa fa-quote-left"></i> edit author ({{$author->author}}), ({{ number_format($quotes,0) }} {{}}$quotetext }}) </h2>
</div>
#endsection
but I am now getting an error saying
Undefined variable: quotetext
It is clearly defined and I have also tried replacing {{ with
What am I doing wrong?
needs to be
<?php $quotetext = "quotes";
if ( $quotes == 1)
{ $quotetext = "quote"; }
?>
Your view needs to look like this:
#extends('layouts.dashboardmaster')
<?php $quotetext = "quotes"; ?>
#if($quotetext == 1)
<?php $quotetext = "quote"; ?>
#endif
#section('pageheading')
<div class="well">
<h2><i class = "fa fa-quote-left"></i> edit author ({{$author->author}}), ({{ number_format($quotes,0) }} {{$quotetext }}) </h2>
</div>
#endsection
you didn't put php codes in <?php tag.
put them in php tag and everything will be fine
<?php
$quotetext = "quotes";
if ( $quotes == 1){
$quotetext = "quote";
}
?>
from the docs https://laravel.com/docs/5.2/blade
{{ isset($name) ? $name : 'Default' }}
so
{{ isset($quotetext) ?: "quotes" }}
#if ($quotes == 1)
{{ $quotetext = "quote"; }}
#endif
but i think u will get an error about $quotes aswell, anyway remember this is blade not normal php
Use localization provided by Laravel. See Laravel Docs for more information.
Just as an example, add this to your language file (for example resources/lang/en/lang.php
return [
'quote' => 'quote|quotes',
]
Then use this in your view:
{{ trans_choice('lang.quote', $count) }}
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?
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..