How to use Service Layer in laravel 5.5 - php

I am working in Laravel 5.5, and I don't want to write logic in controller, I would like to separate logic form Controller. write something like interface and services like what we user to do in "ASP.NET MVC" frameworks.

I also switched to Laravel coming from Zend and missed my Services. To sooth myself I have implemented a Service namespace which sits in namespace App\Services. In there I do all my Model / Validation handeling. I have experienced no loss of functionality or anything.
<?php
namespace App\Http\Controllers;
use App\Services\Contact as ContactService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Lang;
class IndexController extends Controller
{
/**
* Create a new controller instance.
*
* #param Request $request
* #return void
*/
public function __construct(Request $request)
{
$this->_request = $request;
}
/**
* Standard contact page
*
* #return contact page
*/
public function contact(ContactService $contactService)
{
$errors = null;
$success = false;
if ($this->_request->isMethod('post')) {
$validator = $contactService->validator($this->_request->all());
if ($validator->fails()) {
$errors = $validator->errors();
} else {
$contactService->create($validator->getData());
$success = true;
}
}
return view('pages/contact', ['errors' => $errors, 'success' => $success]);
}
}
Example of Service:
<?php
namespace App\Services;
use Validator;
use Mail;
use App\Models\Contact as ContactModel;
class Contact
{
/**
* Get a validator for a contact.
*
* #param array $data
* #return \Illuminate\Contracts\Validation\Validator
*/
public function validator(array $data)
{
return Validator::make($data, [
'email' => 'required|email|max:255',
'phone' => 'max:255',
'firstName' => 'required|max:255',
'lastName' => 'required|max:255',
'message' => 'required'
]);
}
/**
* Create a new contact instance after a valid form.
*
* #param array $data
* #return ContactModel
*/
public function create(array $data)
{
$data = [
'email' => $data['email'],
'firstName' => $data['firstName'],
'lastName' => $data['lastName'],
'language' => $data['language'],
'phone' => $data['phone'],
'message' => $data['message']
];
// Send an email
Mail::send('emails.contact', ['data' => $data], function ($m) use ($data) {
$m->from(config('mail.from.address'), config('mail.from.name'));
$m->to(env('MAIL_TO', 'hello#world.com'), env('MAIL_TO'))->subject('Contact form entry from: ' . $data['firstName']);
});
return ContactModel::create($data);
}
}

Related

Laravel 5.2 - Send welcome email after user registered

