laravel 5 fill form select with data - php

I'm trying to build a form to assign a reward to an item (I call it a "ticket"). I want a dropdown list with all of the tickets so that the person can then choose.
This is my controller
$tickets = Ticket::all();
return view('rewards.create',compact('tickets'));
And in my blade.php view
<div class="form-group">
{!! Form::label('ticket','reward for: ') !!}
{!! Form::select('id', $tickets, Input::old('id')) !!}
</div>
This works, but it shows all the fields of the object. I want it show two fields. To store the 'id' in the vallue and 'description' in the written field of the select box, but doing something like
{!! Form::select('id', $tickets->description, Input::old('id')) !!}
brings up an error.
Can anyone please help?

The options have to be passed as array: ['value' => 'text']. You can use lists() to build that array for you:
$tickets = Ticket::lists('description', 'id');
return view('rewards.create',compact('tickets'));

In your blade.php
<div class="form-group">
{!! Form::label('ticket','reward for: ') !!}
{!! Form::select('id', $tickets->id, Input::old('id')) !!}
{!! Form::select('description', $tickets->description, Input::old('description')) !!}
</div>

Related

Laravel forms with models

I have this code for my form and it works well:
<div class="form-group">
<select class="form-control" id="exampleSelect1">
<option>Assign</option>
#foreach ($projects as $project)
<option>{{ $project->name }} </option>
#endforeach
</select>
</div>
but what I'm trying to do is this with a contact form:
<div class="form-group">
{!! Form::label('name', 'Project') !!}
{!! Form::select (#theforeach with the values :c ) !!}}
</div>
I'm using the use App\Http\Requests\ContactFormRequest; and I have been searching the way of doing it but there is to few examples on google.
Form is part of the Laravel Collective HTML library, you can find the documentation here, specifically you're looking for the Select documentation:
echo Form::select('size', ['L' => 'Large', 'S' => 'Small']);
You have a Collection of Project models, each with a name and (presumably) an id which you need to turn into a key -> value array for the select method which you can do using pluck:
{!! Form::select('project', $projects->pluck('name', 'id')) !!}
Then within your controller you'll be able to find the project that has been selected using find, e.g:
Project::find($request->project);
If you want your select options to works, you need to call it properly,
From controller,
// Example : This is for single view page
$list_of_options = Products::pluck('name','id');
return view('your_view_name',compact('list_of_options'));
// Example : If you want select dropdown in all page ( within the controller views) then,
use Illuminate\Support\Facades\View;
public function __construct(){
View::share('list_of_options',Products::pluck('name','id'));
}
Now in blade,
{{ dd($list_of_options); }} // Check if the values are comming in proper formate
{!! Form::select('name_of_the_select', $list_of_options, null ,[
'class' => 'form-control',
'id' => 'name_of_the_select'
]);
!!}
Here is the button with <i> or <span> inside of it :-
{{ Form::button(
'<span class="fa fa-play fa-1x"></span>',
[
'class'=>'btn btn-info',
'type'=>'button'
])
}}
From your question ( UPDATED )
<div class="form-group">
{!! Form::label('exampleSelect1', 'Project') !!}
{!! Form::select('projects', $projects, null ,[
'class' => 'form-control',
'id' => 'exampleSelect1',
'placeholder' => 'Please select project'
]);
!!}
</div>
I hope this helps. :)
Try this
<div class="form-group">
{!! Form::label('project', 'Project') !!}
{!! Form::select ('project', $projects->pluck('name')) !!}}
</div>
See docs https://laravel.com/docs/4.2/html#drop-down-lists
<div class="form-group">
{!! Form::label('project', 'Project') !!}
{!! Form::select ('project', $projects->pluck('name', 'id')) !!}}
</div>

Is it possible to achieve update or delete functionality with POST and without using hidden() in the view

