Route undifined laravel export - php

here my web.php
Route::post('/export_excel', 'PenyetoranController#exportExcel')->name('penyetoran.export-excel')->middleware('role:BENDAHARA|SUPERVISOR');
here my export file
<?php
namespace App\Exports;
use App\GroupPasar;
use Carbon\Carbon;
use App\Users;
use App\Pasar;
use App\Penyetoran;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\WithMapping;
class PenyetoranExport implements FromCollection, WithHeadings, WithMapping
{
/**
* #return \Illuminate\Support\Collection
*/
public function collection()
{
$startDate = request()->input('tgl_awal') ;
$endDate = request()->input('tgl_akhir') ;
if(request()->input('grup_pasar')!=null)
{
$groupId = request()->input('grup_pasar');
return GroupPasar::where('group_pasars.id', $groupId)
->join('pasar', 'pasar.grup_pasar', '=', 'group_pasars.id')
->join('penyetoran', function ($join){
$join->on('penyetoran.pasar', '=', 'pasar.id');
$join->where('status', 1);
})
->join('users', 'penyetoran.petugas', '=', 'users.id')
->whereBetween('penyetoran.tanggal_penyetoran', [$startDate, $endDate])
->select('group_pasars.nama as nama_pasar','users.name as nama_petugas', 'penyetoran.jumlah_setoran','penyetoran.penyetoran_melalui','penyetoran.tanggal_penyetoran','penyetoran.tanggal_disetor')
->get();
}
return Penyetoran::select('pasar','petugas','jumlah_setoran','penyetoran_melalui','tanggal_penyetoran','tanggal_disetor')->where('status',1)
->whereBetween('tanggal_penyetoran', [$startDate, $endDate])->get();
}
public function map($penyetoran) : array {
if(request()->input('grup_pasar')!=null){
return [
$penyetoran->nama_pasar,
$penyetoran->nama_petugas,
$penyetoran->jumlah_setoran,
$penyetoran->penyetoran_melalui,
Carbon::parse($penyetoran->tanggal_penyetoran)->toFormattedDateString(),
Carbon::parse($penyetoran->tanggal_disetor)->toFormattedDateString(),
] ;
}
return [
$penyetoran->nama_pasar,
$penyetoran->name,
$penyetoran->jumlah_setoran,
$penyetoran->penyetoran_melalui,
Carbon::parse($penyetoran->tanggal_penyetoran)->toFormattedDateString(),
Carbon::parse($penyetoran->tanggal_disetor)->toFormattedDateString(),
] ;
}
public function headings() : array {
return [
'Pasar',
'Petugas',
'Jumlah Setoran',
'Penyetoran Melalui',
'Tanggal Penyetoran',
'Tanggal Disetor',
] ;
}
}
here my controller
``public function exportExcel(Request $request)
{
$this->validate($request,[
'tgl_awal' => 'required|date',
'tgl_akhir' => 'required|date|after:tgl_awal',
], [
'tgl_awal.required' => 'Tanggal awal harus diisi',
'tgl_akhir.after' => 'Tanggal akhir yang dipilih harus sehari sesudah tanggal awal',
'tgl_akhir.required' => 'Tanggal akhir harus diisi',
]);
return Excel::download(new PenyetoranExport, 'Daftar Penyetoran - '.date('d-m-Y').'.xlsx');
}`
`
Here my View
{{-- <a class="btn btn-success" href="/penyetoran/export_excel" role="button" target="_blank">Export Excel<span class=""></a> --}}
<form id="formExport" action="{{route('penyetoran.export-excel')}}" method="post" enctype="multipart/form-data">
{{ csrf_field() }}
<div class="form-group row">
<label for="export" class="col-sm-1 col-form-label">Export</label>
<div class="col-sm-3">
<input id="tgl_awal" name="tgl_awal" type="date" class="form-control #error('tgl_awal') is-invalid #enderror" value="{{ old('tgl_awal') }}">
#error('tgl_awal')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div> -
<div class="col-sm-3">
<input id="tgl_akhir" name="tgl_akhir" type="date" class="form-control #error('tgl_akhir') is-invalid #enderror" value="{{ old('tgl_akhir') }}">
#error('tgl_akhir')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
<div class="col-sm-2">
<input type="submit" class="btn btn-success" value="Export Excel">
</div>s
</div>
<div class="form-group row">
<label for="export" class="col-sm-1 col-form-label"></label>
<div class="col-sm-3">
<select id="grup_pasar" name="grup_pasar" class="form-control">
<option value="">-- Pilih Grup Pasar --</option>
#foreach($groups as $group)
<option value="{{$group->id}}">{{$group->nama}}</option>
#endforeach
</select>
<small class="text-muted">Pilih grup pasar untuk mencetak berdasarkan grup pasar</small>
</div>
</div>
</form>
do i need to re make the export ? or there is something just wrong with the way i using it? please help me
here is the error
Route [penyetoran.export-excel] not defined. (View:C:\xampp\htdocs\siappara_web_v2\resources\views\penyetoran\indexLaporan.blade.php)

