Laravel View Composer - php

I'm following a tutorial for laravel and there is something that I don't understand. It's referred to using views composer.
-I have a template called from app/http/routes.php given an Url:
Route::get('cats/create', function(){return view('cats.create');});
this is cats/create.blade.php:
#extends('master')
#section('header')
<h2> Add a new cat </h2>
#stop
#section('content')
{!! Form::open(['url'=>'/cats']) !!}
#include('partials.forms.cat')
{!! Form::close() !!}
#stop
-This template includes another one (partial) which covers the HTML of a Form
<div class="form-group">
{!! Form::label('name','Name') !!}
<div class="form-controls">
{!! Form::text('name', null, ['class' => 'form-control']) !!}
</div>
</div>
<div class="form-group">
{!! Form::label('date_of_birth', 'Date of Birth') !!}
<div class="form-controls">
{!! Form::date('date_of_birth', null, ['class' => 'form-control']) !!}
</div>
</div>
<div class="form-group">
{!! Form::label('breed_id','Breed') !!}
<div class="form-controls">
{!! Form::select('breed_id', $breeds, null, ['class' => 'form-control']) !!}
</div>
</div>
{!! Form::submit('Save Cat', ['class' => 'btn-primary']) !!}
-Now uses a view composer in order to automatically fullfill the select element when this partial view is called. In AppServiceProvider:
public function boot(ViewFactory $view)
{
$view->composer('partials.forms.cat','Furbook\Http\Views\Composers\CatFormComposer');
}
4.- And this is that CatFormComposer
class CatFormComposer
{
protected $breeds;
public function __construct(Breed $breeds)
{
$this->breeds = $breeds;
}
public function compose(View $view) {
$breeds = $this->breeds;
$view->with('breeds', $breeds->lists('name', 'id'));
}
}
It works. What I don't get is, How is that $breeds parameter being passed to the constructor of the class?

All View Composers are resolved by laravel service container. So when you type-hint Breed $breeds laravel will use php reflection api to find the expected class and inject the instance of that class (in that case: Container will find Breed class , create new Breed and pass the instance on constructor).
Also for deeper understanding you can take look about service locator pattern

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>

Laravel Not posting to database

There is a bug in the code somewhere and I cant seem to find it , any help would be great. Its a simple form that stores to a DB.
The app is using laravel 5.2 and all that is needed is to collect data. when the submit button is hit on the form nothing!
route
Route::resource('/form' , 'PagesController');
controller only needs to indes, create and store , thats all the app needs to do.
<?php
namespace App\Http\Controllers;
use Request;
use App\Http\Requests;
use Data;
use App\Http\Requests\DataRequest;
use Carbon\Carbon;
class PagesController extends Controller
{
//Display Index
public function index()
{
return view ('welcome');
}
public function create()
{
return view ('create');
}
//Store Articles from form
public function store(DataRequest $request)
{
Data::create($request->all());
return redirect('create')->with('message' , 'Form submitted');
}
}
model uses a simple protected fields list and carbon to store timestamps
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use App\Http\Requests\DataRequest;
use Carbon\Carbon;
class Data extends Model
{
protected $fillable = [
'name',
'email',
'phone',
'company',
'addcomments',
'published_at',
];
protected $dates = ['published_at'];
//Get all published articles by date
public function scopePublished($query)
{
$query->where('published_at' , '<=' , Carbon::now());
}
//Get all unpublished or future articles
public function scopeUnpublished($query)
{
$query->where('published_at' , '>=' , Carbon::now());
}
// Set form to publish articles with a time and date in the Published_at field
public function setPublishedAtAttribute($date)
{
$this->attributes['published_at'] = Carbon::createFromFormat('Y-m-d' , $date);
}
}
form
{!! Form::open(['url' => 'form']) !!}
<div class="form-group">
{!! Form::label('name' , 'Name:') !!}
{!! Form::text('name', null , ['class' => 'form-control']) !!}
</div>
<div class="form-group">
{!! Form::label('email' , 'EMail:') !!}
{!! Form::text('email', null , ['class' => 'form-control']) !!}
</div>
<div class="form-group">
{!! Form::label('phone' , 'Phone Number:') !!}
{!! Form::text('phone', null , ['class' => 'form-control']) !!}
</div>
<div class="form-group">
{!! Form::label('company' , 'Company:') !!}
{!! Form::text('company', null , ['class' => 'form-control']) !!}
</div>
<div class="form-group">
{!! Form::label('addcomments' , 'Additional Comments:') !!}
{!! Form::textarea('addcomments', null , ['class' => 'form-control']) !!}
</div>
<div class="form-group">
{!! Form::submit('Submit Now', ['class' => 'btn btn-primary form-control']) !!}
</div>
{!! Form::close() !!}
So the issue was what was mentioned in the comments
use DATA;
to
use App\DATA;
and a mixture of a few little front end tweaks
all sorted

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.

