so i have a form that input data with <option>. the value is come from one database i provide. ( i can make the value from blade.php but the requirement require it from db). and the form will send the data to the main database. i've already make the view and the <option> work. but the trouble comes when i want to submit the data to the main database.
-the main db = blogs ( target column = 'sistem')
-the option db = sistems ( source column = 'nama')
the goal is the value of 'nama' passed to the 'sistem'
this is the view form
<form action="/" method="post" enctype="multipart/form-data">
// .......
// .......
<select name="sistem[]" id="tag_select">
<option value="0"> Tidak Ada </option>
#foreach ($sistems as $sistem)
<option value="{{$sistem->id}}"> {{$sistem->nama}}</option>
#endforeach
</select>
// .......
// .......
</form>
this is the store controller
public function store(Request $request)
{
// .........
// .........
$request -> sistem = array_unique(array_diff($request->sistem, [0]));
$blog -> sistem = $request -> sistem;
// .........
// .........
$blog -> save();
}
Like above and also are you shure that action "/" points to store method?
The save() method will save the changes that you make to your Eloquent model. Also you shouldn't need to edit the $request object to achieve the required result here.
Additionally you will need to ensure that this property on your model can be mass assigned (either in the $fillable array or excluded from the $guarded array on the $blog model).
$blog->sistem = array_unique(array_diff($request->sistem, [0]));
$blog->save();
I will show how i store things via post method and it works for me, but you must know that I am noob. Sory if what i writting is obvious for you, but cant do anything more :)
public function store(request $request)
{
$this->validatePost();
$post = new Post(request(
['title', 'excerpt','deadline']
));
$post->save();
return redirect(route('admin.posts'));
}
Related
I designed form to save data in Laravel
and this problem shows me the following error
Property [id] does not exist on this collection instance.
This is my Code
Controller
public function create ()
{
$post = Post::all();
return view ("post.create",compact('post'));
}
view create.blade.php
<form action="{{url()->action ('PostController#store', ['id'=>$post->id])}}" method="POST">
<input type="text" name="title" placeholder="Write Title">
<input type="text" name="body" placeholder="Write Body">
<input type="submit" value="Submit" name="submit">
</form>
I know the problem is here, but I don't know what I can do
'PostController#store', ['id'=>$post->id])}}" method="POST"
This will return the collection
$post = Post::all();
Instead, pass one object to the view by using
$post = Post::first();
or if u want to check particular post or any other condition you can use where clause to it..
eg: $post = Post::where('id',$user_id)->first(); // It will return single row...It will solve your problem
The problem is that you are sending a collection of Post models to your view. The $post variable contains a collection of Post models, which means that the collection will not have an id because it is a collection, not a single Post.
This:
$post = Post::all();
returns a collection.
Because this is a create method, you may wish to new up a Post model:
$post = new Post();
and add a few things to it and save it before sending to the view to get an id, OR, probably more useful: you can open the form without form-model binding since you don't actually have a Post model created yet -- just remove the ['id'=>$post->id] part since there is no post to have an id at the time the form is created.
You can make it look cleaner for the route.
web.php
Route::post('/myform/store', 'PostController#store')->name('post.store');
In your view, you can use the route name you just created.
<form action="{{ route('post.store', ['id' => $post->id]) }}" method="post">
But since you don't have column of 'id' in your Post then it returns the error you getting. Try creating a column 'id' first to resolve your problem.
I agree with #Watercayman on using model-binding instead, it's quick and makes the code more readable (and understandable too). Since Laravel quickly matches 'id' with unique id in the database. Take a look here for route parameters (how you can pass your data through URLs) and how to access your parameter here.
Using model binding will return you a collection.
public function store(Post $post)
Your $post variable is a collection so if you want to access your 'id' column you will do $post->id.
I'm currently following an online course on Laravel and I'm stuck at some relations. I've been looking for a bug last 3 hours and I'm unable to find it.
Basically, I have a form which user fills in, and a field where he loads a picture. For that picture I have two separate tables in database (photos - contains info about that photo & users - where photo_id should go). I followed all the steps in the course, but upon inserting picture in my database, relation doesn't work properly. I'll provide all the code I have down below.
User-Photo relation:
public function photo(){
return $this->belongsTo('App\Photo');
}
Saving form data in database and creating a picture in controller:
public function store(UsersRequest $request)
{
$input = $request->all();
if ($file = $request->file('photo_id')){
$name = time().$file->getClientOriginalName();
$file->move('images', $name);
$photo = Photo::create(['file'=>$name]);
$input['photo_id'] = $photo->id;
}
$input['password'] = bcrypt($request->password);
User::create($input);
return redirect('/admin/users');
}
This is my form input field for a picture:
<div class="form-group">
{!! Form::label('photo_id','Photo: ') !!}
{!! Form::file('photo_id', null , ['class'=>'form-control']) !!}
</div>
This code gives me no error whatsoever, but my relations don't work properly. Photos table doesn't get filled with any data, and in my Users table, column photo_id gets filled with a photo name, not an id as it should.
I'd really appreciate any help here. If I forgot to provide anything else here, please let me know.
Like Chung Nguyễn Trần I assume that the file upload isn't working properly.
Common mistake here is that the form was not opened with 'files' => true.
See also in the docs: https://laravelcollective.com/docs/5.2/html#file-input
So you should do:
echo Form::open(['url' => 'foo/bar', 'files' => true]);
From what you say, the Photo model should contain:
public function user()
{
return $this->belongsTo(User::class)
}
The User model should contain:
public function photo()
{
return $this->hasOne(Photo::class);
// Or maybe this should be photos() and
//return $this->hasMany(Photo::class);
}
A common gotcha with relationships is making sure the id fields are correct, eg: photos table has a user_id field
And when getting to grips with how relationships work, I'd recommended working with 'artisan tinker' so you can check these simply in isolation to the rest of the code.
I have a problem. I want to create a dropdown box with the name's from a table in my database andstore just an id from that name in other table (that id is a foreign key). I will show you my code
//acao model
public function estado() {
return $this->belongsTo('App\Estado');
}
//estado model<p>
public function acao()
{
return $this->hasMany('App\Acao');
}
AcaoController#Create:
public function create()
{
$estado = Estado::pluck('nome', 'id');
return view('Backoffice.acoes.criar_acao', compact('estado'));
}
AcaoController#Store:
$data = Acao::create([
'estado_id' => $data[estado_id],
]);
return redirect()->back();
}
This way the store doesn´t work and i think that this code doesn´t work with the relationship beetween acao and estado.
Can anyone help me please
Thanks
If I get it, you want to create an Acao Model among whit the Estado model.
First of all, you are using $data[estado_id] which is not initialized yet.
One simple solution is to create the Acao Object first, then accessing the property estado and create a new Instance of it. then save the model using eloquent:
$acao = new \App\Acao([/*your data*/]); // even a create is good
$acao->save(); // instead of save
$acao->estado()->create(
[/*estado data*/]
);
$acao->save();
I'm not sure what you are trying to achieve passing $data[estado_id] to the create method.
Edit
View
<select name="estado">
#foreach($estdo in $estados)
<option value="{{ $estado->id }}">{{$estado->nome}}</option>
#endforeach
</select>
Controller
Acao::create([
'estado_id' => $request->get('estado'),
]);
Or
$acao = new Acao;
$acao->estado_id = $request->get('estado');
$acao->save();
I am new in Laravel, i am trying to send all the values of a form to a database along with some other/modified values by using fill() in laravel 5.1.
here is how my controller looks like
public function store(Request $request)
{
$pages = new Pages; //i have a model with name Pages
$pages->fill(Input::all());
$pages->save();
return "data saved successfully";
}
Whenever i want to fill data into the table i get these values.
But before sending the data into database i want to mention some other attributes as well like $userid, change the datetime format to timestamp and then i want to send the data to database.
I want to use fill(Input::all()); method because if i need to add more field in the form, then i wont have to modify my controller or model.
Any suggestion will be helpful.Or any other best practice will also work.
Thank you! (in advance)
You can use eloquent
public function store(Request $request)
{
$request['user_id']='your id';
Pages::create($request->all());
return "data saved successfully";
}
If not eloquent
try this
$pages = new Pages; //i have a model with name Pages
$request['user_id']='your id';
$pages->fill(Input::all());
$pages->save();
return "data saved successfully";
I'm learning programming in yii2 framework, and I can't find out how to achieve specific task: I want to generate monthly statistic based on collected data. For this task, I need to generate form, that will wary on number of projects and users. For example:
Project 1: 500$
user1 field (in fields I want to put percentage of above value)
user2 field
user3 field
project 2: 1000$
user2 field
user3 field
And so on. It's easy to do in structural way, and save results in serialized form, but this way I'm unable to validate (for example if sum of values in fields for given project excess 100% and if there was error, after sending form, data would be erased).
Is it possible to achieve such task with Yii2?
edit:
currently I'm generating form this way:
controller:
$date = "2015-05";
$model = new Raport();
$invoices = Faktura::find()->where(['LIKE','paid_date', $date])->all();
$projects = array();
foreach($invoices as $invoice){
$id = $invoice->project_id;
$projects[$id]['faktury'][] = $invoice;
$projects[$id]['model']= Project::find()->where(['id'=>$invoice->project_id])->one();
$projects[$id]['value']+= $invoice->value_netto;
$projects[$id]['users']= '' ;
$checks = Check::find()->where(['project_id'=>$id])->all();
if (empty($checks)){
$projects[$id]['users']=$projects[$id]['model']->users;
}else {
foreach ($checks as $check) {
$projects[$id]['users'][$check->user->id] = $check->user;
}
}
}
view:
foreach ($projects as $key => $project) {
echo"<h2>".$project['model']->name."</h2>";
echo 'project value: '.$project['value'];
echo"<p>percentage value:</p>";
// echo"<pre>";
foreach ($project['users'] as $user) {
echo"<p>".$user->email."</p>";
echo "<input name='Raport[".$key."][".$user->id."]'>";
}
}
Yes it is possible, you are already creating the form in a dynamic way, create the model rules in the same dynamic way.
What you are trying to do is already done in the GII generator. Gii takes some fields (in GII's case database table fields) and it created the rules for the model and the fields on the form. In the end Gii writes those rules to the model file but you do not have to, you can just return that array as the result of the form. The same goes for the fields on the form, you can always have a
Basically you should create a Model that is not an Active Record model something like this https://github.com/yiisoft/yii2-app-advanced/blob/master/frontend/models/ContactForm.php. Instead of the way the rules function is created you should create that array based on "other things" (like your projects and users). You should create a function that does validation and that checks if the % is above 100 and tie it to the validation of some fields. A simple example would be
/**
* #inheritdoc
*/
public function rules()
{
$rules = [];
foreach(['p1', 'p2'] as $project) {
foreach(['u1', 'u2'] as $user) {
$rules[] = [$project.'_'.$user, "required"];
}
}
return $rules;
}
Afterwards, based on the same "other things" as a above you should create your form. Because the model and the view use the same fields it should all work out quite ok.
example view
<?php $form = ActiveForm::begin(); ?>
<?php
foreach(['p1', 'p2'] as $project) {
foreach(['u1', 'u2'] as $user) {
echo $form->field($model, $project.'_'.$user)->textInput()
}
}
?>
...................
<?php ActiveForm::end(); ?>