please help me to create a image upload system using Laravel 5.4 and also can save the filename at the database...
i can't find any related article about this and i also tried a youtube tutorial but it doesn't explain how filename transferred on the database, hope you can help mo on this
thank you...
here so far my code that i done...
$this->validate(request(), [
'article_banner' => 'required | mimes:jpeg,jpg,png | max:2000',
'article_title' => 'required|max:255',
'article_date' => 'required|date',
'article_content' => 'required',
]
);
$article_banner = $request->file('article_banner');
$article_title = $request->input('article_title');
$article_date = $request->input('article_date');
$article_content = $request->input('article_content');
return $article_banner;
}
also here's my error on validation every time i upload a docx... not image
here's the article_add.php
#extends('layouts.app')
#section('content')
<div class="container">
<div class="row">
<div class="col-md-8 col-md-offset-2">
<div class="panel panel-default">
<div class="panel-heading">User Management -> Edit User</div>
<div class="panel-body">
<form class="form-horizontal" role="form" method="POST" action="{{ route('article_add.post') }}" enctype="multipart/form-data">
{{ csrf_field() }}
<div class="form-group{{ $errors->has('article_banner') ? ' has-error' : '' }}">
<label for="article_banner" class="col-md-4 control-label">Article Banner: </label>
<div class="col-md-6">
<input id="article_banner" type="file" class="form-control" name="article_banner" required autofocus>
<p class="help-block">Example block-level help text here.</p>
#if ($errors->has('article_banner'))
<span class="help-block">
<strong>{{ $errors->first('article_banner') }}</strong>
</span>
#endif
</div>
</div>
<div class="form-group{{ $errors->has('article_title') ? ' has-error' : '' }}">
<label for="article_title" class="col-md-4 control-label">Article Title: </label>
<div class="col-md-6">
<input id="article_title" type="text" class="form-control" name="article_title" value="{{ old('article_title') }}" required autofocus>
#if ($errors->has('article_title'))
<span class="help-block">
<strong>{{ $errors->first('article_title') }}</strong>
</span>
#endif
</div>
</div>
<div class="form-group{{ $errors->has('article_date') ? ' has-error' : '' }}">
<label for="article_date" class="col-md-4 control-label">Article Date: </label>
<div class="col-md-6">
<input id="article_date datepicker" type="text" class="form-control datepicker" name="article_date" value="{{ old('article_date') }}" data-provide="datepicker" required autofocus>
#if ($errors->has('article_date'))
<span class="help-block">
<strong>{{ $errors->first('article_date') }}</strong>
</span>
#endif
</div>
</div>
<div class="form-group{{ $errors->has('article_content') ? ' has-error' : '' }}">
<div style="padding:10px;">
<label for="article_content">Article Date: </label>
<br />
<textarea id="content article_content" type="text" class="form-control" name="article_content" autofocus>{{ old('article_content') }}</textarea>
</div>
#if ($errors->has('article_content'))
<span class="help-block">
<strong>{{ $errors->first('article_content') }}</strong>
</span>
#endif
</div>
#if(session()->has('message'))
<div class="alert alert-success">
{{ session()->get('message') }}
</div>
#endif
#if(session()->has('errors'))
<div class="alert alert-danger">
{{ session()->get('errors') }}
</div>
#endif
<div class="form-group">
<div class="col-md-6 col-md-offset-4">
<button type="submit" class="btn btn-primary">
Submit
</button>
<a href="{{ url('article_management') }}" class="btn btn-primary">
Back
</a>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
#endsection
make one function as
public function uploadFiles($_destination_path, $images, $new_file_name) { //code to uplaod multiple fiels to path and return paths array wit file names
$file_name = str_replace(' ', '-', $new_file_name);
$paths = array('path' => $_destination_path . '/' . basename(Storage::disk($this->diskStorage)->putFileAs($_destination_path, $images, $file_name)),
'name' => pathinfo($file_name));
return $paths;
}
And pass required argument to it like as
$image = $request->file('image');
$fileName = $image->getClientOriginalName();
$destinationPath = '/images';
$img_path[] = $this->uploadFiles($destinationPath, $image, $fileName);
You will get required data in the img_path[] array variable.
public function feedbackPost(Request $request, $id)
{
$fileName1 = "";
$fileName2 = "";
$rules = array(
'conferencename' =>'required',
'yourname' =>'required',
'email' =>'required',
'objective' =>'required',
'results' =>'required',
'recommendations' =>'required',
'key_customers' =>'required',
'actions' =>'required',
'business_opportunities' =>'required',
'other_opportunities' =>'required',
'upload_leads' =>'mimes:csv,xls,xlsx',
'upload_attendees' =>'mimes:csv,xls,xlsx',
);
$validator = Validator::make($request->all(), $rules);
if ($validator->fails())
{
return back()->with('danger', 'File format not valid');
}
else
{
if($file=$request->hasFile('upload_attendees')) {
$file=$request->file('upload_attendees');
$fileName1=$file->getClientOriginalName();
if (!file_exists('uploads/feedback/attendees/'.$id.'')) {
mkdir('uploads/feedback/attendees/'.$id.'', 0777, true);
}
$destinationPath='uploads/feedback/attendees/'.$id.'';
$file->move($destinationPath,$fileName1);
}
if($file=$request->hasFile('upload_leads')) {
$file=$request->file('upload_leads');
$fileName2=$file->getClientOriginalName();
if (!file_exists('uploads/feedback/leads/'.$id.'')) {
mkdir('uploads/feedback/leads/'.$id.'', 0777, true);
}
$destinationPath='uploads/feedback/leads/'.$id.'';
$file->move($destinationPath,$fileName2);
}
$feedback = Feedback::insert([
'user_id' => $request->user_id,
'conferenceid' => $request->conferenceid,
'conferencename' =>$request->conferencename,
'yourname' =>$request->yourname,
'email' =>$request->email,
'objective' =>$request->objective,
'results' =>$request->results,
'recommendations' =>$request->recommendations,
'key_customers' =>$request->key_customers,
'actions' =>$request->actions,
'business_opportunities' =>$request->business_opportunities,
'other_opportunities' =>$request->other_opportunities,
'upload_attendees' =>$fileName1,
'upload_leads' =>$fileName2,
]);
}
return back()->with('success', 'Thanks! Your Feedback has been Submitted!');
}
This is how I did. You may try this.
Related
I am struggling to update data in the database with an edit form and couldn't find anything online that fits the logic of my setup.
I have a add button, delete button and an edit button. Adding and Deleting works but Editing does not update the data.
Any help would be appreciated as I have tried multiple methods with no success.
Thank you in advance.
View:
#extends('layouts.app')
#section('content')
<div class="container flex-center">
<div class="row col-md-8 flex-column">
<h1>Edit a link</h1>
#foreach ($links as $link)
<form action="{{ url('link/'.$link->id) }}" method="POST">
{!! csrf_field() !!}
#method('PUT')
#if ($errors->any())
<div class="alert alert-danger" role="alert">
Please fix the following errors
</div>
#endif
<h3 class="edit-link-title">{{ $link->title }}</h3>
{!! csrf_field() !!}
<div class="form-group{{ $errors->has('title') ? ' has-error' : '' }}">
<label for="title">Title</label>
<input type="text" class="form-control" id="title" name="title" placeholder="Title" value="{{ $link->title }}">
#if($errors->has('title'))
<span class="help-block">{{ $errors->first('title') }}</span>
#endif
</div>
<div class="form-group{{ $errors->has('url') ? ' has-error' : '' }}">
<label for="url">Url</label>
<input type="text" class="form-control" id="url" name="url" placeholder="URL" value="{{ $link->url }}">
#if($errors->has('url'))
<span class="help-block">{{ $errors->first('url') }}</span>
#endif
</div>
<div class="form-group{{ $errors->has('description') ? ' has-error' : '' }}">
<label for="description">Description</label>
<textarea class="form-control" id="description" name="description" placeholder="description">{{ $link->description }}</textarea>
#if($errors->has('description'))
<span class="help-block">{{ $errors->first('description') }}</span>
#endif
#endforeach
</div>
<button type="submit" class="btn btn-default submit-btn">Submit</button>
</form>
</div>
</div>
#endsection
web/route controller:
use Illuminate\Http\Request;
Route::post('/submit', function (Request $request) {
$data = $request->validate([
'title' => 'required|max:255',
'url' => 'required|url|max:255',
'description' => 'required|max:255',
]);
$link = tap(new App\Link($data))->save();
return redirect('/');
});
use App\Link;
Route::delete('/link/{link}', function (Link $link) {
// Link::destroy($link);
$link->delete();
return redirect('/');
});
Route::PUT('/link/{link}', function (Link $link) {
$link->update();
return redirect('/');
});
As a design pattern, it's often recommended to separate your controller from the routes. The reason your edit is not updating is that you're not providing the model with the data from the request:-
Route::PUT('/link/{link}', function (Request $request, Link $link) {
$request->validate([
'title' => 'required|max:255',
'url' => 'required|url|max:255',
'description' => 'required|max:255',
]);
$link->update($request->all());
return redirect('/');
});
In a controller, you could abstract away the validation logic to a validation helper function to avoid duplicating code.
Good luck!
I have problem with my laravel and sqlserver. Recently no problem with php pod because Ive use this sqlserver on my yii2 project and it work well.
try {
DB::connection()->getPdo();
if(DB::connection()->getDatabaseName()){
echo "Yes! Successfully connected to the DB: " . DB::connection()->getDatabaseName();
}
} catch (\Exception $e) {
die("Could not connect to the database. Please check your configuration.");
}
I also have tried db connection and it returned "Yes! Successfully connected to the DB: MyDB".
This is my controller
public function postsignup(Request $request){
$this->validate($request, [
'username' =>'required',
'email' =>'required',
'password' =>'required',
]);
try{
$users = new User;
$users->id = '15';
$users->username = $request->input('username');
$users->password_hash = bcrypt($request->input('password'));
$users->email = $request->input('email');
$users->save();
return redirect('/')->with('response','register success');
}
catch(\PDOException $e){
echo $e->getMessage();
}
}
my model
public $timestamps = false;
protected $fillable = [
'username', 'email', 'password_hash',
];
protected $hidden = [
'password', 'remember_token',
];
this is my view
#extends('layouts.app')
#section('content')
<div class="container">
<div class="row">
#if(session('response'))
<div class="col-md-8 alert alert-success">
{{session('success')}}
</div>
#endif
<div class="col-md-8 col-md-offset-2">
<div class="panel panel-default">
<div class="panel-heading">Register</div>
<div class="panel-body">
<form class="form-horizontal" method="post" action="{{route('account-create-post')}}">
{{ csrf_field() }}
<div class="form-group{{ $errors->has('name') ? ' has-error' : '' }}">
<label for="name" class="col-md-4 control-label">Name</label>
<div class="col-md-6">
<input id="name" type="text" class="form-control" name="username"
value="{{ old('name') }}" required autofocus>
#if ($errors->has('name'))
<span class="help-block">
<strong>{{ $errors->first('name') }}</strong>
</span>
#endif
</div>
</div>
<div class="form-group{{ $errors->has('email') ? ' has-error' : '' }}">
<label for="email" class="col-md-4 control-label">E-Mail Address</label>
<div class="col-md-6">
<input id="email" type="email" class="form-control" name="email"
value="{{ old('email') }}" required>
#if ($errors->has('email'))
<span class="help-block">
<strong>{{ $errors->first('email') }}</strong>
</span>
#endif
</div>
</div>
<div class="form-group{{ $errors->has('password') ? ' has-error' : '' }}">
<label for="password" class="col-md-4 control-label">Password</label>
<div class="col-md-6">
<input id="password" type="password" class="form-control" name="password" required>
#if ($errors->has('password'))
<span class="help-block">
<strong>{{ $errors->first('password') }}</strong>
</span>
#endif
</div>
</div>
<div class="form-group">
<label for="password-confirm" class="col-md-4 control-label">Confirm Password</label>
<div class="col-md-6">
<input id="password-confirm" type="password" class="form-control"
name="password_confirmation" required>
</div>
</div>
<div class="form-group">
<div class="col-md-6 col-md-offset-4">
<button type="submit" class="btn btn-primary">
Register
</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
#endsection
myroutes
Route::post('/signup', array(
'as' => 'account-create-post',
'uses' => 'UserController#postsignup'
));
Route::get('/signup', array(
'as' => 'account-create',
'uses' => 'UserController#getsignup'
));
This code are used to my signup. First, user fill the signup input field then hit register button to save their data to database but I know something wrong with my connection with database because this 500 error not appear if I comment $users->save() . I also have tried to retrive data from database with $users = User::all(); and this 500 error appear.
I hope some one ever faced this error and help me to solve this error so I can continue my work. Fyi I already do debug everywhere so I guess my codes are ok.
After 3 days finally I know why this 500 comes out. I recently tried to check db connection with error handling and it returned success massage, but when I tried to migrate schema from database, my cmd stop to respond, I realize something wrong with my db conf in config/database.php
'sqlsrv' => [
'driver' => 'sqlsrv',
'host' => 'my_IP',
'port' => 'my_Port',
'database' => 'DbName',
'username' => 'Db_Username',
'password' => 'Db_Password',
'charset' => 'utf8',
'prefix' => 'pos.',
],
the problem is very simple -_-, prefix contain "." . I remove it and everything work perfectly. huh awkward moment, thanks #madalinivascu for your fast respond +1 for you
I am learning Laravel and got stuck with one issue. I have created form with validation and all goes to database. Except my image_url with type="file"
<form method="POST" action="{{route('photos.store')}}" class="form-horizontal" enctype="multipart/form-data">
{{ csrf_field() }}
<div class="">
#component('components.back', ['url' => route('photos.index')])
#endcomponent
<hr>
</div>
<div class="form-all">
<ul class="form-section page-section">
<li class="form-line" data-type="control_image" id="id_1">
<div id="cid_1" class="form-input-wide">
<div style="text-align:center;">
<img alt="" class="form-image" style="border:0px;" src="" height="42px" width="42px" data-component="image">
</div>
</div>
</li>
<li class="form-line" data-type="control_text" id="id_12">
<div id="cid_12" class="form-input-wide">
<div id="text_12" class="form-html" data-component="text">
<p><span style="color:#363636;font-size:xx-large;">Įkelti nuotrauką</span></p>
</div>
</div>
</li>
<li class="form-group{{ $errors->has('title')?' has-error' : ''}}" id="id_7">
<label class="form-label form-label-top" id="label_7" for="title">Pavadinimas</label>
<div id="cid_7" class="form-input-wide">
<input id="title" type="text" name="title" value="{{ old('title') }}" class="form-control" placeholder="Pavadinimas">
#if ($errors->has('title'))
<span class="help-block">
<strong>
{{ $errors->first('title')}}
</strong>
</span>
#endif </div>
</li>
<li class="form-group{{ $errors->has('description')?
' has-error' : ''}}">
<label class="form-label form-label-top" id="label_5" for="description">Aprašymas</label>
<div id="cid_5" class="form-input-wide">
<input id="description" type="text" name="description" value="{{ old('description') }}" class="form-control" placeholder = "Aprašymas">
#if ($errors->has('description'))
<span class="help-block">
<strong>
{{ $errors->first('description')}}
</strong>
</span>
#endif
</div>
</li>
<li class="form-group {{ $errors->has('image_url')?
' has-error' : ''}}">
<label class="form-label form-label-top" id="label_11" for="image_url">Nuotrauka</label>
<div id="cid_11" class="form-input-wide">
<input id="image_url" type="file" name="image_url" value="{{ old('image_url') }}" class="form-control">
#if ($errors->has('image_url'))
<span class="help-block">
<strong>
{{ $errors->first('image_url')}}
</strong>
</span>
#endif
</div>
</li>
<li class="form-group {{ $errors->has('category_id') ? 'has-error': ''}}">
<label class="form-label form-label-top" id="label_11">Kategorija</label>
#if(isset($photo))
<select name="category_id" class="form-control">
<option value="">Pasirinkti kategoriją</option>
#foreach($categories as $category)
<option value="{{$category->id}}">{{$category->title}}</option>
#endforeach
</select>
#else
<select name="category_id" class="form-control">
<option value="">Pasirinkti kategoriją</option>
#foreach($categories as $category)
<option value="{{$category->id}}">{{$category->title}}</option>
#endforeach
</select>
#endif
#if($errors->has('category_id'))
<span class="help-block">
<strong>{{ $errors->first('category_id')}}</strong>
</span>
#endif
</li>
<li class="form-line" data-type="control_button" id="id_2">
<div id="cid_2" class="form-input-wide">
<div style="text-align:center;" class="form-buttons-wrapper">
<button id="input_2" type="submit" class="form-submit-button" data-component="button">
Patvirtinti
</button>
</div>
</div>
</li>
</ul>
</div>
and my Controller looks like this:
public function create()
{
$categories = Category::all();
return view('photo.create', compact('photo','categories'));
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$this->validate($request, [
'title' => 'required|min:3',
'image_url'=> 'required',
'category_id' => 'required',
]);
$photo = new Photo;
$photo->title = $request->input('title');
$photo->image_url = $request->input('image_url');
$photo->description = $request->input('description');
$photo->category_id = $request->input('category_id');
$photo->save();
$request->session()->flash('create', $request->title. "Sekmingai sukurta");
$path = $request->image_url->store('images');
return redirect()->route('photos.index');
}
and seeder:
public function __construct( Photo $photo, Category $category) {
$this->photo = $photo;
$this->category = $category;
}
public function run()
{
$categories_ids = $this->category->pluck('id');
DB::table('photos')->insert(
[
'title' => '',
'image_url' => '',
'description' => '',
'category_id' => $categories_ids->random()
]);
}
I understand that I should put some if into Controller telling "If its not text, but file- accept file". But I am not able to find answer online.
Thank you for your advises in advance.
You will get image name from $fileName = $request->image_url->store('images');
and note $fileName wil return folder name also images/2Q3J1gU3j8NkMgt5HtGurSDtu5BIbeATNZb13Ih3.jpeg
$photo = new Photo;
if ($request->hasFile('image_url')) {
$fileName = $request->image_url->store('images');
$photo->image_url = $fileName;
}
$photo->title = $request->input('title');
$photo->description = $request->input('description');
$photo->category_id = $request->input('category_id');
$photo->save();
$request->session()->flash('create', $request->title. "Sekmingai sukurta");
return redirect()->route('photos.index');
Admin login don't work and don't give me any error.
I have this routes in web.php file:
Auth::routes();
Route::prefix('admin')->group(function () {
Route::get('/login','Auth\AdminLoginController#showLoginForm')->name('admin.login');
Route::post('/login','Auth\AdminLoginController#login')->name('admin.login.submit');
Route::get('/','AdminController#getIndex')->name('admin.dashboard');
Route::get('/logout','Auth\AdminLoginController#logout')->name('admin.logout');
Route::post('/password/email','Auth\AdminForgotPasswordController#sendResetLinkEmail')->name('admin.password.email');
Route::get('/password/reset','Auth\AdminForgotPasswordController#showLinkRequestForm')->name('admin.password.request');
Route::post('/password/reset','Auth\AdminResetPasswordController#reset');
Route::get('/password/reset/{token}','Auth\AdminResetPasswordController#showResetForm')->name('admin.password.reset');
});
And this functions in controller(I only put here which have the problems)
public function showLoginForm()
{
return view('auth.adminlogin');
}
public function login(Request $request)
{
//validate the form data
$this->validate($request, [
'email' => 'required|email',
'password' => 'required|min:6'
]);
//attempt to log the user in
if (Auth::guard('admin')->attempt(['email' => $request->email, 'password' => $request->password], $request->remember)){
//if successful, then redirect to their intended location
return redirect('/admin');
}
return redirect()->back()->withInput($request->only('email','remember'));
}
And in resources/views/auth/adminlogin.blade.php i have this code:
#extends('backend.public.includes.head')
<body>
<div class="container">
<div class="row">
<div class="col-md-8 col-md-offset-2">
<div class="panel panel-default">
<div class="panel-heading">ADMIN Login</div>
<div class="panel-body">
<form class="form-horizontal" role="form" method="POST" action="{{ route('admin.login.submit') }}">
{{ csrf_field() }}
<div class="form-group{{ $errors->has('email') ? ' has-error' : '' }}">
<label for="email" class="col-md-4 control-label">E-Mail Address</label>
<div class="col-md-6">
<input id="email" type="email" class="form-control" name="email" value="{{ old('email') }}" required autofocus>
#if ($errors->has('email'))
<span class="help-block">
<strong>{{ $errors->first('email') }}</strong>
</span>
#endif
</div>
</div>
<div class="form-group{{ $errors->has('password') ? ' has-error' : '' }}">
<label for="password" class="col-md-4 control-label">Password</label>
<div class="col-md-6">
<input id="password" type="password" class="form-control" name="password" required>
#if ($errors->has('password'))
<span class="help-block">
<strong>{{ $errors->first('password') }}</strong>
</span>
#endif
</div>
</div>
<div class="form-group">
<div class="col-md-6 col-md-offset-4">
<div class="checkbox">
<label>
<input type="checkbox" name="remember" {{ old('remember') ? 'checked' : '' }}> Remember Me
</label>
</div>
</div>
</div>
<div class="form-group">
<div class="col-md-8 col-md-offset-4">
<button type="submit" class="btn btn-primary">
Login
</button>
<a class="btn btn-link" href="{{ route('admin.password.request') }}">
Forgot Your Password?
</a>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</body>
This was working days ago.. and now not, i'm looking all but don't find the error. In networking isn't showing anything and with a debug i don't see anything.
I try to reset password and when i reset it (i have a redirect in the function he redirect me good, only not working in normal login).
Errors aren't showed too
EDIT
Migrate file:
public function up()
{
Schema::create('admins', function (Blueprint $table) {
$table->increments('id');
$table->string('name',50)->unique();
$table->string('email',200)->unique();
$table->string('password');
$table->boolean('public')->default(true);
$table->rememberToken();
$table->timestamps();
});
}
Seed file:
private $arrayAdmins = array(
array(
'name' => 'Lluis',
'email' => 'lluis.puig#correo.biz',
'password' => 'correo1',
'public' => 1
)
);
public function run()
{
self::seedAdmins();
}
public function seedAdmins()
{
DB::table('admins')->delete();
foreach ($this->arrayAdmins as $admin)
{
$a = new Admin;
$a->name = $admin['name'];
$a->email = $admin['email'];
$a->password = $admin['password'];
$a->public = $admin['public'];
$a->save();
}
}
The admin login isn't working if i created with the seed. (So the problem i guess is with the "user created" with the seed.
I try to create one with php artisan tinker and it works.
SOLVED
I check the seed. The problem was de password isn't encrypted!
This line :
$a->password = $admin['password'];
Must be like this:
$a->password = bcrypt($admin['password']);
I'm currently trying to modify the laravel Auth two be able to register two different kinds of users, a seller and a buyer. Both have the same form, except one field, that only the seller has, called companyName.
So what I did is putting a dropdown for registration instead of the normal register button, this is what I got there:
<div class="dropdown">
<button class="btn btn-default dropdown-toggle" type="button" id="dropdownMenu1" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true">
Registrieren
<span class="caret"></span>
</button>
<ul class="dropdown-menu" aria-labelledby="dropdownMenu1">
<li>
Als Käufer
Als Händler
</li>
</ul>
</div>
Then I made a route for this two kinds of registrations, like this:
Route::get('/register/{userType}', 'Auth\RegisterController#showRegistrationForm');
In the controller then I simply overwrote this showRegistrationForm function to pass the userType into my view, just like that:
public function showRegistrationForm($userType)
{
return view('auth.register', ['userType'=> $userType]);
}
And in my view, I got this:
#extends('master')
#section('content')
<div class="container">
<div class="row">
<div class="col-md-8 col-md-offset-2">
<div class="panel panel-default">
<div class="panel-heading">Registrieren
als <?php if ($userType == 'customer') echo "Käufer";if ($userType == 'seller') echo "Verkäufer";?></div>
<div class="panel-body">
<form class="form-horizontal" role="form" method="POST" action="{{ url('/register') }}">
{{ csrf_field() }}
<div class="form-group{{ $errors->has('sex') ? ' has-error' : '' }}">
<label for="sex" class="col-md-4 control-label">Anrede</label>
<div class="col-md-6">
<select class="form-control" id="sex">
<option value="male">Herr</option>
<option value="female">Frau</option>
</select>
</div>
#if ($errors->has('sex'))
<span class="help-block">
<strong>{{ $errors->first('sex') }}</strong>
</span>
#endif
</div>
<div class="form-group{{ $errors->has('name') ? ' has-error' : '' }}">
<label for="firstName" class="col-md-4 control-label">Vorname</label>
<div class="col-md-6">
<input id="firstName" type="text" class="form-control" name="firstName"
value="{{ old('firstName') }}" required autofocus>
#if ($errors->has('firstName'))
<span class="help-block">
<strong>{{ $errors->first('firstName') }}</strong>
</span>
#endif
</div>
</div>
<div class="form-group{{ $errors->has('name') ? ' has-error' : '' }}">
<label for="name" class="col-md-4 control-label">Nachname</label>
<div class="col-md-6">
<input id="name" type="text" class="form-control" name="name"
value="{{ old('name') }}" required autofocus>
#if ($errors->has('name'))
<span class="help-block">
<strong>{{ $errors->first('name') }}</strong>
</span>
#endif
</div>
</div>
<?php if ($userType == 'seller'){ ?>
<div class="form-group{{ $errors->has('companyName') ? ' has-error' : '' }}">
<label for="companyName" class="col-md-4 control-label">Firmenname</label>
<div class="col-md-6">
<input id="companyName" type="text" class="form-control" name="companyName"
value="{{ old('companyName') }}" required autofocus>
#if ($errors->has('companyName'))
<span class="help-block">
<strong>{{ $errors->first('companyName') }}</strong>
</span>
#endif
</div>
</div>
<?php } ?>
<div class="form-group{{ $errors->has('email') ? ' has-error' : '' }}">
<label for="email" class="col-md-4 control-label">E-Mail Addresse</label>
<div class="col-md-6">
<input id="email" type="email" class="form-control" name="email"
value="{{ old('email') }}" required>
#if ($errors->has('email'))
<span class="help-block">
<strong>{{ $errors->first('email') }}</strong>
</span>
#endif
</div>
</div>
<div class="form-group{{ $errors->has('password') ? ' has-error' : '' }}">
<label for="password" class="col-md-4 control-label">Passwort</label>
<div class="col-md-6">
<input id="password" type="password" class="form-control" name="password" required>
#if ($errors->has('password'))
<span class="help-block">
<strong>{{ $errors->first('password') }}</strong>
</span>
#endif
</div>
</div>
<div class="form-group{{ $errors->has('password_confirmation') ? ' has-error' : '' }}">
<label for="password-confirm" class="col-md-4 control-label">Passwort
wiederholen</label>
<div class="col-md-6">
<input id="password-confirm" type="password" class="form-control"
name="password_confirmation" required>
#if ($errors->has('password_confirmation'))
<span class="help-block">
<strong>{{ $errors->first('password_confirmation') }}</strong>
</span>
#endif
</div>
</div>
<div style="display:none;" class="form-group{{ $errors->has('role') ? ' has-error' : '' }}">
<label for="role" class="col-md-4 control-label">Deine Rolle:</label>
<div class="col-md-6">
<input name="role" type="radio"
<?php if ($userType == 'customer') echo "checked";?> value="Käufer"> Käufer<br/>
<input name="role" type="radio"
<?php if ($userType == 'seller') echo "checked";?> value="Verkäufer"> Verkäufer
#if ($errors->has('role'))
<span class="help-block">
<strong>{{ $errors->first('role') }}</strong>
</span>
#endif
</div>
</div>
<div class="form-group">
<div class="col-md-6 col-md-offset-4">
<button type="submit" class="btn btn-primary">
Registrieren
</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
#endsection
So mostly basic, just few more fields then with the auth without modification and the companyName only showing up when accessed over the route /register/seller.
My RegisterController is of course also a bit modified, or especially the create function, it looks like this now:
protected function create(array $data)
{
$user = User::create([
'name' => $data['name'],
'firstName' => $data['firstName'],
'sex' => $data['sex'],
'email' => $data['email'],
'username' => $data['username'],
'password' => bcrypt($data['password']),
'role' => $data['role'],
'templateURL' => ""
]);
if($data['role'] == 'Verkäufer'){
Complaint::create([
'user_id' => $user->id,
'complaintCount' => 0
]);
}
switch($data['role']){
case 'Käufer':
$user->attachRole(2);
break;
case 'Verkäufer':
$user->attachRole(3);
$user->companyName = $data['companyName'];
$user->save();
break;
default:
$user->attachRole(2);
break;
}
return $user;
}
And now comes the problem: As you can see, in my "invidual" views, which is basically just one anyway, I still post to the url /register, which I thought should work, but it doesn't.... Any ideas why this is not working? I also tried to add individual routes, so something like that:
Route::post('/register/seller', 'Auth\RegisterController#create');
Route::post('/register/buyer', 'Auth\RegisterController#create');
but thats not working as well. In both cases, I just get the same window back, as if there was an error (so my data still entered (expect the password), but nothing is registered or entered in the db, but as well there are no errors showing up, neither in my view, nor in the console.
What's interesting as well is the network tab, it seems like it definetely sends the request to /register as it shows up there with status code 302, but as well there's the route /register/customer again, and I'm wondering why...What's also interesting is that I think that somehow it kinda works, as if I enter a password with less then 6 characters or 2 different passwords, I get an error, so somehow the form seems to be posted, but nothing is entered into the db....
Any ideas why this happens like this and whats the problem?
First of all, I'd like to suggest you a Polymorphic approach to saving the users. Right now, you have only 2 user types, what if you get a third user type (say retailer or wholesaler or blah blah)... and for each of them, you will require different fields which may or may not fit in for all user types...
So, go with this
class User
{
public function profile()
{
return $this->morphTo();
}
}
class Seller
{
public function user()
{
return $this->morphOne('App\User', 'profile');
}
}
class Buyer
{
public function user()
{
return $this->morphOne('App\User', 'profile');
}
}
Now, In your routes, add these
Route::get('login', 'LoginController#show')->name('login.show');
Route::post('login', 'LoginController#login')->name('login.post');
Route::get('register', 'RegisterController#show')->name('register.show');
Route::post('register', 'RegisterController#register')->name('register.post');
Route::get('logout', 'LoginController#logout')->name('login.logout');
Now, in your form add a dropdown/radio button for User Type selection (you can also make seprate and run different routes and make these fields hidden);
Say,
<select name="type">
<option value="1">Buyer</option>
<option value="2">Seller</option>
<select>
Your RegisterController#register can be as follows:
use App\Buyer;
use App\Seller;
use Validator;
class RegisterController extends Controller
{
public function show()
{
return view('auth.register');
}
public function register()
{
$inputs = request()->all();
$validator = $this->validator($inputs);
if($validator->fails()) {
return redirect()->back()->withErrors($validator)->withInput();
}
$userInputs = array_only($inputs, ['name', 'email', 'password']);
$userInputs['password'] = Hash::make($userInputs['password']);
switch($inputs['type'])
{
case 1:
$sellerInputs = array_only($inputs, ['company_name']);
$seller = Seller::create();
$user = $seller->user()->create($userInputs);
case 2:
$buyer = Buyer::create();
$user = $buyer->user()->create($userInputs);
default:
$user = null;
break;
}
if(!$user) {
return redirect()->back(); //Show flash messsage etc... and redirect back to show an error
}
auth()->attempt(array_only($inputs, ['email', 'password']));
return redirect(route('some.route'));
}
protected validator($inputs)
{
$rules = [
'name' => 'required|min:1|max:50',
'email' => 'required|email|min:1|max:100',
'password' => 'required|min:6|max:25',
// Other rules
];
$messages = [
// Any special messages if required...
];
return Validator::make($inputs, $rules, $messages);
}
}
Use same kind of coding structure in LoginController... I am simply going to write the login behind logging in below
public function login()
{
$inputs = request()->all();
//Validator etc...
if(auth()->attempt(array_only($inputs, ['email', 'password']))) {
return redirect(route('some.route'));
} else {
return redirect()->back(); // Again... Show some error flash message
}
}
Note :- I have not tested the code but I am 99% sure this should work... I wrote all this down myself... Took a damn half an hour almost!
Hope everything is answered and you understood. Let me know in the comments below if you have any other query :)