Laravel form error message

I created a form for myself and it was working perfect. I did some rules like: if the user haven't wrote anything in the form or haven't wrote enough, give me some error message. This was working while used the 'former' package instead of the normally used 'form' package. Now I changed my form from "Former" to "Form" and now my error message are gone.. Well my form works and the rules too. If I don't write anything in my form or not at least 3 characters in the title/content section, it should redirect me with the errors I need. This works, but without the error message.
Here is my form:
#extends('master')
#section('content')
{!! Form::open(array('action' => 'Test\\TestController#store')) !!}
<div class="form-group">
{!! Form::label('thread', 'Title:') !!}
{!! Form::text('thread', null, ['class' => 'form-control']) !!}
</div>
<div class="form-group">
{!! Form::label('content', 'Body:') !!}
{!! Form::textarea('content', null, ['class' => 'form-control']) !!}
</div>
<div class="form-group">
{!! Form::submit('Add Thread', ['class' => 'btn btn-primary form-control']) !!}
</div>
{!! Form::close() !!}
#stop
My Controller#store function:
public function store(StoreRequest $request){
Thread::create($request->all());
return redirect(action('Test\\TestController#index'));
}
my Model:
<?php
namespace App\Models\Thread;
use Illuminate\Database\Eloquent\Model;
class Thread extends Model {
public $table = 'thread';
public $fillable = [
'thread',
'content',
];
}
and now the rules ( StoreRequest.php ) :
<?php
namespace App\Http\Requests\Store;
use App\Http\Requests\Request;
class StoreRequest extends Request {
public function rules() {
return [
'thread' => 'required|min:3',
'content' => 'required|min:3'
];
}
public function authorize() {
return true;
}
}
The error message was getting automaticly generated. Laravel did that for me. But not anymore.
Does anybody see why?
You can check if the form returned any error with something along these line:
#if ($errors->has('name')) <p class="help-block">{{ $errors->first('name') }}</p> #endif
Or you could use BootForm and let it handle everything for you

Post Method Not Working in Laravel

Form:
#section('form')
<div class="col-sm-4">
{!! Form::open() !!}
<div class="form-group">
{!! Form::label('name', 'Name:') !!}
{!! Form::text('name', 'Enter your name', ['class' => 'form-control']) !!}
</div>
<div class="form-group">
{!! Form::label('contact', 'Contact Number:') !!}
{!! Form::text('contact', 'Enter your contact number', ['class' => 'form-control']) !!}
</div>
<div class="form-group">
{!! Form::label('location', 'Location:') !!}
{!! Form::select('location', $locations, null, ['class' => 'form-control']) !!}
</div>
<div class="form-group">
{!! Form::label('service', 'Service Required:') !!}
{!! Form::select('service', $services, null, ['class' => 'form-control']) !!}
</div>
<div class="form-group">
{!! Form::submit('Just go Befikr >>', ['class' => 'btn btn-primary form-control']) !!}
</div>
{!! Form::close() !!}
</div>
#stop
routes.php:
<?php
Route::get('/', 'PagesController#index');
Route::post('/', 'PagesController#store');
PagesController.php
<?php namespace App\Http\Controllers;
use App\service_location;
use App\service_type;
use App\service_request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Request;
class PagesController extends Controller {
public function index()
{
$locations = service_location::lists('location_area', 'location_id');
$services = service_type::lists('service_desc', 'service_id');
return view('home.index', compact('locations','services'));
}
public function store()
{
$input = Request::all();
return $input;
}
}
Unfortunately, the code neither seems to return $input on the screen (implying that its not executing the store() function at all), nor does it throw any error/exception.
Can anyone please let me know why the post method is not resulting in appropriate results here?
Edit 1
I attempted to directly return via the route's inline function, but even that didn't work. Hence, now I'm pretty confident that the post method is not getting triggered at all. This is what I did to verify it:
Route::post('/', function()
{
return 'Hello';
});
Well, I figured the answer to my own question here.
Turns out, that in order to be able to execute a post request, you need to explicitly deploy a PHP server as:
php -s localhost:<AnyFreePort> -t <YourRootDirectory>
Whereas when I attempted to run it the first time through XAMPP, I was attempting to run the application out of sheer laziness, directly as:
http://localhost/myproject/public
which worked fine for a get request.
Even I had same issue, but your solution wasn't helpful for me since I was using Apache server instead of built in PHP server
then I found this solution which says just enter space to form action, weird issue and solution but it worked for me...
Eg.
{!! Form::open(array('url' => ' ', 'method' => 'post')) !!}

Categories