Batch uploading and adding files to the database with Laravel - php

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.

Related

How to Import Excel with Table Relation in Laravel 7?

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',
]);
}
}

Getting error of 'Trying to get property 'course_code' of non-object' when i click my edit button. what could be the problem?

I am trying to edit the entry into the table, but every time I click my edit button to take me to the edit page it gives me the error:
Trying to get property 'course_code' of non-object
Below is my code:
CourseController.php :
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Course;
class CoursesController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
// $courses = Course::all();
// $courses = Course::orderBy('title', 'desc')->get();
$courses = Course::orderBy('course_code', 'desc')->paginate();
return view('subs.index')->with('courses', $courses);
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
return view('subs.create');
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$this->validate($request, [
'course_code' => 'required',
'course_name' => 'required'
]);
$course = new Course;
$course->course_code = $request->input('course_code');
$course->course_name = $request->input('course_name');
$course->save();
return redirect('/subs')->with('success', 'New course added!');
}
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function show($course_code)
{
$course = Course::find($course_code);
return view('subs.show')->with('course', $course);
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function edit($course_code)
{
$course = Course::find($course_code);
return view('subs.edit')->with('course', $course);
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(Request $request, $course_code)
{
$this->validate($request, [
'course_code' => 'required',
'course_name' => 'required'
]);
$course = Course::find($course_code);
$course->course_code = $request->input('course_code');
$course->course_name = $request->input('course_name');
$course->save();
return redirect('/subs')->with('success', 'Course Updated!');
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy($id)
{
//
}
}
show.blade.php:
#extends('layouts.app')
#section('content')
Go back
<div class="container">
<h1>{{$course->course_code}}</h1>
<h3>{{$course->course_name}}</h3>
</div>
Edit</td>
#endsection
edit.blade.php:
#extends('layouts.app')
#section('content')
Go back
<div class="container" style="width:50%; margin-left:350px;margin-top:20px">
<h1>Edit Course</h1>
{!! Form::open(['action' => ['CoursesController#update', $course->course_code], 'method'=>'POST']) !!}
<div class="form-group">
{{Form::label('course_code', 'Course code')}}
{{Form::text('course_code', $course->course_code,['placeholder'=>'Course code', 'class'=>'form-control col-md-3'])}}
</div>
<div class="form-group">
{{Form::label('course_name', 'Course name')}}
{{Form::text('course_name', $course->course_name,['placeholder'=>'Course name', 'class'=>'form-control col-md-7'])}}
</div>
{{Form::hidden('_method', 'PUT')}}
{{Form::submit('Add Course',['class'=>'btn btn-primary'])}}
{!! Form::close() !!}
</div>
#endsection
my model code:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Course extends Model
{
//
}
Where did I go wrong and how can I fix this error?
The ::find() method will only return objects with a matching primary key, you cannot pass other values. If not object is found with this primary key, null will be returned and you can't get a property from null.
Either change your primary key, or better, update your query:
$course = Course::where('course_code', $course_code)->first();
It's also a good idea to add a check if the query actually returned something. Just to be sure to avoid the same error in the future:
if ($course === null) {
abort(404); // Show 404 page if course does not exist
}
If you change the primary key, don't forget to update the following properties on your Course model.
// The column name of your primary key.
protected $primaryKey = 'your_key_name';
// Indicating that the primary key is not a number.
public $incrementing = false;
I think here course_code is not primary key..so you can't get it by using find
Two ways.
1st passing your primary key(**id**) & update
2nd using where
$course = Course::where('course_code',$course_code)->first();
then update.
here you want to change the value of course_code also.so 1st one is correct for you passing id & use find & update that
You are using the wrong value to generate links for your model. You need to be using the id not course_code. The find method will use the primary key of the model to do its search.
Edit
Now you are passing the correct value for the parameter so you can use find on the model. If you want to use a different value other than id you can do that but you have to adjust your query to find it by a different field.
If you keep using course_code instead of id you just have to search based on that field:
$course = Course::where('course_code', $course_code)->first();

Laravel 5.2 belongstoMany in views

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');
}

Password Reminder - Change email column

I'm trying to do a Password Reminder in Laravel 4
I've setup the Controller, But keep getting the error :
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'email' in
'where clause' (SQL: select * from users where users.deleted_at
is null and email is null limit 1
This would be correct as my users' table has the column "user_email" not "email
Is their any particular way that I can change the query that Laravel runs, to a new / different where that says user_email instead of email.
My controller is as follows :
class RemindersController extends Controller {
/**
* Display the password reminder view.
*
* #return Response
*/
public function getRemind()
{
return View::make('users/password_remind');
}
/**
* Handle a POST request to remind a user of their password.
*
* #return Response
*/
public function postRemind()
{
switch ($response = Password::remind(Input::only('email')))
{
case Password::INVALID_USER:
return Redirect::back()
->with('error', Lang::get($response));
case Password::REMINDER_SENT:
return Redirect::back()
->with('status', Lang::get($response));
}
}
/**
* Display the password reset view for the given token.
*
* #param string $token
* #return Response
*/
public function getReset($token = null)
{
if (is_null($token)) App::abort(404);
return View::make('password.reset')->with('token', $token);
}
/**
* Handle a POST request to reset a user's password.
*
* #return Response
*/
public function postReset()
{
$credentials = Input::only(
'email',
'password',
'password_confirmation',
'token'
);
$response = Password::reset($credentials, function($user, $password)
{
$user->password = Hash::make($password);
$user->save();
});
switch ($response)
{
case Password::INVALID_PASSWORD:
case Password::INVALID_TOKEN:
case Password::INVALID_USER:
return Redirect::back()
->with('error', Lang::get($response));
case Password::PASSWORD_RESET:
return Redirect::to('/');
}
}
}
Users Model
<?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, SoftDeletingTrait;
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'users';
/**
* The attributes excluded from the model's JSON form.
*
* #var array
*/
protected $hidden = array('user_password', 'remember_token');
protected $dates = ['deleted_at'];
protected $primaryKey = "user_id";
protected $fillable = array('user_email');
public static $rules = array(
'user_firstname' => 'required|alpha',
'user_surname' => 'required|alpha',
'user_email' => 'required|email|unique:users',
'user_password' => 'required',
'user_telephone' => 'required|numeric'
);
/**
* Get the password for the user.
*
* #return string
*/
public function getAuthPassword()
{
return $this->user_password;
}
public function getEmail() {
return $this->user_email;
}
public function getReminderEmail() {
return $this->user_email;
}
public function getUserByEmail( $user_email )
{
return $this->where('user_email', '=', $user_email)->first();
}
}
and last but not least, My view :
{{ Form::open(array('url' => 'password/remind')) }}
#if (Session::has('error'))
<p style="color: red;">{{ Session::get('error') }}</p>
#elseif (Session::has('status'))
<p>{{ Session::get('status') }}</p>
#endif
<div class="form-group">
<label>Your Email Address</label>
<input name="user_email" type="email" class="form-control" placeholder="Your Email Address" data-error="Please enter your Email Address" value="{{{ Input::old('user_email') }}}" required>
<span class="glyphicon form-control-feedback" aria-hidden="true"></span>
<div class="help-block with-errors"></div>
</div><!-- /.form-group -->
<div class="text-center">
<button type="submit" class="cta">Reset Password</button>
</div><!-- /.text-center -->
{{ Form::close() }}

Laravel Auth::attempt() return false [duplicate]

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)

Categories