error route [penyetoran.export-excel] not defined
Most likely this is an issue with your route being cached.
To clear the route cache.
php artisan route:clear
To list the routes:
php artisan route:list

Related

How to create category tags for posts? I am using laravel 8

I am trying to allow users to create and add category tags to a post when creating that post in the form.
I would further want those tags to appear in the profile view and function as filter buttons to show posts according to the tag names they possess.
However, in my attempt to achieve this overall result, I am stuck because everytime I submit a post with tags, the tags array keeps showing up empty in the view.
My post table is:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreatePostsTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('user_id');
$table->string('caption');
$table->string('url');
$table->string('image');
$table->text('tags');
$table->timestamps();
$table->index('user_id');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('posts');
}
}
My Post Model is:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Carbon\Carbon;
class Post extends Model
{
use \Conner\Tagging\Taggable;
use HasFactory;
protected $fillable = ['caption','url','image', 'tags'];
public function user()
{
return $this->belongsTo(User::class);
}
protected $dates = [
'created_at',
'updated_at',
];
}
My create and store methods in PostsController are:
public function create()
{
return view('posts.create');
}
public function store(Request $request)
{
$data = request()->validate([
'caption' => 'required',
'url' => 'required',
'image' => ['required', 'image'],
'tags' => 'required',
]);
$tags = explode(", ", $request->tags);
$imagePath = request('image')->store('uploads', 'public');
auth()->user()->posts()->create([
'caption' => $data['caption'],
'url' => $data['url'],
'image' => $imagePath,
'tags' => $data['tags'],
]);
return redirect('/users/' . auth()->user()->id);
}
My form to create post is:
<form action="/posts" enctype="multipart/form-data" method="post">
#csrf
<div class="form-group">
<label for="caption" class="create_caption_label">Post Caption</label>
<div class="create_caption_div">
<input id="caption"
type="text"
class="form-control #error('caption') is-invalid #enderror"
name="caption"
value="{{ old('caption') ?? '' }}"
autocomplete="caption" autofocus>
#error('caption')
<div class="invalid-feedback-div">
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
</div>
#enderror
</div>
</div>
<div class="form-group">
<label for="tags" class="create_tags_label">Tags</label>
<div class="create_tags_div">
<input id="tags"
type="text"
data-role="tagsinput"
class="form-control #error('tags') is-invalid #enderror"
name="tags"
value="{{ old('tags') ?? '' }}"
autocomplete="tags" autofocus>
#error('tags')
<div class="invalid-feedback-div">
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
</div>
#enderror
</div>
</div>
<div class="form-group">
<label for="url" class="edit_title_label">URL</label>
<div class="edit_url_div">
<input id="url"
type="text"
class="form-control #error('url') is-invalid #enderror"
name="url"
value="{{ '' }}"
autocomplete="url" autofocus>
#error('url')
<div class="invalid-feedback-div">
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
</div>
#enderror
</div>
</div>
<div class="create_post_image_div">
<label for="image" class="create_image_label">Post Image</label>
<input type="file" class="form-control-file" id="image" name="image">
#error('image')
<div class="invalid-feedback-div">
<strong>{{ $message }}</strong>
</div>
#enderror
<div class="create_post_btn_div">
<button class="create_post_btn">Save Post</button>
</div>
</div>
</form>
Finally, my view is: (This is where the tags array shows up empty after submitting a post)
#foreach( $user->posts as $post )
<div class="carousel_posts_container">
<div class="post_date_and_edit_div">
<div class="posted_date_div">
<p class="posted_date">posted: {{ $post->created_at->diffForHumans() }}</p>
</div>
<div class="post_edit_div">
<form action="/posts/{{$post->id}}/edit">
<input class="post_edit_btn" type="submit" value="• • •">
</form>
</div>
</div>
<div class="post_counter_div">
<p class="post_counter">1 like</p>
</div>
<div class="post_counter_div">
<p class="post_counter">1 comment</p>
</div>
<div class="carousel_post_img_div">
<img src="/storage/{{ $post->image }}" class="carousel_img_placeholder">
</div>
<div class="like_comment_view_container">
<div class="view_btn_div">
<form action="{{$post->url}}">
<input class="like_comment_view_btns" type="submit" value="( View Post )">
</form>
</div>
<div class="like_btn_div">
<button type="button" class="like_comment_view_btns">( Like )</button>
</div>
<div class="comment_btn_div">
<button type="button" class="like_comment_view_btns">( Comment )</button>
</div>
</div>
<div class="carousel_caption_container">
<div class="carousel_caption_div">
<p class="carousel_caption_username">{{$user->username}} - {{$post->caption}}</p>
<p class="carousel_caption">{{$post->caption}}</p>
</div>
<div class="post-tags mb-4">
<strong>Tags : </strong>
#foreach($post->tags as $tag)
<span class="badge badge-info">{{$tag->name}}</span>
#endforeach
</div>
</div>
</div>
#endforeach
How can I resolve this issue?
And furthermore, how can I allow the tags to function as filter buttons to show posts according to the tag names they possess?
You can save tags as json array in db. Then cast to array in model, so it will be automatically array when you will retrieve. When saving you will pass tags as array then it will automatically convert to json string.
protected $casts = [
'tags' => 'array',
];