Good day to all, I am new to Laravel framework and as I read some articles about HTTP verbs which say that POST is universal to both PUT and DELETE (reference:
https://softwareengineering.stackexchange.com/questions/114156/why-are-there-are-no-put-and-delete-methods-on-html-forms
) and thus I wonder if it is possible to achieve Update and Delete functionality with POST and without using hidden() in the view itself. For example, if you look at the code below hidden method is used to clarify which HTTP verb should be used in this case PUT and what if I remove it and try to update the data will it be possible.
The code:
#extends('layouts.app')
#section('content')
<h1>Income</h1>
<br>
{!! Form::open(['action'=>['IncomeController#update',$income->id], 'method' =>'POST']) !!}
<div class="form-group">
{{Form::label('Title', 'Title')}}
{{Form::text('Title', $income->Title, ['class' =>'form-control', 'placeholder' =>'Enter title'])}}
</div>
**{{Form::hidden('_method', 'PUT')}}**
{{Form::submit('Create', ['class'=>'btn btn-primary'])}}
{!! Form::close() !!}
#stop
suppose if you have Route like this
Route::put('income/update/{id}', 'IncomeController#update');
Route::delete('income/delete/{id}', 'IncomeController#delete');
Then you can replace your route with this
Route::post('income/update/{id}', 'IncomeController#update');
Route::post('income/delete/{id}', 'IncomeController#delete');
And then change your form like this (Just remove the hidden field)
#extends('layouts.app')
#section('content')
<h1>Income</h1>
<br>
{!! Form::open(['action'=>['IncomeController#update',$income->id], 'method' =>'POST']) !!}
<div class="form-group">
{{Form::label('Title', 'Title')}}
{{Form::text('Title', $income->Title, ['class' =>'form-control', 'placeholder' =>'Enter title'])}}
</div>
{{Form::submit('Create', ['class'=>'btn btn-primary'])}}
{!! Form::close() !!}
#stop

Laravel how to echo selected a value in a dropdown using blade when updating a specific resource

I want to echo the selected value when I edit a specific resource in my table. When I edit the specific resource it should display the current data in my dropdown but in the real scenario it displays the first one on the list which is wrong. So how can I echo the selected value in the options of the dropdown using blade in laravel?
Here is some sample of my code in the view below
<!-- Shows Field -->
<div class="form-group col-sm-6">
{!! Form::label('show_id', 'Shows:') !!}
{!! Form::select('show_id', $shows, $shows, ['class' => 'form-control input-md','required'])!!}
</div>
{{-- {{ $channelshows->channel->name }} --}}
<!-- Client Id Field -->
<div class="form-group col-sm-6">
{!! Form::label('channel_id', 'Channels:') !!}
{!! Form::select('channel_id', $channel, $channel, ['class' => 'form-control input-md','required'])!!}
</div>
<!-- Submit Field -->
<div class="form-group col-sm-12">
{!! Form::submit('Save', ['class' => 'btn btn-primary']) !!}
Cancel
</div>
and here is the code in my controller below.
public function edit($id)
{
$channelshows = $this->channelshowsRepository->findWithoutFail($id);
$shows = Show::pluck('name', 'id');
$channel = Channel::pluck('name', 'id');
if (empty($channelshows)) {
Flash::error('Assigned show not found');
return redirect(route('admin.channelshows.index'));
}
return view('admin-dashboard.channelshows.edit', compact('shows', $shows), compact('channel', $channel))->with('channelshows', $channelshows);
}
Everything here works fine even if I updated the specific resource. I just want to auto populate or select the current value of the resource that I will update because when I edit the specific resource it shows the first one on the list.
Am I going to use an #if statement in blade? But how can I do it using the blade template in my select form. Can somebody help me?
Appreciate if someone can help.
Thanks in advance.
Here is an example:
Open form:
{{ Form::model($service, array('route' => array('services.update', $service->id))) }}
Select form field:
<div class="form-group">
{{ Form::label('Related Agreement') }}
{{ Form::select('agreement', $agreementsList, null, array('class'=>'form-control', 'placeholder'=>'Please select ...')) }}
</div>
In Controller:
$agreementsList = Agreement::all()->sortBy('name', SORT_NATURAL | SORT_FLAG_CASE)->pluck('name', 'id');
(Include this when passing data to your view)

How to debug "Parse error: syntax error, unexpected '<', expecting ']'" in Laravel?

