I have the following problem:
I want to insert into my database, with input fields.
Here is my html:
<div class="row">
<form action="{{ action('test#store') }}" method="post">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<div class="col-md-2 col-sm-2">
<label for="MtrNr">MtrNr:</label>
<input type="text" name="MtrNr" class="form-control">
</div>
<div class="col-md-2 col-sm-3">
<label for="Vorname">Vorname:</label>
<input type="text" name="Vorname" class="form-control">
</div>
<div class="col-md-2 col-sm-3">
<label for="Nachname">Nachname:</label>
<input type="text" name="Nachname" class="form-control" >
</div>
<div class="col-md-2 col-sm-2">
<label for="Klassenname">Klassenname:</label>
<input type="text" name="Klassenname" class="form-control">
</div>
<div class="col-md-2 col-sm-2">
<button class="btn btn-primary option-button button_rowAllign" type="submit">Schüler hinzufügen</button>
</div>
</form>
</div>
My controller:
public function store(Request $request)
{
$user = new schueler;
$user->MatNr = Input::get("MtrNr");
$user->vorname = Input::get("Vorname");
$user->nachname = Input::get("Nachname");
$user->klassenname = Input::get("Klassenname");
$user->save();
}
And here my routes:
Route::post("{{ action('test#store') }}", "test#store");
The thing is, that I already inserted into my database. But when i tried to
reproduce it, it doesn't work.
For local server I use xampp.
I hope you can help me.
The problem is that you only created a new Schueler object and gave the data to it. But you didn't save it in the database. You only made local changes.
Use this method to save.
public function store(Request $request) {
$user = new schueler;
$user->MatNr = Input::get("MtrNr");
$user->vorname = Input::get("Vorname");
$user->nachname = Input::get("Nachname");
$user->klassenname = Input::get("Klassenname");
$user->save();
}
Try changing your routes like this
Route::post("/test", "test#store"); // change /test to /anything you want
Before all make sure you have the database setup and there are all tables in that database like schuelers - For that do php artisan migrate
If you want to Insert record into the database you miss to add $user->save() in your controller
public function store(Request $request)
{
$user = new schueler;
$user->MatNr = Input::get("MtrNr");
$user->vorname = Input::get("Vorname");
$user->nachname = Input::get("Nachname");
$user->klassenname = Input::get("Klassenname");
$user->save();
}
I think something wrong with your route.
Route::post("{{ action('test#store') }}", "test#store");
Route should be something like below:
Route::post("schueler/store", "yourcontrollername#store");
//This is sample code, Please update with your one.
Related
i'm trying to upload some files via form to my db and also in the storage of my project
I did the following code on my homepage :
<x-layout>
#if (session('message'))
<div class="alert alert-success">{{session('message')}}</div>
#endif
<div class="container vh-100">
<div class="row h-100 w-100 align-items-center">
<div class="offset-3 col-6">
<form method="POST" action="{{route('transfer.submit')}}" class="card" enctype="multipart/form-data">
#csrf
<div class="border w-100" id="fileWrapper">
<div class="mb-3 w-100 h-100">
<input type="file" class="form-control w-100 h-100 fileInput" id="fileupload" name="files[]" multiple >
</div>
</div>
<div class="mb-3">
<label for="exampleInputPassword1" class="form-label">Invia file a </label>
<input type="email" class="form-control" id="exampleInputPassword1" name="recipient_mail">
</div>
<div class="mb-3">
<label for="exampleInputPassword1" class="form-label">La tua mail</label>
<input type="email" class="form-control" id="exampleInputPassword1" name="sender_mail">
</div>
<div class="mb-3">
<input type="text" class="form-control" id="title" name="title">
</div>
<div class="mb-3">
<textarea name="message" cols="50" rows="10"></textarea>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
</div>
</div>
</x-layout>
Then i done the following in my model :
protected $fillable = [
'recipient_mail',
'sender_mail',
'title',
'message',
'files[]'
];
and the following in my controller :
public function transferSubmit(TransferRequest $request){
$transfer = Transfer::create([
'sender_mail'=>$request->input('sender_mail'),
'recipient_mail'=>$request->input('recipient_mail'),
'title'=>$request->input('title'),
'message'=>$request->input('message'),
'files'=>$request->file('files[]')->store('public/files'),
]);
return redirect(route('home'))->with('message', 'File inviato con successo');
}
I havo also created the POST route and completed the migrations but, when i try to submit the form i get the following error :
Error Call to a member function store() on null
After this i tried the dd($request) ro check the data that i was actually passing to the Trasnfer class and i found that it is receiving correctly every data including the array of files.
Is there anybody that can help me to understand why i'm getting that error?
Thank you so much
You want store multiple files. And you will get an array. Then you have to iteratrate over your file array like that.
$files = [];
if($request->hasfile('files[]'))
{
foreach($request->file('files[]') as $file)
{
$files => $file->store('public/files'),
}
}
Important Note:
And don't forget the symlink before working with the Laravel storage.
php artisan storage:link
Updated
You iterate first then you have the file array which contains the paths to the images. you can then pass that to your model.
A little note: data coming from a form should always be validated.
public function transferSubmit(TransferRequest $request){
$files = [];
if($request->hasfile('files[]'))
{
foreach($request->file('files[]') as $file)
{
$files => $file->store('public/files'),
}
}
$transfer = Transfer::create([
'sender_mail'=>$request->input('sender_mail'),
'recipient_mail'=>$request->input('recipient_mail'),
'title'=>$request->input('title'),
'message'=>$request->input('message'),
'files'=> $files;
return redirect(route('home'))->with('message', 'File inviato con successo');
}
I am trying to get hold of Laravel framework and got stuck while retrieving the values from the page in a Database.
These are the snippets of my controller, routes, view part which might help in understanding what I am doing
web.php (for routes):
<?php
use Illuminate\Support\Facades\Route;
Route::resource('posts', 'PostController');
Postcontroller.php (just a snippet)
<?php
public function create()
{
//
return view('posts.create');
}
public function store(Request $request)
{
//
$this->validate($request , array(
'title' => 'required',
'body' => 'required'
));
$post = new Post;
$post->title = $request->title;
$post->body = $request->body;
$post->save();
return redirect()->route('posts.show', $post->id);
}
create.blade.php(for view)
<div class="row">
<div class="col-mid-8 col-md-offset-2" >
<h1>Create New Post</h1>
<hr>
<form route='posts.store' >
#csrf
<div class="form-group">
<label for="exampleInputEmail1">Email address</label>
<input type="email" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp">
<small id="emailHelp" class="form-text text-muted">We'll never share your email with anyone else.</small>
</div>
<div class="form-group">
<label for="exampleInputPassword1">Password</label>
<input type="password" class="form-control" id="exampleInputPassword1">
</div>
<div class="form-group form-check">
<input type="checkbox" class="form-check-input" id="exampleCheck1">
<label class="form-check-label" for="exampleCheck1">Check me out</label>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
</div>
The problem with your code is that you don't have name properties on your input, so nothing gets passed to your backend code.
Add name to your inputs like this (they need to be different, else they would get overwritten):
<input type="text" class="form-control" id="your-unique-input-id" name"your_unique_input_name">
Then, when you submit your form, the all the inputs that have name attribute in them will get passed to your backend method. You can then retrieve their value, by using the name you gave them earlier. So in this example:
$request->your_unique_input_name // Which will return anything that user typed in that field
Hello im developing a students CRUD in laravel but i have a problem saving the data in my db.
Here is the problem that laravel returns. SQLSTATE[HY000]: General error: 1364 Field 'name' doesn't have a default value
My store function.
public function store(Request $request)
{
$alumno = Alumno::create();
$alumno->fill($request->all());
$alumno->save();
return redirect('/alumnos');
}
My model:
class Alumno extends Model
{
protected $fillable = ['name','apellido','matricula','correo'];
}
My form:
<form action="/alumnos" method="post">
#csrf
<fieldset class="form-fieldset">
<div class="form-group">
<label class="form-label">Nombre<span class="form-required">*</span></label>
<input type="text" class="form-control" name="name" required/>
</div>
<div class="form-group">
<label class="form-label">Apellido<span class="form-required">*</span></label>
<input type="text" class="form-control" name="apellido" required/>
</div>
<div class="form-group">
<label class="form-label">Matricula<span class="form-required">*</span></label>
<input type="number" class="form-control" required name="matricula" />
</div>
<div class="form-group mb-0">
<label class="form-label">Correo Electronico<span class="form-required">*</span></label>
<input type="email" class="form-control" name="correo" required />
</div>
</fieldset>
<input type="submit" class="btn btn-primary" value="Guardar" />
</form>
What im doing wrong? Please help and thank you!!! :)
The problem is from the form action URL try to change the action to {{ action('YourController#store') }}
You should save data as below:
public function store(Request $request)
{
$alumno = new Alumno();
$alumno = $alumno->create($request->all());
return redirect('/alumnos');
}
and it will work fine.
You should add line to migration
$table->string('name')->nullable();
set form as above
<form action="{{action('YourController#store')}}">
For insert all request inputs
Alumno::create($request->all());
You solve this problem in two different ways
Your database structure has to be changed like below. Default field must be Null. Where description field is your database field.
Like below this
Open your model database/migrations/your_model then use like this code
Schema::table('your_model', function (Blueprint $table) {
$table->string('name')->nullable();
});
When I am submitting my forms in laravel, the user session expires and it logs out the current user. I thought it was a csrf token problem, so I disabled its verification but the problem persists.
My view
<form action="{{url('/save-user-details')}}" method="POST" enctype="multipart/form-data"
>
#csrf
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label>Primeiro Name</label>
<input type="text" class="form-control"
name="firstName" required>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label>Apelido</label>
<input type="text" class="form-control" name="lastName" required>
</div>
</div>
</div>
<button type="submit" class="button pull-right" value="">Actualizar Perfil</button>
</form>
My Route list
Route::post('/save-user-details', 'DashboardController#saveUser');
Route::get('/editar-usuario', 'DashboardController#editProfile');
My Controller
public function __construct()
{
$this->middleware('auth');
}
public function saveUser(Request $request){
$user_id = auth()->user()->id;
$user = User::find($user_id);
$detalhes = new Detalhesuser;
$detalhes->user_id = $user_id;
$detalhes->firstName = $request->input('firstName');
$detalhes->lastName = $request->input('lastName');
$detalhes->profissao = $request->input('profissao');
$detalhes->instituicao = $request->input('instituicao');
$detalhes->biografia = $request->input('biografia');
$detalhes->save();
$user->detalhesUser_id = $detalhes->id;
$user->save();
return redirect('/dashboard')->with('success', 'Detalhes salvos');
}
My sessions are being stored in a file. I tried to change it to database, the problem still persisted.
Any idea where I may be doing this wrong?
I wish to clarify the steps to get a new form properly submitted to my database using Laravel 5.2 and Bootstrap 3.
I have the login/register pages set up properly using Laravel's defaults, and they work fine. I now want to create a user profile page accessible to authenticated users. I am using one row in the database for all of their user info. Some fields were filled in during registration, and now I want them to have access to additional fields (while restricting access to certain registration fields like user name).
In the example code below, there are fields to upload a personal photo, enter a first name, and enter a last name. (None of these were done during registration.)
What I have already done (all code is below):
Create the view profile.blade.php
Create a controller profileController.php
Update routes.php in the controller directory.
A note:
When I try to submit the form as it appears below, I get, Type error: Argument 1 passed to App\Http\Controllers\ProfileController::update() must be of the type array, none given.
What are the next steps required to get this page working properly?
profile.blade.php:
#extends('layouts.app')
#section('content')
<div class="container" style="padding-top: 30px;">
<h1 class="page-header">User Profile</h1>
<div class="row">
<!-- left column -->
<div class="col-md-4 col-sm-6 col-xs-12">
<div class="text-center">
<i class="fa fa-user fa-5x"></i>
<h6>Please upload a photo...</h6>
<input type="file" class="text-center center-block well well-sm">
</div>
</div>
<!-- edit form column -->
<div class="col-md-8 col-sm-6 col-xs-12 personal-info">
<form class="form-horizontal" role="form" method="POST" action="{{ url('/profile') }}">
{!! csrf_field() !!}
<div class="form-group">
<label class="col-lg-3 control-label">First name:</label>
<div class="col-lg-8">
<input class="form-control" value="<?php echo Auth::user()->firstname; ?>" id="firstname" name="firstname" placeholder="First..." type="text">
</div>
</div>
<div class="form-group">
<label class="col-lg-3 control-label">Last name:</label>
<div class="col-lg-8">
<input class="form-control" value="<?php echo Auth::user()->lastname; ?>" id="lastname" name="lastname" placeholder="Last..." type="text">
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label"></label>
<div class="col-md-8">
<button type="submit" class="btn btn-primary">
<i class="fa fa-btn fa-user"></i>Submit
</button>
<span></span>
<input class="btn btn-default" value="Cancel" type="reset">
</div>
</div>
</form>
</div>
</div>
</div>
#endsection
profileController.php:
<?php
namespace App\Http\Controllers;
use App\Http\Requests;
use Illuminate\Http\Request;
class ProfileController extends Controller
{
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('auth');
}
/**
* Show the application dashboard.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
return view('profile');
}
protected function update(array $data)
{
return User::update([
'firstname' => $data['firstname'],
'lastname' => $data['lastname'],
]);
}
}
And I added the following in the routes middleware:
Route::get('/profile', 'ProfileController#index');
Route::post('/profile', 'ProfileController#update');
It's a protocol mismatch, since you're POSTing your form. You need to change your route to
route::post('/profile', 'ProfileController#index');
Using a validator is a great idea, since it will make sure that your input is exactly what you need it to be, and all required fields are filled out.
Your update function should look something like this:
public function update(Request $request)
{
$first_name = $request->input('firstname');
$last_name = $request->input('lastname');
$id = Auth::user()->id;
$user = \App\User::find($id);
$user->firstname = $first_name;
$user->lastname = $last_name;
$user->save();
return view('profile');
// Sanitize, validate, before you do ANYTHING with update
// Instead of returning the update result, you can instead show another view or forward them to another page.
}