SQLSTATE[23000]: Integrity constraint violation: 19 NOT NULL constraint failed: pets.user_id

I am working on a pet registration platform, but when I click on the submit button to save the info to my database, I seem to get this error:
SQLSTATE[23000]: Integrity constraint violation: 19 NOT NULL constraint failed: pets.user_id (SQL: insert into "pets" ("nickname", "species", "date_of_birth", "user_id", "updated_at", "created_at") values (Tom, Male, 2009-07-30, ?, 2020-12-13 09:59:07, 2020-12-13 09:59:07))
This is the Pets Controller:
<?php
namespace App\Http\Controllers;
use App\Models\Pet;
use App\Models\User;
class PetsController extends Controller
{
public function create()
{
return view('create');
}
public function store(User $user)
{
Pet::create([
'nickname' => request('nickname'),
'species' => request('species'),
'date_of_birth' => request('date_of_birth'),
'color' => request('color'),
'description' => request('description'),
'user_id' => $user->id
]);
return redirect('/');
}
}
This is the Model for User:
<?php
namespace App\Models;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
class User extends Authenticatable
{
use HasFactory, Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name',
'email',
'username',
'phone',
'password',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password',
'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
public function pets()
{
return $this->hasMany(Pet::class);
}
This is the model for Pets:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Pet extends Model
{
protected $fillable = ['nickname','species','date_of_birth','gender','user_id'];
public function users()
{
return $this->belongsTo(User::class);
}
}
This is the form view:
#extends('layouts.app')
#section('content')
<div class="container py-5">
<form action="/create" enctype="multipart/form-data" method="post">
#csrf
<div class="row">
<div class="col-10">
<div class="row justify-content-center">
<h1><strong>Add A Pet</strong></h1>
</div>
<div class="form-group row py-4">
<label for="nickname" class="col-md-4 col-form-label text-md-right">Nickname</label>
<div class="col-md-6">
<input id="nickname" type="text" class="form-control #error('nickname') is-invalid #enderror"
name="nickname"
value="{{ old('nickname') }}"
placeholder="Enter the name of the animal"
required autocomplete="nickname" autofocus>
#error('nickname')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
<div class="form-group row">
<label for="species" class="col-md-4 col-form-label text-md-right">Species</label>
<div class="col-md-6">
<select id="species" class="form-control #error('species') is-invalid #enderror"
name="species"
value="{{ old('species') }}"
required autocomplete="species" autofocus>
<option disabled selected>Select species</option>
<option>Dog</option>
<option>Domestic cat</option>
<option>other</option>
</select>
#error('species')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
<div class="form-group row py-4">
<label for="date_of_birth" class="col-md-4 col-form-label text-md-right">Date of birth</label>
<div class="col-md-6">
<input id="date_of_birth" type="date" class="form-control #error('date_of_birth') is-invalid #enderror"
name="date_of_birth"
value="{{ old('date_of_birth') }}"
placeholder="yyyy-mm-dd"
required autocomplete="date_of_birth" autofocus>
#error('date_of_birth')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
<div class="form-group row justify-content-center" style="padding-left:108px">
<div class="form-group col-md-3">
<label for="gender">Gender</label>
<select id="species" class="form-control #error('species') is-invalid #enderror"
name="species"
value="{{ old('species') }}"
required autocomplete="species" autofocus>
<option>Unknown</option>
<option>Male</option>
<option>Female</option>
</select>
#error('species')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
<div class="form-group col-md-3">
<label for="color">Color</label>
<input id="color" type="text" class="form-control #error('color') is-invalid #enderror"
name="color"
value="{{ old('color') }}"
placeholder="Select color"
required autocomplete="color" autofocus>
#error('color')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
<div class="form-group row py-4">
<label for="description" class="col-md-4 col-form-label text-md-right">Description</label>
<div class="col-md-6">
<textarea name="description" id="description" rows="3"
class="form-control #error('description') is-invalid #enderror"
value="{{ old('description') }}"
placeholder="Enter a description of the animal"></textarea>
#error('description')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
<div class="row col-md-6" style="margin-left:300px">
<button class="btn btn-primary btn-lg btn-block">Finish</button>
</div>
<div class="row col-md-6 py-4" style="margin-left:430px">
<u><h4>Add Pet Later</h4></u>
</div>
</div>
</div>
</form>
</div>
#endsection
And finally the migration for pets table:
public function up()
{
Schema::create('pets', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('user_id');
$table->string('nickname');
$table->string('species');
$table->date('date_of_birth');
$table->string('gender');
$table->string('color')->nullable();
$table->text('description')->nullable();
$table->timestamps();
});
}
Been struggling with this for quite a while now!
Here is the routes file:
<?php
use Illuminate\Support\Facades\Route;
Route::get('/', function () {
return view('welcome');
});
Auth::routes();
Route::get('/register/create', [App\Http\Controllers\PetsController::class, 'create']);
Route::post('/create', [App\Http\Controllers\PetsController::class, 'store']);
$user injected in method store() is empty User model without attributes, like after $user = new User;.
You could retrieve current user id with 2 ways:
First: from request.
public function store()
{
Pet::create([
'nickname' => request('nickname'),
'species' => request('species'),
'date_of_birth' => request('date_of_birth'),
'color' => request('color'),
'description' => request('description'),
'user_id' => request()->user()->id
]);
return redirect('/');
}
Second: from auth.
public function store()
{
Pet::create([
'nickname' => request('nickname'),
'species' => request('species'),
'date_of_birth' => request('date_of_birth'),
'color' => request('color'),
'description' => request('description'),
'user_id' => auth()->id()
]);
return redirect('/');
}
Does the pet belong to the user who is logged in? It is not clear where the User instance comes from, in the form action I don't see a user id.
If the pet belongs to the logged in user, why don't you get the id of the user with:
Auth::user()->id; or Auth::id(); or auth()->user()->id;