I'm trying to create a form that list the cars in a cars table and if clicked, sends into another form which is based on a DB query that returns the data of the chosen car (identified by $modelesc). This form sends the data to a "orders" table.
I'm now getting the following error in orders.blade.php:
Parse error: syntax error, unexpected '<', expecting ']'
I don't understand why I'm getting '<'; I don't see this in the code!
This is my code so far:
CarController
function catalog() {
$cars = DB::table('cars')->get();
return view('catalog', compact('cars'));
}
function orders($modelesc=null) {
$cars = DB::table('cars')->where('Model', '=', '$modelesc');
return view('orders', compact('cars'));
}
Catalog.blade.php
#foreach($cars as $car)
{!! Form::open(array('action' => 'CarController#orders', 'method' => 'GET')) !!}
{!! Form::hidden('$modelesc', $car->Model) !!}
{!! Form::submit($car->Model) !!}
{!! Form::close() !!}
#endforeach
Orders.blade.php
{!! Form::open(array('action' => 'index', 'method' => 'POST')) !!}
{!! Form::text('Model', $car->Model) !!}
{!! Form::hidden(users_id, Auth::user()->id) !!}
{!! Form::hidden(Fabrication_date, date(Y-m-d)) !!}
{!! Form::select('Colour', [
#foreach($colours as $colour)
'$colour->Colour' => '$colour->Colour'
#endforeach
]) !!}
{!! Form::hidden(Order_status_id, '1' !!}
{!! Form::close() !!}
This is the structure of the orders table. The *_id fields come from other tables, and I want to fill some values of the forms with the relevant entry (id, users_id, Model, Fabrication_date, Colour_id, Order_status_id).
Firstly you need to wrap the Form names within quotes, the Order Status ID was also missing a closing bracket:
{!! Form::hidden('users_id', Auth::user()->id) !!}
{!! Form::hidden('Fabrication_date', date('Y-m-d')) !!}
{!! Form::hidden('Order_status_id', '1') !!}
Next, if $colours is a collection you can do the following in Laravel 5.4 (I'm unsure which version you're using)
{!! Form::select('Colour', $colours->pluck('Colour')) !!}
If you're on Laravel 5.1 or prior, you'll do the following:
{!! Form::select('Colour', $colours->lists('Colour')) !!}
This is because the lists method was removed in 5.2.
#pseudoanime is also correct with his answer, the database call needs the get method adding
try changing $cars = DB::table('cars')->where('Model', '=', '$modelesc');
$cars = DB::table('cars')->where('Model', '=', $modelesc)->get();
Your orders method in your CarController doesn't set $cars to what you'd think; without calling get(), it'll be an instance of Builder instead of an array! Furthermore, you're only fetching cars where the model equals the string "$modelesc" instead of the value of $modelesc.
Furthermore, in your orders.blade.php file, you seem to reference a $colours variable, but that doesn't get passed down in your CarController.
Change your orders method to the one below:
public function orders($modelesc = null)
{
$cars = DB::table('cars')
->where('Model', $modelesc)
->get();
$colours = DB::table('colours')->get()->pluck('Colour');
return view('orders', compact('cars', 'colours'));
}
There is also an issue with your Form::select call in your orders.blade.php file; the Blade template directives (#foreach, #endforeach) are only for the "HTML" portion of the Blade file. Since we called pluck() on the Collection of colours in the CarController, we can simply pass in $colours for that method.
{{-- Incorrect --}}
{!! Form::select('Colour', [
#foreach($colours as $colour)
'$colour->Colour' => '$colour->Colour'
#endforeach
]) !!}
{{-- Correct --}}
{!! Form::select('Colour', $colours) !!}
You also appear to be using constants in your Form builders (instead of strings with quotes); these should be strings only.
{!! Form::open(['action' => 'index', 'method' => 'POST']) !!}
{!! Form::text('Model', $car->Model) !!}
{!! Form::hidden('users_id', Auth::user()->id) !!}
{!! Form::hidden('Fabrication_date', date('Y-m-d')) !!}
{!! Form::select('Colour', $colours) !!}
{!! Form::hidden('Order_status_id', '1') !!}
{!! Form::close() !!}

Getting information from one table and saving the returned information in new table - Laravel 5.2

I'm making a school system for my school and I have this problem in which I'm stuck for days. In my app I have users with type admin, teacher and student. The admin creates all the users and all the other information. Now I'm making the teacher panel in which the teacher will be able to add marks for the students and later they will be displayed in the student panel.
So in first place when the teachers get into their account he will be able to pick a class which he teaches and the subjects which he teaches, for that case I have table - class_subjects in which I'm saving the teacher_id, subject_id and class_id from the admin panel. I'm calling this here, in my teacher panel, and it seems to work just fine, because I see the exact classes and subjects I need. After that I need to make a post query with these both picked from the teacher and in return to get all the students from the picked class + the picked subject, that also works exactly how I want it. So what I am returning is a new blade with arrays with information from the table class_subject, from this returned arrays the teacher need to pick information, and here in text field he must add his mark for the student he picks. After that I need to save the picked information in new table called student_marks with fields student_id, subject_id, mark_type_id, mark.
My question is how the save this information (that the teacher picks) in the new table (student_marks)?
I'm posting the controller:
class AccountController extends Controller
{
public function getIndex() {
$user = Auth::user();
$classStudent = ClassSubject::where('teacher_id','=',$user->id)->get()->lists('class_id');
$userSubject = ClassSubject::where('teacher_id','=',$user->id)->get()->lists('subject_id');
return view('educator.account.account',[
'user' => $user,
'userTeacher'=> $classStudent,
'userSubject'=> $userSubject,
]);
}
public function postIndex(Request $request) {
ClassSubject::where(
'subject_id','=',$request->get('userSubject'),
'class_id','=',$request->get('userClass')
);
$user = Auth::user();
$markType = MarkType::lists('type');
$sub = Subject::where('id','=',$request->get('userSubject'))->get()->lists('name');
$stu = User::where('class_id','=',$request->get('userClass'))
->orderBy('first_name', 'asc')->get()->lists('full_name');
return view('educator.account.input', [
'user' => $user,
'studentss'=> $stu,
'markType' => $markType ,
'sub'=> $sub,
}
I know its a bit twisted but I'm really stuck in here and I will be really grateful if someone can finally help me with this. If something is unclear, please ask.
educator.account.account (first blade)
#extends('teacher-app')
#section('teacher-content')
<div class="col-md-6">
{!! Form::open(['method' => 'post', 'class' => 'form-horizontal']) !!}
<div class="form-group">
{!! Form::label('profile_id','Избери клас:', ['class' => 'control-label col-md-4']) !!}
<div class="col-md-3">
{!! Form::select('userClass', $userTeacher, null, ['class'=>'form-control']) !!}
</div>
</div>
<br>
<div class="form-group">
{!! Form::label('profile_id','Избери предмет:', ['class' => 'control-label col-md-4']) !!}
<div class="col-md-3">
{!! Form::select('userSubject', $userSubject, null, ['class'=>'form-control']) !!}
</div>
</div>
<div align="center">
{!! Form::submit('Избери', ['class' => 'btn btn-default']) !!}
</div>
{!! Form::close() !!}
#stop
</div>
educator.account.input (second blade)
#extends('teacher-app')
#section('teacher-content')
<div class="col-md-8">
{!! Form::open(['method' => 'post', 'class' => 'form-horizontal']) !!}
<div class="form-group">
{!! Form::label('profile_id','Ученик:', ['class' => 'control-label col-md-4']) !!}
<div class="col-md-3">
{!! Form::select('userStu', $studentss, null, ['class'=>'form-control']) !!}
</div>
</div>
<div class="form-group">
{!! Form::label('profile_id','Оценка:', ['class' => 'control-label col-md-4']) !!}
<div class="col-md-2">
{!! Form::text('mark',null, ['class'=>'form-control']) !!}
</div>
</div>
<div class="form-group">
{!! Form::label('profile_id','Тип оценка:', ['class' => 'control-label col-md-4']) !!}
<div class="col-md-3">
{!! Form::select('markType', $markType, null, ['class'=>'form-control']) !!}
</div>
</div>
<div class="form-group">
{!! Form::label('profile_id','Предмет:', ['class' => 'control-label col-md-4']) !!}
<div class="col-md-3">
{!! Form::select('stuSub', $sub, null, ['class'=>'form-control']) !!}
</div>
</div>
<br>
<div align="center">
<button type="button" class="btn btn-default">Назад</button>
{!! Form::submit('Запиши', ['class' => 'btn btn-default']) !!}
</div>
{!! Form::close() !!}
</div>
#stop
When they submit the form for the student rating, you'll have a route similar to this to post to:
class AccountController extends Controller {
public function markStudent(Request $request)
{
// get request data
$mark = $request->input('mark');
$subject_id = $request->input('stuSub');
$mark_type = $request->input('markType');
$student_id = $request->input('userStu');
// get the existing record or create a new, empty record
$student_mark = StudentMark::firstOrNew(compact('student_id', 'subject_id'));
// add the updated data to the model
$student_mark->fill(compact('mark_type', 'mark'));
// persist to database
$student_mark->save();
// redirect or do whatever you want after request completion...
}
}
This above code assumes you only want one entry per student, per subject (ie. a unique index on both these columns).
I would also recommend that you validate the data before inserting it, either by doing so before the StudentMark::firstOrNew() or by creating a custom request object with validation.

Categories