I'd like to ask.
I want to make excel import feature using laravel-excel package. Which, the data I imported has relational values to another table.
so, when i import excel it will save the data in two tables.
the first table, stores data such as name and file path. And the second table, saves the details of the imported excel file and adds the relationship to the first table.
below are the two tables that I have
booked_vouchers:
id
name
path
booked_voucher_details:
id
booked_voucher_id
voucher_code
course_code
user_name
and below are the codes that I have made in the controller, view and import files.
Form
<form action="{{ route('booked.import')}}" method="POST" enctype="multipart/form-data">
#csrf
<div class="form-group">
<label for="name">Name</label>
<input name="name" type="text" class="form-control" required>
</div>
<div class="form-group">
<label for="file">File</label>
<input name="file" type="file" class="form-control" required>
</div>
<button type="submit" class="btn btn-primary">Import</button>
</form>
Controller
public function import(Request $request)
{
$validator = Validator::make($request->all(), [
'file' => 'required|mimes:csv,xlx,xls,xlsx'
]);
if ($validator->fails()) {
return back()->with('toast_error', $validator->messages()->all()[0])->withInput();
}
$data = new BookedVoucher();
$data->name = $request->name;
$fileName = time().'_'.$request->file->getClientOriginalName();
$filePath = $request->file('file')->storeAs('reports', $fileName, 'public');
$data->file = $filePath;
$data->created_by = \Auth::user()->id;
if ($data->save()) {
Excel::import(new BookedVoucherDetailImport, $request->file('file'));
}
return redirect()->back()->with('success','Data have been imported');
}
BookedVoucherDetailImport.php
<?php
namespace App\Imports;
use App\Model\BookedVoucher;
use App\Model\BookedVoucherDetail;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\WithStartRow;
class BookedVoucherDetailImport implements ToModel, WithStartRow
{
/**
* #return int
*/
public function startRow(): int
{
return 2;
}
/**
* #param array $row
*
* #return \Illuminate\Database\Eloquent\Model|null
*/
public function model(array $row)
{
$data = BookedVoucher::first();
return new BookedVoucherDetail([
'booked_voucher_id' => $data->id,
'course_code' => $row[0],
'voucher_code' => $row[1],
'user_name' => $row[2],
'status' => 'OK'
]);
}
}
How do I set the booked_voucher_id value to be the same as the id value from the booked_voucher table that has been saved before the excel import process?
*for now, if I use code like in the BookedVoucherDetailImport.php file, the result of the booked_voucher_id value in the booked_voucher_details table is always incorrect.
You could pass the BookedVoucher to the Import class:
Excel::import(new BookedVoucherDetailImport($data), $request->file('file'));
Then update your BookedVoucherDetailImport to be:
<?php
namespace App\Imports;
use App\Model\BookedVoucher;
use App\Model\BookedVoucherDetail;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\WithStartRow;
class BookedVoucherDetailImport implements ToModel, WithStartRow
{
/**
* #var BookedVoucher
*/
protected $bookedVoucher;
/**
* #param BookedVoucher $bookedVoucher
*/
public function __construct(BookedVoucher $bookedVoucher)
{
$this->bookedVoucher = $bookedVoucher;
}
/**
* #return int
*/
public function startRow(): int
{
return 2;
}
/**
* #param array $row
*
* #return \Illuminate\Database\Eloquent\Model|null
*/
public function model(array $row)
{
return new BookedVoucherDetail([
'booked_voucher_id' => $this->bookedVoucher->id,
'course_code' => $row[0],
'voucher_code' => $row[1],
'user_name' => $row[2],
'status' => 'OK',
]);
}
}
Related
My problem is that when adding data, the value goes "on" and it gives an error in recording to the database section. If it is "off", it does not record.
My migration table as below and table name ise cities
$table->bigIncrements('id');
$table->string('title');
$table->enum('status', ['active', 'passive'])->default('active');
HTML classic form is below
<div class="col-lg-6">
<span class="switch">
<label>
<input name="title" type="text" placeholder="Please City Name"/>
<span></span>
</label>
</span>
<span class="form-text text-muted">{{ __('Required') }}</span>
</div>
</div>
<div class="col-lg-6">
<span class="switch">
<label>
<input name="status" type="checkbox" checked="checked"/>
<span></span>
</label>
</span>
<span class="form-text text-muted">{{ __('Is it active?') }}</span>
</div>
</div>
CityController is below I used helper and request.
public function store(CityStoreRequest $request): RedirectResponse
{
$data = $this->helper->clean($request);
$hotels = $this->service->store($data);
return back()->with(['status' => __('Ok! Recorded.')]);
}
CityStoreRequest code is below. When I select required here, if I make the button passive, the record is not added and add the required fields.
public function rules(): array
{
return [
'title' => 'required',
'status' => 'required',
];
}
CityService
<?php
namespace App\Services;
use App\Repositories\CityRepository;
class CityService
{
/**
* #var CityRepository
*/
protected $repository;
/**
* Service constructor.
*/
public function __construct()
{
$this->repository = new CityRepository();
}
/**
* #param array $data
* #return mixed
*/
public function index(array $data)
{
return $this->repository->index($data);
}
/**
* #param int $id
* #return mixed
*/
public function show(int $id)
{
return $this->repository->show($id);
}
/**
* #param array $data
* #return mixed
*/
public function store(array $data)
{
return $this->repository->store($data);
}
/**
* #param array $data
* #param int $id
* #return mixed
*/
public function update(array $data, int $id)
{
return $this->repository->update($data, $id);
}
/**
* #param int $id
* #return mixed
*/
public function destroy(int $id)
{
return $this->repository->destroy($id);
}
}
Repository as below
<?php
namespace App\Repositories;
use App\Models\City;
class CityRepository
{
/**
* #var City
*/
protected $city;
/**
* #var int
*/
protected $perPage = 25;
/**
* Repository constructor.
*/
public function __construct()
{
$this->city = new City();
}
/**
* #param array $data
* #return mixed
*/
public function index(array $data)
{
return $this->city->filter($data)->paginate($this->perPage);
}
/**
* #param int $id
* #return mixed
*/
public function show(int $id)
{
return $this->city->findOrFail($id);
}
/**
* #param array $data
* #return mixed
*/
public function store(array $data)
{
return $this->city->create($data);
}
/**
* #param array $data
* #param int $id
* #return mixed
*/
public function update(array $data, int $id)
{
$hotel = $this->city->findOrFail($id);
$hotel->fill($data);
$hotel->save();
return $hotel;
}
/**
* #param int $id
* #return mixed
*/
public function destroy(int $id)
{
$hotel = $this->city->findOrFail($id);
$hotel->delete();
return $hotel;
}
}
In your opinion, where I need to check the data coming from the form and take the necessary actions.
I think it will be better to use boolean field instead of enum.
But if you want to use enum (maybe for any further statuses), use the simple way:
Add attribute value to checkbox. <input ... value="active" />
Validate incoming status.
Just save it like other fields.
You would check (validate) input from your form in your validation. For you this is in your CityStoreRequest on the rules() function:
public function rules(): array
{
return [
'title' => 'required',
'status' => ['required', in:active,passive],
];
}
This uses the in validation rule of Laravel to determine if the value for the input is included in the given comma separated list.
'title' => 'required',
'status' => 'required', "in:active,passive",
I want to add and update multiple images over a form with Laravel v5.6.
I am also trying to associate these added pictures with another model. But while adding, I am encountering an SQL error due to the error I made somewhere. Here is that error:
SQLSTATE[HY000]: General error: 1364 Field 'imageable_id' doesn't have a default value (SQL: insert into `images` (`img_url`, `updated_at`, `created_at`) values (public/images/yxJ0BQDFz2dU5wzKk5uNreHlKl4Z5kmXDRfMug8p.png, 2020-12-19 05:43:29, 2020-12-19 05:43:29))
Thank you in advance for your help!
My Service.php model file:
use Spatie\Sluggable\HasSlug;
use Spatie\Sluggable\SlugOptions;
class Service extends Model
{
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'slug',
'title',
'content',
'status',
];
use HasSlug;
/**
* Get the options for generating the slug.
*/
public function getSlugOptions(): SlugOptions
{
return SlugOptions::create()
->generateSlugsFrom('title')
->saveSlugsTo('slug');
}
/**
* Eğer `status` set ediliyorsa...
*
*/
public function setStatusAttribute($value)
{
$this->attributes['status'] = in_array($value, ['on', 'yes', 'ok', 'true']) ? 1 : 0;
}
/**
* Eğer `status` alınıyorsa...
*
*/
public function getStatusAttribute()
{
return $this->attributes['status'] == 1 ? 'on' : null;
}
/**
* Get all of the images for the post.
*/
public function images()
{
return $this->morphMany(Image::class, 'imageable');
}
}
My Image.php model file:
use Illuminate\Database\Eloquent\Model;
class Image extends Model
{
/**
* Fillable fields
*
*/
protected $fillable = [
'name',
'desc',
'img_url',
'imageable_id',
'imageable_type',
];
/**
* imageable items
*
*/
public function imageable()
{
return $this->morphTo();
}
}
And ServiceController.php:
public function store(Request $request)
{
session()->flash('status', $request->status);
$request->validate([
'title' => 'required|between:5,255',
'content' => 'required|min:10',
// 'status' => 'accepted',
'files.*' => 'file|image|mimes:jpeg,png|max:2048',
]);
$service = new Service;
$service->title = $request->title;
$service->content = $request->content;
$service->status = $request->status;
$service->save();
if($request->hasFile('files')) {
collect($request->file('files'))->each(function ($file) use($service) {
// return Storage::putFile('public/images', $file);
// $newFile = Storage::putFile('public/images', $file);
$newFile = $file->store('public/images');
/**
*
* I don't know if the method of adding to the database here is correct.
* I'll be grateful to those who propose the truth:
*
*/
$image = new \App\Image;
$image->img_url = $newFile;
// $image->imageable->create($service);
$image->save();
$service->images()->save($image);
});
}
return redirect(route('admin.services.index'))->with('success', trans('Kayıt başarıyla eklendi'));
}
create.blade.php:
<form action="{{ route('admin.services.store') }}" enctype="multipart/form-data" method="POST">
#csrf
#method('POST')
<!-- ... -->
<div class="form-group">
<label for="files">{{ __('Yükelenecek dosya') }}:</label>
<input type="file" name="files[]" multiple id="files" class="form-control-file" placeholder="{{ __('Yüklenecek dosyaları seçin') }}" aria-describedby="files-label">
<small id="files-label" class="form-text text-muted">
{{ __('Yüklenecek dosyalar .png ve .jpg türlerini içermelidir.') }}
</small>
</div>
<!-- ... -->
</form>
When you call $image->save() that Image does not yet have a foreign key set for imageable_id and your database schema says there must be a value for imageable_id.
Don't call $image->save() as the Model will be saved after you call $service->images()->save($image). That will set the foreign key and save the model for you. So when it saves it will have the needed foreign key field with a value.
I have tried to insert lead_name,lead_status,lead_description value in db in laravel 6.18.41 version.
Controller code(LeadController.php):
<?php
namespace App\Http\Controllers;
use App\Repository\LeadRep as LeadRepo;
use Illuminate\Http\Request;
use App\Http\Controllers\BaseController as BaseController;
use Illuminate\Support\Facades\Log;
use Symfony\Component\Serializer\Serializer;
use Symfony\Component\Serializer\Normalizer\GetSetMethodNormalizer;
use Symfony\Component\Serializer\Encoder\JsonEncoder;
class LeadController extends BaseController
{
private $leadRepo;
public function __construct(LeadRepo $leadRepo)
{
$this->leadRepo = $leadRepo;
}
/**
* #param OptionsResolver $resolver
*/
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'App\Entities\Lead'
));
}
/**
* Display a listing of the resource.
* #return \Illuminate\Http\Response
*/
public function index()
{
//$started = microtime(true);
$count = $this->leadRepo->count();
//$end = microtime(true);
//$queryTime = $end - $started;
$lead = $this->leadRepo->findAll();
if (is_null($lead)) {
return $this->sendError('Lead not found.');
}
$serializer = new Serializer(array(new GetSetMethodNormalizer()), array('json' => new
JsonEncoder()));
$json = $serializer->serialize($lead, 'json');
return $this->sendResponse($json, 'Leads retrieved successfully.');
//return $this->sendResponse($count . "<-count ... querytime -> " . $queryTime . " ms", 'Leads retrieved successfully.');
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$input = $request->all();
// $validatedData = $request -> validate([
// 'lead_name' => 'required',
// 'lead_status' => 'required',
// 'lead_description' => 'required'
// ]);
/*$validator = Validator::make($input, [
'lead_name' => 'required',
'lead_status' => 'required',
'lead_description' => 'required'
]);*/
/*if ($validator->fails()) {
return $this->sendError('Validation Error.', $validator->errors());
}*/
//$input = $request->all();
Log::info($input);
//$lead = Lead::create($input);
$lead = $this->leadRepo->create($input);
return $this->sendResponse($lead, 'Lead created successfully.');
}
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function show($id)
{
$lead = $this->leadRepo->findById($id);
Log::info(print_r($lead,true));
if (is_null($lead)) {
return $this->sendError('Lead not found.');
}
$serializer = new Serializer(array(new GetSetMethodNormalizer()), array('json' => new
JsonEncoder()));
$json = $serializer->serialize($lead, 'json');
return $this->sendResponse($json,
'Lead retrieved successfully.');
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param Lead $lead
* #return \Illuminate\Http\Response
*/
public function update(Request $request, Lead $lead)
{
$input = $request->all();
$validator = Validator::make($input, [
'id' => 'required',
'lead_name' => 'required',
'lead_status' => 'required',
'lead_description' => 'required'
]);
if ($validator->fails()) {
return $this->sendError('Validation Error.', $validator->errors());
}
$lead = $this->leadRepo->findById($input['id']);
if (is_null($lead)) {
return $this->sendError('Lead cannot be updated. Lead Id not found.');
}
$lead->lead_name = $input['lead_name'];
$lead->lead_status = $input['lead_status'];
$lead->lead_description = $input['lead_description'];
$lead = $this->leadRepo->create($lead);
return $this->sendResponse([], 'Lead updated successfully.');
}
/**
* Remove the specified resource from storage.
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy(Lead $lead)
{
//$lead->delete();
return $this->sendResponse([], 'Lead deleted successfully.');
}
}
Lead Entity(Lead.php):
<?php
namespace App\Entities;
use Doctrine\ORM\Mapping as ORM;
use JsonSerializable;
/**
* #ORM\Entity #ORM\Table(name="lead")
*/
class Lead
{
/** #ORM\Id #ORM\Column(type="integer") #ORM\GeneratedValue */
protected $id;
/** #ORM\Column(type="string") */
protected $lead_name;
/** #ORM\Column(type="string") */
protected $lead_status;
/** #ORM\Column(type="string") */
protected $lead_description;
public function getId()
{
return $this->id;
}
public function getLeadName()
{
return $this->lead_name;
}
public function setLeadName($lead_name)
{
$this->lead_name = $lead_name;
}
public function getLeadStatus()
{
return $this->lead_status;
}
public function setLeadStatus($lead_status)
{
$this->lead_status = $lead_status;
}
public function getLeadDescription()
{
return $this->lead_description;
}
public function setLeadDescription($lead_description)
{
$this->lead_description = $lead_description;
}
}
Lead Repository(LeadRep.php):
<?php
namespace App\Repository;
use App\Entities\Lead;
use App\Entities\Post;
use Doctrine\ORM\EntityManager;
use Illuminate\Support\Facades\Log;
use Doctrine\Persistence\ManagerRegistry;
/**
* Class LeadRep
* #package App\Repository
*/
class LeadRep {
/**
* #var string
*/
private $class = 'App\Entities\Lead';
/**
* #var EntityManager
*/
private $em;
/**
* LeadRep constructor.
* #param EntityManager $em
*/
public function __construct(EntityManager $em)
{
$this->em = $em;
}
/**
* #param Lead $lead
* #throws \Doctrine\ORM\ORMException
* #throws \Doctrine\ORM\OptimisticLockException
*/
public function create(Lead $lead)
{
$this->em->persist($lead);
$this->em->flush();
}
/**
* #param Lead $lead
* #param $data
* #throws \Doctrine\ORM\ORMException
* #throws \Doctrine\ORM\OptimisticLockException
*/
public function update(Lead $lead, $data)
{
$lead->setLeadDescription($data['lead_description']);
$lead->setLeadName($data['lead_name']);
$lead->getLeadStatus($data['lead_status']);
$this->em->persist($lead);
$this->em->flush();
}
/**
* #param $id
* #return object|null
*/
public function findById($id)
{
Log::info("Id info".$id);
return $this->em->getRepository($this->class)->findOneBy([
'id' => $id
]);
}
public function findAll()
{
return $this->em->getRepository($this->class)->findAll();
}
public function count()
{
$criteria = [];
return $this->em->getRepository($this->class)->count($criteria);
}
/**
* #param Lead $lead
* #throws \Doctrine\ORM\ORMException
* #throws \Doctrine\ORM\OptimisticLockException
*/
public function delete(Lead $lead)
{
$this->em->remove($lead);
$this->em->flush();
}
/**
* #param $data
* #return Lead
*/
public function prepareData($data)
{
return new Lead($data);
}
}
Web Route:
use App\Http\Controllers\Lead;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/', function () {
return view('welcome');
});
Route::get('lead/{key}','LeadController#show');
Route::get('lead_all','LeadController#index');
/*Route::get('create_lead/{lead_name}/{lead_status?}/{lead_description?}',function () {
return view('leadview');
});*/
Route::post('lead_create','LeadController#store');
Route::get('create_lead',function () {
return view('leadview');
});
Route::get('student/{key}','StudentController#show');
Route::get('student_all','StudentController#index');
Blade View file(leadview.blade.php):
<form method="POST" action="http://127.0.0.1:8000/lead_create" accept-charset="UTF-8">
#csrf <!-- {{ csrf_field() }} -->
<div class="row">
<div class="form-group col-lg-6 ">
<label for="name" class="control-label">Your lead_name</label>
<input class="form-control" placeholder="" name="lead_name" type="text" id="name">
</div>
<div class="form-group col-lg-6 ">
<label for="email" class="control-label">Your lead_status</label>
<input class="form-control" placeholder="" name="lead_status" type="text" id="email">
</div>
<div class="form-group col-lg-12 ">
<label for="message" class="control-label">Your lead_description</label>
<textarea class="form-control" placeholder="" name="lead_description" cols="50" rows="10" id="message"></textarea>
</div>
<div class="form-group col-lg-12">
<input class="btn btn-default" type="submit" value="Send">
</div>
</div>
</form>
I have used doctine with laravel in this project.When submit the form to insert lead value from from,it returning below error,
Argument 1 passed to App\Repository\LeadRep::create() must be an instance of App\Entities\Lead, array given, called in D:\wamp64\www\projects\laraveldemo\crmapp-crud\app\Http\Controllers\LeadController.php on line 108
How can i solve this issue? Can anyone provide solution for this?
The problem is you pass the array of inputs instead of model.
You have function prepareData inside the repo, so you can use it to prepare the model.
$lead = $this->leadRepo->prepareData($input);
$this->leadRepo->create($lead);
UPD
/**
* Class LeadRep
* #package App\Repository
*/
class LeadRep
{
/**
* #param $data
* #return Lead
*/
public function prepareData(array $data): Lead
{
$lead = new Lead();
$lead->setLeadName($data['lead_name']);
$lead->setLeadStatus($data['lead_status']);
$lead->setLeadDescription($data['lead_description']);
return new $lead;
}
}
$lead = $this->leadRepo->create(new LeadRep($lead));
You must pass an instance of a model you are creating.
I changed controller function like below, then added this line in top of controller file - use App\Entities\Lead; ,then it worked.
public function store(Request $storeRequest)
{
$storeRequest->validate([
'lead_name' => 'required',
'lead_status' => 'required',
'lead_description' => 'required'
]);
$lead = new Lead();
$lead->setLeadName($storeRequest->get('lead_name'));
$lead->setLeadStatus($storeRequest->get('lead_status'));
$lead->setLeadDescription($storeRequest->get('lead_description'));
$this->leadRepo->create($lead);
return $this->sendResponse($lead, 'Lead created successfully.');
}
I'm trying to make a belongstoMany relationship in Laravel 5.2.39 between people and places but am unable to pass the information into a view in a select box. I just get: "Error Exception: Undefined variable: people". It also is not saving and making the pivot table entries.
I have created the pivot table person_place with 'place_id' and 'person_id' columns which correspond to the 'people' and 'places' table.
App/Person.php (Person Model)
<?php
namespace ss;
use ss\Place;
use Illuminate\Database\Eloquent\Model;
class Person extends Model
{
/**
* Fillable fields
*
* #var array
*/
protected $fillable = [
'name',
'type',
'status',
'notes',
'email',
'phone',
'alt',
'web',
'first',
'last',
'title',
];
public function places()
{
return $this->belongsToMany('Place');
}
}
App/Place.php (Place Model)
<?php
namespace ss;
use ss\Person;
use Illuminate\Database\Eloquent\Model;
class Place extends Model
{
/**
* Fillable fields
*
* #var array
*/
protected $fillable = [
'name',
'type',
'status',
'notes',
'email',
'phone',
'alt',
'web',
'address1',
'address2',
'city',
'state',
'zip',
'country',
];
public function people()
{
return $this->belongsToMany('Person');
}
}
App/Http/Controllers/PlaceController.php (Places Controller)
<?php namespace ss\Http\Controllers;
use ss\Place;
use ss\Person;
use ss\Http\Requests;
use Illuminate\Http\Request;
use View;
use Session;
class PlaceController extends Controller
{
/**
* Display a listing of the resource.
*
* #return Response
*/
public function index()
{
$places = Place::all();
$people = Person::pluck('name','id')->all();
return View::make('places.index', compact('places','people'));
}
/**
* Show the form for creating a new resource.
*
* #return Response
*/
public function create()
{
$people = Person::lists('last', 'id');
return view('places.create', compact('people'));
}
/**
* Store a newly created resource in storage.
*
* #return Response
*/
public function store(Request $request)
{
$this->validate($request, [
'name' => 'required'
]);
$input = $request->all();
Place::create($input);
Session::flash('flash_message', 'Place successfully added!');
return redirect()->action('PlaceController#index');
}
/**
* Display the specified resource.
*
* #param int $id
* #return Response
*/
public function show($id)
{
$place = Place::findOrFail($id);
return view('places.show')->withPlace($place);
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return Response
*/
public function edit($id)
{
$place = Place::findOrFail($id);
$people = Person::pluck('name','id')->all();
return view('places.edit', compact('place','people'));
}
/**
* Update the specified resource in storage.
*
* #param int $id
* #return Response
*/
public function update($id, Request $request)
{
$this->validate($request, [
'name' => 'required'
]);
$input = $request->except('people');
$place = Place::findOrFail($id);
$peopleIDs = $this->place->people($peopleIds);
$place->fill($input)->save();
Session::flash('flash_message', 'Place successfully edited!');
return redirect()->action('PlaceController#index', $place);
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return Response
*/
public function destroy($id)
{
$place = Place::findOrFail($id);
$place->delete();
Session::flash('flash_message', 'Place successfully deleted!');
return redirect()->action('PlaceController#index');
}
}
resources/views/places/edit.blade.index.php (Places View, where I'm trying to build select list -not working)
#section('aside')
{!! Form::select('people', $people, null, ['class' => '', 'multiple']) !!}
<ul class="section table-of-contents">
<li>New Time</li>
<li>New Money</li>
<li> </li>
<li>New Sub-Task</li>
</ul>
#endsection
resources/views/places/create.blade.index.php (Places View with a select list that works but does not make a pivot table when saving)
#section('aside')
{!! Form::select('people', $people, null, ['class' => '', 'multiple']) !!}
#endsection
Have tried various methods of "with" and "attach" and am unable to get a result. Interestingly, even if I specifically place "$person = "foo"; in my edit method it still says it is undefined.
Thank you for your help.
EDIT: Updated Code
In the PlacesController, your edit($id) method does not pass an array of people to the view.
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return Response
*/
public function edit($id)
{
$place = Place::findOrFail($id);
$people = People::pluck('name','id')->all();
return view('places.edit', compact('place', 'people');
}
This question already has answers here:
laravel 4 custom named password column
(4 answers)
Closed 8 years ago.
I have a problem with laravel 4.2 authentication. Auth::attempt() always return false. Hash::check() return false.
I am tired to solve this problem. I read many tutorial and I can't find the solution.
Here are some of my important files:
my auth.php
<?php
return array(
'driver' => 'eloquent',
'model' => 'User',
'table' => 'users',
'reminder' => array(
'email' => 'emails.auth.reminder',
'table' => 'password_reminders',
'expire' => 60,
),
);
my UserModel.php
<?php
use Illuminate\Auth\UserTrait;
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableTrait;
use Illuminate\Auth\Reminders\RemindableInterface;
class User extends Eloquent implements UserInterface, RemindableInterface {
use UserTrait, RemindableTrait;
/**
* The database table used by the model
*
* #var string
*/
protected $table = 'users';
/**
* The primary key used by the model
*
* #var integer
*/
protected $primaryKey = 'UserId';
/**
* The name of the "created at" column
*
* #var string
*/
const CREATED_AT = 'UserCreatedAt';
/**
* The name of the "updated at" column
*
* #var string
*/
const UPDATED_AT = 'UserUpdatedAt';
/**
* The attributes excluded from the model's JSON form
*
* #var array
*/
protected $hidden = array('UserPassword', 'UserRememberToken');
protected $fillable = array(
'UserName',
'UserSurname',
'UserCity',
'UserStreet',
'UserPostalCode',
'UserPostalCity',
'UserDeskPhone',
'UserMobilePhone',
'UserEmail',
'UserPassword',
'UserType',
'UserPermission',
'UserActive'
);
protected $guarded = array('UserId', 'HotelId', 'UserRememberToken', 'UserCreatedAt', 'UserUpdatedAt');
public static $rules = array(
'name'=>'required|alpha|min:2',
'surname'=>'required|alpha|min:2',
'email'=>'required|email|unique:users',
'password'=>'required|alpha_num|between:8,100|confirmed',
'password_confirmation'=>'required|alpha_num|between:8,100'
);
/**
* Get the unique identifier for the user
*
* #return mixed
*/
public function getAuthIdentifier()
{
return $this->getKey();
}
/**
* Get the password for the user
*
* #return string
*/
public function getAuthPassword()
{
return $this->UserPassword;
}
/**
* Get the e-mail address where password reminders are sent
*
* #return string
*/
public function getReminderEmail()
{
return $this->UserEmail;
}
/**
* Get the remember token for the user
*
* #return string
*/
public function getRememberToken()
{
return $this->UserRememberToken;
}
/**
* Set the remember token for the user
*
* #var string
*/
public function setRememberToken($value)
{
$this->UserRememberToken = $value;
}
/**
* Get the remember token name used by the model
*
* #return string
*/
public function getRememberTokenName()
{
return 'UserRememberToken';
}
/**
* Get the user type
*
* #return integer
*/
public function getUserType()
{
return 'UserType';
}
}
my UserController.php
<?php
class UserController extends BaseController {
/*
|--------------------------------------------------------------------------
| User Controller
|--------------------------------------------------------------------------
*/
/**
* UserController's constructor
*/
public function __construct() {
$this->beforeFilter('csrf', array('on'=>'post'));
$this->beforeFilter('auth', array('only'=>array('getBackend')));
}
/**
* Show register page for the user
*/
public function getRegister()
{
return View::make('app.user.register');
}
/**
* Action after pressing the register button
*/
public function postCreate() {
$validator = Validator::make(Input::all(), User::$rules);
if ($validator->passes()) {
// validation has passed, save user in DB
$user = new User;
$user->UserName = Input::get('name');
$user->UserSurname = Input::get('surname');
$user->UserEmail = Input::get('email');
$user->UserPassword = Hash::make(Input::get('password'));
$user->save();
return Redirect::to('user/login')->with('message', 'Dodano użytkownika!');
} else {
// validation has failed, display error messages
return Redirect::to('user/register')
->with('message', 'Pojawiły się następujące błędy:')
->withErrors($validator)
->withInput();
}
}
/**
* Show login page for the user
*/
public function getLogin()
{
// Check if we already logged in
if (Auth::check())
{
// Redirect to backend homepage
return Redirect::to('backend')->with('message', 'Jesteś zalogowany!');
}
return View::make('app.user.login');
}
/**
* Action after pressing the login button
*/
public function postLogin()
{
// Get all the inputs
$data = array(
'UserEmail' => Input::get('email'),
'UserPassword' => Input::get('password')
);
// Declare the rules for the form validation
$rules = array(
'UserEmail' => 'required|email|min:6',
'UserPassword' => 'required|between:8,100'
);
// Declare error message for the rules for the form validation
$messages = array(
'UserEmail.required' => 'Adres e-mail nie może być pusty!',
'UserEmail.email' => 'Adres e-mail jest nieprawidłowy!',
'UserEmail.min' => 'Adres e-mail musi mieć minimum 6 znaków!',
'UserPassword.required' => 'Hasło nie może być puste!',
'UserPassword.between' => 'Hasło musi mieć od 8 do 100 znaków!'
);
// Validate the inputs
$validator = Validator::make($data, $rules, $messages);
// Check if the form validates with success
if ($validator->passes())
{
// Try to log the user in
if (Auth::attempt($data))
{
// Redirect to backend homepage
return Redirect::to('backend');
}
else
{
// Redirect to the login page
return Redirect::to('user/login')
->withErrors('Twój adres e-mail lub hasło jest nieprawidłowe!')
->withInput(Input::except('password'));
}
}
// Something went wrong
return Redirect::to('user/login')
->withErrors($validator)
->withInput(Input::except('password'));
}
/**
* Show the profile for the given user
*/
public function getProfile($id)
{
$user = User::find($id);
return View::make('app.user.profile', array('user' => $user));
}
/**
* Show backend homepage
*/
public function getBackend()
{
return View::make('app.backend.start');
}
}
my login.blade.php
#extends('app.user.master')
#section('title')
{{ 'Logowanie' }}
#stop
#section('content')
<div class="container-fluid">
<div id="page-login" class="row">
<div class="col-xs-12 col-md-4 col-md-offset-4 col-sm-6 col-sm-offset-3">
{{--
<div class="text-right">
Need an account?
</div>
--}}
<div class="box">
<div class="box-content">
{{ Form::open(array('url'=>'user/login', 'class'=>'form-signin')); }}
<div class="text-center">
<h3 class="page-header">{{ Config::get('app.name') }} - logowanie</h3>
</div>
#if($errors->has())
<div class="form-group">
<ul>
#foreach ($errors->all() as $error)
<li class="alert">{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
<div class="form-group">
<label class="control-label">E-mail</label>
{{ Form::text('email', Input::old('email'), array('class'=>'form-control', 'placeholder'=>'E-mail')) }}
</div>
<div class="form-group">
<label class="control-label">Hasło</label>
{{ Form::password('password', array('class'=>'form-control', 'placeholder'=>'Hasło')) }}
</div>
<div class="text-center">
{{ Form::submit('Zaloguj', array('class'=>'btn btn-large btn-primary btn-block')) }}
</div>
{{ Form::close() }}
</div>
</div>
</div>
</div>
</div>
#stop
The problem is your $data that you pass to Auth::attempt. You should change
if (Auth::attempt($data))
into
$dataAttempt = array(
'UserEmail' => Input::get('email'),
'password' => Input::get('password')
);
if (Auth::attempt($dataAttempt))
and add to your User model the following function:
public function getAuthPassword() {
return $this->UserEmail;
}
This is because you need to pass password in array as your password to attempt method (You can read more about it at How to change / Custom password field name for Laravel 4 and Laravel 5 user authentication)