I'm using Laravel Collective and Laravel 5.2... I'm kinda new at this, so please if someone can help, I would be grateful.
I want to populate data to my view,
this is my controller:
<?php
namespace App\Http\Controllers\Admin;
use Illuminate\Http\Request;
use App\Http\Requests\SaveProfileRequest;
use App\Http\Requests;
use App\Clas;
use App\Profile;
use App\Http\Controllers\Controller;
class ClassesController extends Controller
{
public function getIndex() {
return view('admin.classes.list', [
'classes' => Clas::get()
]);
}
public function postIndex(Request $request) {
$class = Clas::create([
'profile_id'=>
'name' => $request ->input('class-name'),
]);
if($class->id) {
return redirect()->back()->with('message', [
'type'=> 'success',
'message' => 'Успешно записан нов клас!'
]);
}
return redirect()->back()->with('message', [
'type'=> 'danger',
'message' => 'Класът не е записан!'
]);
}
}
and in my View I have this
<div class="panel-body">
{!! Form::open(['method' => 'post', 'class' => 'form-horizontal']) !!}
<div class="form-group">
{!! Form::label('class-name','Клас:', ['class' => 'control-label col-md-3']) !!}
<div class="col-md-6">
{!! Form::text('class-name', null,['class' => 'form-control', 'placeholder' => 'например: 8а' ]) !!}
</div>
</div>
<div class="form-group">
{!! Form::label('profile-name','Избери профил:', ['class' => 'control-label col-md-3']) !!}
<div class="col-md-6">
{!! Form::select('profile-name') !!}
</div>
</div>
<div align="center">
{!! Form::submit('Запиши', ['class' => 'btn btn-default']) !!}
</div>
{!! Form::close() !!}
</div>
My question is how to pass the data? What should i write in the controller and in the view to connect them?
With regards to you comment.
This returns a list (array) to the view:
EDITED
public function getIndex() {
return view('admin.classes.list', [
//'classes' => Clas::get() //returns object, profile
'profiles' => Profile::lists('name', 'id'); //returns array
]);
}
To populate the select menu with lists of profile_id and name
NB: I changed profile-name to profile_id
<div class="form-group">
{!! Form::label('profile_id','Избери профил:', ['class' => 'control-label col-md-3']) !!}
<div class="col-md-6">
{!! Form::select('profile_id', $profiles) !!}
</div>
</div>
Then your postIndex:
public function postIndex(Request $request) {
$class = Clas::create([
'profile_id'=> $request->get('profile_id'),
'name' => $request ->input('class-name'),
]);
if($class->id) {
return redirect()->back()->with('message', [
'type'=> 'success',
'message' => 'Успешно записан нов клас!'
]);
}
return redirect()->back()->with('message', [
'type'=> 'danger',
'message' => 'Класът не е записан!'
]);
}
Take a look at https://laravel.com/docs/5.0/views#basic-usage
You can pass view variables by calling the function view( string $script, array $viewVariables )
Related
I have a search form to filter Multiple options from Multiple select boxes to filter out revenues. Here I have a 'Accounts" filter which I have (working right now) All accounts or a single account filter. What I need is to be able to Filter All, Single or multiple accounts based on user selection.
My Form:
{!! Form::open(['url' => 'incomes/revenues', 'role' => 'form', 'method' => 'GET']) !!}
<div class="pull-left">
<span class="title-filter hidden-xs">{{ trans('general.search') }}:</span>
<!--{!! Form::text('search', request('search'), ['class' => 'form-control input-filter input-sm', 'placeholder' => trans('general.search_placeholder')]) !!}-->
{!! Form::text('start', request('start'), ['class' => 'form-control input-filter input-sm','id' => 'datepicker', 'placeholder' => trans('general.date_placeholder')]) !!}
{!! Form::text('end', request('end'), ['class' => 'form-control input-filter input-sm','id' => 'datepicker1', 'placeholder' => trans('general.date_placeholder')]) !!}
{!! Form::select('customer', $customers, request('customer'), ['class' => 'form-control input-filter input-sm']) !!}
{!! Form::select('category', $categories, request('category'), ['class' => 'form-control input-filter input-sm']) !!}
{!! Form::select('account', $accounts, request('account'), ['multiple' => 'true','class' => 'form-control input-filter input-sm']) !!}
{!! Form::button('<span class="fa fa-filter"></span> ' . trans('general.filter'), ['type' => 'submit', 'class' => 'btn btn-sm btn-default btn-filter']) !!}
</div>
My Controller
public function index()
{
$revenues = Revenue::with(['account', 'category', 'customer'])->isNotTransfer()->collect(['paid_at'=> 'desc']);
$customers = collect(Customer::enabled()->pluck('name', 'id'))
->prepend(trans('general.all_type', ['type' => trans_choice('general.customers', 2)]), '');
$categories = collect(Category::enabled()->type('income')->pluck('name', 'id'))
->prepend(trans('general.all_type', ['type' => trans_choice('general.categories', 2)]), '');
$accounts = collect(Account::enabled()->pluck('name', 'id')->toArray())
->prepend(trans('general.all_type', ['type' => trans_choice('general.accounts', 2)]), '');
$transfer_cat_id = Category::transfer();
return view('incomes.revenues.index', compact('revenues', 'customers', 'categories', 'accounts', 'transfer_cat_id'));
}
My Filter
public $relations = [];
public function search($query)
{
return $this->whereLike('description', $query);
}
public function start($start)
{
return $this->where('paid_at','>=' , $start);
}
public function end($end)
{
return $this->where('paid_at','<=' , $end);
}
public function customer($customer)
{
return $this->where('customer_id', $customer);
}
public function category($category)
{
return $this->where('category_id', $category);
}
public function account($account)
{
return $this->where('account_id', $account);
}
}
Will be grateful if any one can show me how to achieve this. Thanks.
Trying to delete entries using the destroy method in Laravel controller.
public function destroy($id)
{
$university = University::find($id);
$university->delete();
return redirect('/universities');
}
And this is what i'm using in the view
{!!Form::open(['action' => ['UniversityController#destroy', $university->Id], 'method' => 'POST'])!!}
{{Form::hidden('_method', 'DELETE')}}
{{Form::submit('Delete', ['class' => 'btn btn-danger'])}}
{!!Form::close()!!}
Getting no errors and browser redirects after the button is activated as instructed, but the entry still remains in the veiw list and in the DB. Using MySQL.
Posting to the DB also works fine, but having same problems with update method. No errors and get redirected as I should but no update has happened.
public function update(Request $request, $id)
{
$this->validate($request, [
'Name' => 'required',
'Country' => 'required'
]);
$university = University::find($id);
$university->Name = $request->input('Name');
$university->Country = $request->input('Country');
$university->save();
return redirect('/universities');
}
And in view:
{!! Form::open(['action' => ['UniversityController#update', $university->Id], 'method' => 'POST']) !!}
<div class="form-group">
{{Form::label('Name', 'Name')}}
{{Form::text('Name', $university->Name, ['class' => 'form-control', 'placeholder' => 'Name'])}}
</div>
<div class="form-group">
{{Form::label('Country', 'Country')}}
{{Form::text('Country', $university->Country, ['class' => 'form-control', 'placeholder' => 'Country'])}}
</div>
{{Form::hidden('_method', 'PUT')}}
{{Form::submit('Submit', ['class' =>'btn btn-primary'])}}
{!! Form::close() !!}
Also tried running without the hidden form methods, but same result.
My routes:
Route::get('/universities', 'UniversityController#index');
Route::get('/universities/create', 'UniversityController#create');
Route::get('/universities/{id}/edit', 'UniversityController#edit');
Route::put('/universities/{id}', 'UniversityController#update');
Route::post('/universities/create', 'UniversityController#store');
Route::delete('/universities/{id}', 'UniversityController#destroy');
Solved by setting public $primaryKey = 'Id'; in the model.
I am in a bit of I a fix. I am trying to submit a form using Ajax. Now when I do this without creating the laravel default auth scaffold it works fine, but if add the auth scaffold it fails. I have tried all I can but can't seem to get it to submit.
Here is my code:
controller to send mail --
namespace App\Http\Controllers;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\Response;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Validator;
use Illuminate\Http\Request;
class MailController extends Controller
{
//
public function index(Request $request)
{
if ($request->ajax()) {
$validator = Validator::make($request->all(), [
'first_name' => 'required',
'last_name' => 'required',
'email' => 'required|email',
'mymessage' => 'required',
'g-recaptcha-response' => 'required|captcha',
]);
if ($validator->fails()) {
return redirect()->back()
->withErrors($validator)
->withInput();
} else {
// get input fields values
$data = [
'firstName' => $request->input('first_name'),
'lastName' => $request->input('last_name'),
'email' => $request->input('email'),
'mymessage' => $request->input('mymessage'),
];
Mail::send('emails.email', $data, function ($message) {
official email
$message->to('xxxxxxxxx#gmail.com', 'My Name')->subject('Information');
});
return response()->json([
'responseText' => 'Mail was sent!'], 200);
}
} else {
return View('fail')->render();
}
}
}
The Route files:
Route::get('/', function () {
return view('welcome');
});
Route::post('/mail', [
'as' => 'mail',
'uses' => 'MailController#index'
]);
Auth::routes();
Route::get('/home', 'HomeController#index');
Ajax code:
$(document).ready(function() {
var options = {
beforeSubmit: validate,
url: '/mail',
data: $(this).serialize(),
type: 'POST',
dataType: 'json',
clearForm: true,
success: great,
error: lost
};
$('#footer-form').ajaxForm(options);
});
function validate(formData, jgForm, options) {
for (var i = 0; i < formData.length; i++) {
if (!formData[i].value) {
alert('Please enter a value for all fields');
return false;
}
}
}
function great(responseText, statusText, formData) {
// prevent multiple form submission
$('#mail_btn').prop('disabled', true);
// show alert on success
$(".alert-success").prop("hidden", false);
// remove mail error information if displayed
$(".alert-info").prop("hidden", true);
// reset google recaptcha
grecaptcha.reset();
}
function lost(formData) {
// prevent multiple form submission
$('#mail_btn').prop('disabled', false);
$(".alert-info").prop("hidden", false);
}
My form code:
<div class="col-sm-6">
<div class="footer-content" id="myfooter">
{!! Form::open(['action' => 'MailController#index', 'method' => 'post', 'role' => 'form', 'id' => 'footer-form']) !!}
<div class="form-group has-feedback">
{!! Form::label('first_name', null, ['class' => 'sr-only']) !!}
{!! Form::text('first_name', null, ['class' => 'form-control', 'placeholder' => 'First Name']) !!}
<i class="fa fa-user form-control-feedback"></i>
#if($errors->has('first_name'))
{{ $errors->first('first_name') }}
#endif
</div>
<div class="form-group has-feedback">
{!! Form::label('last_name', null, ['class' => 'sr-only']) !!}
{!! Form::text('last_name', null, ['class' => 'form-control', 'placeholder' => 'Last Name']) !!}
<i class="fa fa-user form-control-feedback"></i>
#if($errors->has('last_name'))
{{ $errors->first('last_name') }}
#endif
</div>
<div class="form-group has-feedback">
{!! Form::label('email', null, ['class' => 'sr-only']) !!}
{!! Form::email('email', null, ['class' => 'form-control', 'placeholder' => 'Email address']) !!}
<i class="fa fa-envelope form-control-feedback"></i>
#if($errors->has('email'))
{{ $errors->first('email') }}
#endif
</div>
<div class="form-group has-feedback">
{!! Form::label('mymessage', null, ['class' => 'sr-only']) !!}
{!! Form::textarea('mymessage', null, ['class' => 'form-control', 'rows' => 8, 'cols' => 3, 'placeholder' => 'Message']) !!}
<i class="fa fa-pencil form-control-feedback"></i>
#if($errors->has('mymessage'))
{{ $errors->first('mymessage') }}
#endif
</div>
<div class="form-group has-feedback">
{!! app('captcha')->display() !!}
</div>
{!! Form::submit('Send', ['class' => 'btn btn-default', 'id' => 'mail_btn']) !!}
{!! Form::close() !!}
<div class="alert alert-success" id="mail_alert" role="alert" hidden>
Mail Sent!
</div>
<div class="alert alert-info" id="mail_info" role="alert" hidden>
Mail Sending Error!
</div>
</div>
</div>
Error message:
Failed to load resource: the server responded with a status of 401 (Unauthorized)
The problem was that I was using mailgun sandbox account hence I was only able to send mail when I use the laravel app with the auth scaffold include with the auth scaffold the app would allow as mailgun sandbox account don't send any reponse.
Solution was to use regular gmail send it and it responded as expected and the mail went through.
I am trying to set up a contact form on a one page site using laravel, I can't seem to be able to get the form to validate the user input and show any errors that the form might have.
email.blade.php:
<ul>
#foreach($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
{!! Form::open(['route' => 'mail', 'method' => 'post', 'role' => 'form', 'id' => 'footer-form']) !!}
<div class="form-group has-feedback">
{!! Form::label('first_name', null, ['class' => 'sr-only']) !!}
{!! Form::text('first_name', null, ['class' => 'form-control', 'placeholder' => 'First Name']) !!}
<i class="fa fa-user form-control-feedback"></i>
#if($errors->has('first_name'))
{{ $errors->first('first_name') }}
#endif
</div>
<div class="form-group has-feedback">
{!! Form::label('last_name', null, ['class' => 'sr-only']) !!}
{!! Form::text('last_name', null, ['class' => 'form-control', 'placeholder' => 'Last Name']) !!}
<i class="fa fa-user form-control-feedback"></i>
#if($errors->has('last_name'))
{{ $errors->first('last_name') }}
#endif
</div>
<div class="form-group has-feedback">
{!! Form::label('email', null, ['class' => 'sr-only']) !!}
{!! Form::email('email', null, ['class' => 'form-control', 'placeholder' => 'Email address']) !!}
<i class="fa fa-envelope form-control-feedback"></i>
#if($errors->has('email'))
{{ $errors->first('email') }}
#endif
</div>
<div class="form-group has-feedback">
{!! Form::label('textarea', null, ['class' => 'sr-only']) !!}
{!! Form::textarea('textarea', null, ['class' => 'form-control', 'rows' => 8, 'placeholder' => 'Message']) !!}
<i class="fa fa-pencil form-control-feedback"></i>
#if($errors->has('textarea'))
{{ $errors->first('textarea') }}
#endif
</div>
{!! Form::submit('Send', ['class' => 'btn btn-default']) !!}
{!! Form::close() !!}
Route: web.php:
Route::get('/ensignhospital', [
'as' => 'home',
'uses' => 'HomeController#home'
]);
Route::group(['before' => 'guest'], function () {
/*
* CSRF Protection
*
* */
Route::group(['before' => 'csrf'], function () {
Route::post('/ensignhospital', [
'as' => 'mail',
'uses' => 'HomeController#postSendMail'
]);
});
});
controller to handle for request:
class HomeController extends Controller {
public function home(){
return View('welcome');
}
public function postSendMail(ContactFormRequest $request){
if($request->fails()){
return Redirect::route('')
->withErrors()
->withInput();
}else{
return View('passed');
}
}
}
The form request validator class:
class ContactFormRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [
//
'first_name' => 'required',
'last_name' => 'required',
'email' => 'required|email',
'message' => 'required'
];
}
}
Problem the form does not validate when I don't enter a valid input. I need the form to validate user input and remain at the form position on the web page.
please note:
I used a .htaccess file to get the site which is on my computer to display the site root as localhost/mylaravelproject rather than the usual localhost/mylaravelprojec/public that one will normally see on a fresh install of laravel.
From the documentation here: https://laravel.com/docs/5.3/validation#form-request-validation
So, how are the validation rules evaluated? All you need to do is type-hint
the request on your controller method. The incoming form request is validated
before the controller method is called, meaning you do not need to clutter
your controller with any validation logic.
Laravel will never actually remain on the form. It will instead redirect, validate and then redirect back, with the errors. You do not need the check in your code if($request->fails()).
So my create news form is very simple:
<div class="row padding-10">
{!! Form::open(array('class' => 'form-horizontal margin-top-10')) !!}
<div class="form-group">
{!! Form::label('title', 'Title', ['class' => 'col-md-1 control-label padding-right-10']) !!}
<div class="col-md-offset-0 col-md-11">
{!! Form::text('title', null, ['class' => 'form-control']) !!}
</div>
</div>
<div class="form-group">
{!! Form::label('body', 'Body', ['class' => 'col-md-1 control-label padding-right-10']) !!}
<div class="col-md-offset-0 col-md-11">
{!! Form::textarea('body', null, ['class' => 'form-control']) !!}
</div>
</div>
<div class="col-md-offset-5 col-md-3">
{!! Form::submit('Submit News', ['class' => 'btn btn-primary form-control', 'onclick' => 'this.disabled=true;this.value="Sending, please wait...";this.form.submit();']) !!}
</div>
{!! Form::close() !!}
This is processed by NewsProvider:
public function store()
{
$validator = Validator::make($data = Input::all(), array(
'title' => 'required|min:8',
'body' => 'required|min:8',
));
if ($validator->fails())
{
return Redirect::back()->withErrors($validator)->withInput();
}
News::create($data);
return Redirect::to('/news');
}
But i have another field, not only title and text body in database, which is author_id and I have no idea how to add info, like the user id from currently authenticated user which wasnt supplied by form. I know how to add hidden input to form with user id, but then someone could change hidden field value. How do I do that correct way?
Maybe I have to edit my news eloquent model in some way, which is:
use Illuminate\Database\Eloquent\Model as Eloquent;
class News extends Eloquent {
// Add your validation rules here
public static $rules = [
'title' => 'required|min:8',
'body' => 'required|min:8',
];
// Don't forget to fill this array
protected $fillable = array('title', 'body');
}
You can always get the current authenticated user by Auth::user(). And you can also modify the $data array before passing it to create. Here's how you do it:
$data['author_id'] = Auth::user()->id;
News::create($data);
Also don't forget to add author_id to the fillable attributes
protected $fillable = array('title', 'body', 'author_id);