I would like to send some emails after users registered.
But, it doest work. I didn't receive an email in my SMTP mail. I'm using mailtrap.io.
I have set up a Registered event with a listener to NewUserRegistered.
Within my NewUserRegistered Controller\Auth\AuthController as follows:
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\User;
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;
use Illuminate\Foundation\Auth\ThrottlesLogins;
use Log;
use Validator;
use Mail;
class AuthController extends Controller {
/*
|--------------------------------------------------------------------------
| Registration & Login Controller
|--------------------------------------------------------------------------
|
| This controller handles the registration of new users, as well as the
| authentication of existing users. By default, this controller uses
| a simple trait to add these behaviors. Why don't you explore it?
|
*/
use AuthenticatesAndRegistersUsers, ThrottlesLogins;
/**
* Where to redirect users after login / registration.
*
* #var string
*/
protected $redirectTo = '/';
/**
* Create a new authentication controller instance.
*
* #return void
*/
public function __construct() {
$this->middleware($this->guestMiddleware(), [
'except' => 'logout'
]);
}
/**
* Get a validator for an incoming registration request.
*
* #param array $data
* #return \Illuminate\Contracts\Validation\Validator
*/
protected function validator(array $data) {
return Validator::make($data, [
'name' => 'required|max:255',
'matric' => 'required|max:5',
'faculty' => 'required|max:255',
'email' => 'required|email|max:255|unique:users',
'password' => 'required|min:6|confirmed',
'address' => 'required',
'phone' => 'required',
]);
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return User
*/
protected function create(array $data) {
return User::create([
'name' => $data['name'],
'matric' => $data['matric'],
'faculty' => $data['faculty'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
'address' => $data['address'],
'phone' => $data['phone'],
]);
event(new Registered($user));
//sreturn User;
}
}
Within my Registered Events as follows:
<?php
namespace App\Events;
use App\Events\Registered;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
class Registered extends Event
{
use SerializesModels;
/**
* #var
*/
public $user;
/**
* Create a new event instance.
*
* #param $user
*/
public function __construct($user)
{
//
$this->user = $user;
}
/**
* Get the channels the event should be broadcast on.
*
* #return array
*/
public function broadcastOn()
{
return [];
}
}
Within my NewUserRegistered Listeners as follows:
<?php
namespace App\Listeners;
use App\Events\Registered;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Mailer;
use Mail;
class NewUserRegistered
{
/**
* Create the event listener.
*
* #return void
*/
public function __construct(Mailer $mailer)
{
$this->mailer = $mailer;
}
/**
* Handle the event.
*
* #param Registered $event
* #return void
*/
public function welcome(Registered $event)
{
$data = [
'user' => $event->user,
'from' => 'hello#test.dev',
'subject' => 'Welcome to test'
];
$this->mailer->send('emails.auth.verify', $data, function($message) {
$message->to($data['user']->email, $data['user']->matric)
->subject($data['subject']);
});
}
}
Your event never fires because you're returning the user after creating them. Your code should have thrown errors when you attempted. Change your code to this.
use App\Events\Registered;
protected function create(array $data)
{
$user = User::create([
'name' => $data['name'],
'matric' => $data['matric'],
'faculty' => $data['faculty'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
'address' => $data['address'],
'phone' => $data['phone'],
]);
event(new Registered($user));
return $user;
}
Also be sure to register your event listener.
A couple potential issues with your solution could be:
In Controller\Auth\AuthController, you haven't imported the Registered event into the namespace. Try adding use App\Events\Registered; to the top.
In NewUserRegistered, you've defined a #welcome method, but Laravel event listeners expect a #handle method. See the Laravel docs on Events for more information.
Beyond that, you could be experiencing issues with your Mailtrap credentials.

Laravel 5.2 Storing data in another Database after Registration

Im using the default registration and log in form of laravel. What i want to happen is how do i store a data after the user successfully register. I tried doing this but its not storing any data in the Time_tracker table and there is no any error occured. Can some one help me?
AuthController.php
<?php
namespace App\Http\Controllers\Auth;
use App\User;
use Validator;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ThrottlesLogins;
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;
use Illuminate\Mail\Mailer;
use Illuminate\Http\Request;
use App\Time_tracker;
class AuthController extends Controller
{
/*
|--------------------------------------------------------------------------
| Registration & Login Controller
|--------------------------------------------------------------------------
|
| This controller handles the registration of new users, as well as the
| authentication of existing users. By default, this controller uses
| a simple trait to add these behaviors. Why don't you explore it?
|
*/
use AuthenticatesAndRegistersUsers, ThrottlesLogins;
/**
* Where to redirect users after login / registration.
*
* #var string
*/
protected $redirectTo = 'maintenance';
/**
* Create a new authentication controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware($this->guestMiddleware(), ['except' => 'logout']);
}
/**
* Get a validator for an incoming registration request.
*
* #param array $data
* #return \Illuminate\Contracts\Validation\Validator
*/
protected function validator(array $data)
{
return Validator::make($data, [
'name' => 'required|max:255',
'company' => 'required|max:255',
'email' => 'required|email|max:255|unique:users',
'telephone' => 'required|max:255',
'password' => 'required|min:6|confirmed',
'g-recaptcha-response' => 'required|captcha',
]);
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return User
*/
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'company' => $data['company'],
'email' => $data['email'],
'telephone' => $data['telephone'],
'password' => bcrypt($data['password']),
]);
$user = new Time_tracker;
$user->current_time = 0;
$user->purchase_time = 0;
$user->status = 'not_paid';
$user->user_id = $id;
$user->save();
}
}
You are returning the created user that's why the code below it isn't running, you should remove return and place it at the end in this way:
protected function create(array $data)
{
$user = User::create([ // <------ Removed 'return' from the front of this line
'name' => $data['name'],
'company' => $data['company'],
'email' => $data['email'],
'telephone' => $data['telephone'],
'password' => bcrypt($data['password']),
]);
$time_tracker = new Time_tracker();
$time_tracker->current_time = 0;
$time_tracker->purchase_time = 0;
$time_tracker->status = 'not_paid';
$time_tracker->user_id = $user->id; // <----- This would be '$user->id' instead of '$id'
$time_tracker->save();
return $user; // <----- 'return' added at the end of the method
}
Hope this helps!

Pass array parameter from controller to Mailable class. Laravel

I am trying to send email after user successfully register. so right now i am stuck to pass data in email template.I am sending email with Mailable . so from my Register Controller i using like that Mail::to('example#email.com','User Name')->send(new Verify_Email())
So my question is how to pass array param into new Verify_Email()Massage build class.and so then how to pass from Verify_Email to View.
RegisterController.php
public function __construct()
{
$this->middleware('guest');
}
/**
* Get a validator for an incoming registration request.
*
* #param array $data
* #return \Illuminate\Contracts\Validation\Validator
*/
protected function validator(array $data)
{
return Validator::make($data, [
'firstname' => 'required|max:255',
'lastname' => 'required|max:255',
'email' => 'required|email|max:255|unique:users',
'password' => 'required|min:6|confirmed',
]);
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return User
*/
protected function create(array $data)
{
$confirmation_code = str_random(30);
$user = User::create([
'firstname' => $data['firstname'],
'lastname' => $data['lastname'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
'confirmation_code' => $confirmation_code
]);
$email_data = ([
'name' => $data['firstname'].' '.$data['lastname'],
'link' => '#'
]);
Mail::to('example#email.com','User Name')->send(new Verify_Email());
return $user;
}
Verify_Email.php
class Verify_Email extends Mailable
{
use Queueable, SerializesModels;
/**
* Create a new message instance.
*
* #return void
*/
public function __construct()
{
//
}
/**
* Build the message.
*
* #return $this
*/
public function build()
{
return $this->from('example#example.com')
->view('emails.verify-user');
//--------------------------> **Send data to view**
//->with([
//'name' => $this->data->name,
//'link' => $this->data->link
//]);
}
Please follow this approach
Pass the inputs to the Verify_Email constructor and use $this->variable to pass them onto the view.
Mail::to('example#email.com','User Name')->send(new Verify_Email($inputs))
and then this in Verify_Email
class Verify_Email extends Mailable {
use Queueable, SerializesModels;
protected $inputs;
/**
* Create a new message instance.
*
* #return void
*/
public function __construct($inputs)
{
$this->inputs = $inputs;
}
/**
* Build the message.
*
* #return $this
*/
public function build()
{
return $this->from('example#example.com')
->view('emails.verify-user')
->with([
'inputs' => $this->inputs,
]);
}
}
Hope that answers your question :)

Insert in two tables when registering users in Laravel

I'm using the default Laravel 5.1 user registration. I have two tables: users and shops. When user registers, the app should insert a user in the table users, get the id and use it to register a shop. I've been reading the default AuthController.php but i didn't find anything. Here is the AuthController if it helps.
<?php
namespace App\Http\Controllers\Auth;
use App\User;
use Validator;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ThrottlesLogins;
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;
class AuthController extends Controller
{
/*
|--------------------------------------------------------------------------
| Registration & Login Controller
|--------------------------------------------------------------------------
|
| This controller handles the registration of new users, as well as the
| authentication of existing users. By default, this controller uses
| a simple trait to add these behaviors. Why don't you explore it?
|
*/
use AuthenticatesAndRegistersUsers, ThrottlesLogins;
/**
* Create a new authentication controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest', ['except' => 'getLogout']);
}
/**
* Get a validator for an incoming registration request.
*
* #param array $data
* #return \Illuminate\Contracts\Validation\Validator
*/
protected function validator(array $data)
{
return Validator::make($data, [
//'name' => 'required|max:255',
'email' => 'required|email|max:255|unique:users',
'password' => 'required|confirmed|min:6',
]);
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return User
*/
protected function create(array $data)
{
return User::create([
//'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
]);
}
/**
* Get the path to the login route.
*
* #return string
*/
public function loginPath()
{
return route('login');
}
/**
* Get the post register / login redirect path.
*
* #return string
*/
public function redirectPath()
{
return route('home');
}
}
Solved, but now I have a Integrity constraint violation. Is this code correct?
protected function create(array $data)
{
$user = new User([
'email' => $data['email'],
'password' => bcrypt($data['password'])
]);
$user->role = 'shop_owner';
$user->remember_token = str_random(10);
$user->save();
$userId = $user->id;
Shop::create([
'name' => $data['s_name'],
'address' => $data['s_address'],
'CP' => $data['s_pcode'],
'Telephone' => $data['s_tlf'],
'contact_name' => $data['cp_name'],
'contact_num' => $data['cp_tlf'],
'id_user' => $userId
]);
return $user;
}
There you go:
protected function create(array $data)
{
$user = User::create([
//'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
]);
$userId = $user->id;
Shop::create([... use $userId here ...]);
return $user;
}
This goes to your controller:
public function store(Request $request) {
$user = User::create(Input::all());
$user->save();
$shop = Shop::create([..enter shop attributes or leave blank..]);
$user->shop()->save($shop);
}
You need to place the following code at the top of the Auth Controller
use App\Shop;

How use the hash in my custom login laravel5

I am developing my own login and I have the following code
public function login(Request $request ) {
$email = \Request::input('email');
$password = \Request::input('password');
if (Auth::attempt(['email' => $email, 'password' => $password]))
{
//echo "success";
return redirect('home');
}
else {
return "fail";
}
}
And the CreateUserRequest
<?php namespace App\Http\Requests;
use App\Http\Requests\Request;
class CreateUserRequest extends Request {
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [
'nif' => 'required | max:9 ',
'name' => 'required | max:255',
'email' => 'required',
'cognoms' => 'required | max:255',
'birthday' => 'required',
'password' => 'required | confirmed',
'password_confirmation' => 'required',
'municipios' => 'required | Integer|Min:1',
'presentacion' => 'required',
'file' => 'required'
];
}
}
My register controller
public function registro(CreateUserRequest $request){
$usuario = new User();
$usuario->nif = \Request::input('nif');
$usuario->name = \Request::input('name');
$usuario->cognoms = \Request::input('cognoms');
$usuario->birthday = \Request::input('birthday');
$usuario->email = \Request::input('email');
$usuario->password= \Request::input('password');
/**Foto del usuario**/
$file = \Request::file('file');
$fileName = $file->getClientOriginalName();
$file->move(public_path().'/uploads/', $fileName);
$usuario->file = 'uploads/'.$fileName.'';
$usuario->save();
/**Asignamos el rol a la tabla intermedia***/
$user = User::find($usuario->id);
$user->roles()->attach(1);
return redirect('/');
}
The model
<?php namespace App;
use Illuminate\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;
class User extends Model implements AuthenticatableContract, CanResetPasswordContract {
use Authenticatable, CanResetPassword;
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'users';
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = ['nif','name','cognoms','email', 'password','idempresa','id_poblacion','id_online',];
/**
* The attributes excluded from the model's JSON form.
*
* #var array
*/
protected $hidden = ['password', 'remember_token'];
public function empresa()
{
return $this->belongsTo('Empresa');
}
public function municipio()
{
return $this->belongsTo('App\Ciudad','id_poblacion');
}
public function roles()
{
return $this->belongsToMany('App\Rol')->withPivot('user_id','rol_id');
}
public function mensajes()
{
return $this->belongsToMany('App\User')->withPivot('id_emisor','id_receptor');
}
public function subastas(){
return $this->hasMany('App\Subasta','id_creador','id');
}
public function pujas(){
return $this->hasMany('App\Puja','id_subasta','id');
}
}
When I put the password , the laravel create the user andthe field password in database is white.
Please try this:
public function registro(CreateUserRequest $request){
$file = $request->file('file');
$fileName = $file->getClientOriginalName();
$file->move(public_path().'/uploads/', $fileName);
$user = User::create([
'nif' => $request->input('nif'),
'name' => $request->input('name'),
'cognoms' => $request->input('cognoms'),
'birthday' => $request->input('birthday'),
'email' => $request->input('email'),
'password' => \Hash::make($request->input('password')),
'file' => 'uploads/'.$fileName.'',
]);
/**Asignamos el rol a la tabla intermedia***/
$user = User::find($user->id);
$user->roles()->attach(1);
return redirect('/');
}

Categories