Laravel 5.8: Call to a member function update() on null

I'm currently learning Laravel 5.8 and creating instagram clone app and I've been having an issue with updating my profile details. Whenever I hit "Update profile", it gives off an error - "Call to a member function update() on null". The issue seems to be in public function update(). I've looked up other threads and can't seem to fix this issue, so any help would be greatly appreciated!
Here's my code:
View:
#section('content')
<div class="container">
<form action="/profile/{{ $user->id }}" enctype="multipart/form-data" method="post" >
#csrf
#method('PATCH')
<div class="row">
<div class="col-8 offset-2">
<div class="row pb-3">
<h1>Edit profile</h1>
</div>
<div class="form-group row">
<label for="title" class="col-form-label"><strong>Title</strong></label>
<input id="title" type="text" class="form-control #error('title') is-invalid #enderror" name="title" value="{{ old('title') ?? $user->profile['title'] }}" required autocomplete="title" autofocus>
#error('title')
<span class="invalid-feedback" role="alert">
<strong>{{ $title }}</strong>
</span>
#enderror
</div>
<div class="form-group row">
<label for="description" class="col-form-label"><strong>Description</strong></label>
<input id="description" type="text" class="form-control #error('description') is-invalid #enderror" name="description" value="{{ old('description') ?? $user->profile['description']}}" required autocomplete="description" autofocus>
#error('description')
<span class="invalid-feedback" role="alert">
<strong>{{ $description }}</strong>
</span>
#enderror
</div>
<div class="row">
<label for="photo" class="col-form-label">Select Profile Picture</label>
<input type="file" class="form-control-file" id="photo" name="photo">
#error('photo')
<strong>{{ $message }}</strong>
#enderror
</div>
<div class="row pt-3">
<button class="btn btn-primary">
Update Profile
</button>
</div>
</div>
</div>
</form>
</div>
#endsection
Route:
Auth::routes();
Route::get('/profile/{user}', 'ProfileController#index')->name('profile.show');
Route::get('/profile/{user}/edit', 'ProfileController#edit')->name('profile.edit');
Route::patch('/profile/{user}', 'ProfileController#update')->name('profile.update');```
Controller:
<?php
namespace App\Http\Controllers;
use App\User;
use App\Profile;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class ProfileController extends Controller
{
public function index(User $user){
return view('profile.index', [
'user' => $user,
]);
}
public function edit(User $user){
return view('profile.edit', [
'user' => $user,
]);
}
public function update(User $user){
$data = request()->validate([
'title' => 'required',
'description' => 'required',
'photo' => '',
]);
auth()->user()->profile->update($data);
return redirect("/storage/ {$user->id}");
}
}
Thank you in advance!
try passing the user you are editing as you have passed them in the routes., The error means you want to update a user but you haven't specified which user you are updating.
try doing something like this:
public function validateUser(){
return request()->validate([
'title' => 'required',
'description' => 'required',
'photo' => '',
]);
}
then in the update function do something like this:
public function update($user_id){
return User::where('id',$user_id)->update($this->validateUser());
}
public function update(User $user){
$data = request()->validate([
'title' => 'required',
'description' => 'required',
'photo' => '',
]);
$user->profile()->update($data);
return redirect("/storage/".$user->id);
}
Update Or Insert
Sometimes you may want to update an existing record in the database or create it if no matching record exists. In this scenario, the updateOrInsert method may be used.
User::where('id',$id)->updateOrInsert($data);

Photos won't upload using laravel 5.7

Using Laravel 5.6 before, my photos uploaded perfectly and now that I've upgraded to 5.7, now they wont and I'm at a loss. The posts will upload, just not the photos. I have checked any rechecked the relationships and routes gut to no avail. Any help will be appreciated.
home.blade.php:
<form method="POST" action="{{ route('makePost') }}">
#csrf
<div class="form-group row">
<label for="body" class="col-md-4 col-form-label text-md-right">{{ __('Body') }}</label>
<div class="col-lg-6">
<textarea id="body" type="text" class="form-control{{ $errors->has('body') ? ' is-invalid' : '' }}" name="body" value="{{ old('body') }}" required autofocus></textarea>
#if ($errors->has('body'))
<span class="invalid-feedback" role="alert">
<strong>{{ $errors->first('body') }}</strong>
</span>
#endif
</div>
</div>
<div class="col-md-6">
<input id="image" type="file" class="form-control{{ $errors->has('image') ? ' is-invalid' : '' }}" name="image" value="{{ old('image') }}" autofocus>
#if ($errors->has('image'))
<span class="invalid-feedback" role="alert">
<strong>{{ $errors->first('image') }}</strong>
</span>
#endif
</div>
<div class="form-group row mb-0">
<div class="col-md-6 offset-md-4">
<button type="submit" class="btn btn-primary">
{{ __('Create Post') }}
</button>
</div>
</div>
</form>
PostsController.php:
public function store(Request $request)
{
$input = $request->all();
$user = Auth::user();
if($file = $request->file('photo_id')) {
$name = time() . $file->getClientOriginalName();
$file->move('images', $name);
$photo = Photo::create(['file'=>$name]);
$input['photo_id'] = $photo->id;
}
$user->post()->create($input);
return redirect('/home');
}
Photo.php:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Photo extends Model
{
protected $fillable = [
'file',
];
public function user() {
return $this->belongsTo('App\User');
}
public function photo() {
return $this->belongsTo('App\Photo');
}
}
Post.php:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
protected $fillable = [
'body', 'photo_id', 'user_id',
];
public function post()
{
return $this->belongsTo('App\User');
}
}
Add enctype="multipart/form-data" to <form> tag. This value is required when you are using forms that have a file upload control.
<form method="POST" action="{{ route('makePost') }}" enctype="multipart/form-data">
//
</form>
Source: HTML enctype Attribute

Laravel Auth modify for two kinds of users

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 :)

Categories