I want to load the relation of order with customer but it is returning null in the postman
Customer Model
<?php
namespace App;
use Tymon\JWTAuth\Contracts\JWTSubject;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
class Customer extends Authenticatable implements JWTSubject
{
use Notifiable;
protected $fillable = [
'first_name',
'last_name',
'phone_number',
'postal_code',
'email',
'preferred_method_to_contact',
'password',
'address',
];
protected $hidden = [
'password', 'remember_token',
];
protected $casts = [
'email_verified_at' => 'datetime',
];
public function getNameAttribute()
{
$name = $this->first_name . " " . $this->last_name;
return $name;
}
public function orders()
{
return $this->hasMany('App\Order');
}
public function getJWTIdentifier()
{
return $this->getKey();
}
/**
* Return a key value array, containing any custom claims to be added to the JWT.
*
* #return array
*/
public function getJWTCustomClaims()
{
return [];
}
}
Order Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Order extends Model
{
protected $fillable = [
'first_name',
'last_name',
'email',
'phone_number',
'post_code',
'address',
'alternative_address',
'property_type',
'property_type_other',
'contract_type',
'contract_type_other',
'no_of_bedrooms',
'no_of_bathrooms',
'customer_id',
'best_day',
'best_time',
'type_of_cleaning',
];
public function customers()
{
return $this->belongsTo('App\Customer');
}
}
Order Resource
<?php
namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\JsonResource;
class OrderResource extends JsonResource
{
/**
* Transform the resource into an array.
*
* #param \Illuminate\Http\Request $request
* #return array
*/
public function toArray($request)
{
/*return parent::toArray($request);*/
return [
'id' => $this->id,
'first_name' => $this->first_name,
'last_name' => $this->last_name,
'email' => $this->email,
'phone_number' => $this->phone_number,
'post_code' => $this->post_code,
'address' => $this->address,
'alternative_address' => $this->alternative_address,
'property_type' => $this->property_type,
'property_type_other' => $this->property_type_other,
'contract_type' => $this->contract_type,
'contract_type_other' => $this->contract_type_other,
'no_of_bedrooms' => $this->no_of_bedrooms,
'phone_number' => $this->phone_number,
'no_of_bathrooms' => $this->no_of_bathrooms,
'customer' => new CustomerResource($this->whenLoaded('customers')),
];
}
}
Customer Resource
<?php
namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\JsonResource;
class CustomerResource extends JsonResource
{
/**
* Transform the resource into an array.
*
* #param \Illuminate\Http\Request $request
* #return array
*/
public function toArray($request)
{
/*return parent::toArray($request);*/
return [
'id' => $this->id,
'first_name' => $this->first_name,
'last_name' => $this->last_name,
'email' => $this->email,
];
}
}
Here is the function in OrderController which is responsible for sending the JSON response
public function store(Request $request)
{
$validator = Validator::make($request->all(), [
'first_name' => ['required', 'string', 'max:10'],
'last_name' => ['required', 'string', 'max:10'],
'email' => ['required', 'string', 'email', 'max:50'],
'phone_number' => ['required', 'string', 'max:30'],
'post_code' => ['required', 'string', 'max:30'],
'address' => ['required', 'string', 'max:300'],
'alternative_address' => ['required', 'string', 'max:300'],
'property_type' => ['required', 'string', 'max:30'],
'contract_type' => ['required', 'string', 'max:30'],
'no_of_bedrooms' => ['required', 'string', 'max:30'],
'type_of_cleaning' => ['required', 'string', 'max:30'],
'best_day' => ['required', 'string', 'max:30'],
'best_day' => ['required', 'string', 'max:30'],
]);
if ($validator->fails()) {
return response()->json($validator->errors(), 422);
}
// $customer = Customer::findOrFail($request->customer_id);
$order = Order::create($request->all());
// $order = Order::create();
$order->load(array('customers'));
return new OrderResource($order);
}
I want the customer details to be loaded along with the order.
Somehow I managed to fix that problem. Actually the ManyToOne relationship function was not recognizing the customers. The customers function targets the many-to-one so it should be singular instead of plural according to the standards of laravel.
public function customer()
{
return $this->belongsTo('App\Customer');
}
Similarly in the OrderController
$order->load(array('customer')); // <- make it singular as well
In the OrderResource
'customer' => new CustomerResource($this->whenLoaded('customer')), // <- make it singular
Related
i am trying to send an notification custom email to reference email when user register
using Mail Inception in Laravel 8
i don't need to send email to user himself i want to send that email to email reference which is user will write it in registration field
CreateNewUser Default Controller from Laravel
<?php
namespace App\Actions\Fortify;
use App\Models\User;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Laravel\Fortify\Contracts\CreatesNewUsers;
use Laravel\Jetstream\Jetstream;
use Carbon\Carbon;
use Illuminate\Support\Facades\Mail;
use App\Mail\RefMail;
class CreateNewUser implements CreatesNewUsers
{
use PasswordValidationRules;
/**
* Validate and create a newly registered user.
*
* #param array $input
* #return \App\Models\User
*/
public function create(array $input)
{ $massage = ['tc_no_pasaport_no.unique'=> 'Sorry, internal error .',
'phone.unique'=>'Sorry, internal error .' ];
Validator::make($input, [
'phone' => ['required', 'string', 'max:255','unique:users'],
'name' => ['required', 'string', 'max:255'],
'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
'tc_no_pasaport_no' => ['required','max:11','unique:users'],
'place_of_birth' => ['required'],
'date_of_birth' => ['required'],
'educational_status' => ['required','string'],
'school_department' => ['required'],
'address' => ['required'],
'password' => $this->passwordRules(),
'terms' => Jetstream::hasTermsAndPrivacyPolicyFeature() ? ['required', 'accepted'] : '',
],$massage)->validate();
$users = User::where('email', '=', $input['email'])->first();
if ($users === null) {
return User::create([
'name' => $input['name'],
'email' => $input['email'],
'phone' => $input['phone'],
'password' => Hash::make($input['password']),
'membership_status' =>'pasif',
'membership_type' =>'standard',
'last_activation_date' => Carbon::now(),
'membership_end_date' => Carbon::now(),
'temporary_id' => random_int(1000000, 9999999),
'tc_no_pasaport_no' => $input['tc_no_pasaport_no'],
'place_of_birth' => $input['place_of_birth'],
'date_of_birth' => $input['date_of_birth'],
'educational_status' => $input['educational_status'],
'school_department' => $input['school_department'],
'Institution_and_unit' => $input['Institution_and_unit'],
'address' => $input['address'],
'referance_email' => $input['referance_email'],
'letter_of_Intent'=>$input['letter_of_Intent'],
'created_at' => Carbon::now(),
]);}
$data = [
'name' => $input->name,
'referance_email' => $input->referance_email,
];
Mail::to($input->referance_email)->send(new RefMail ($data));
}
}
RefMail code
<?php
namespace App\Mail;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
class RefMail extends Mailable
{
use Queueable, SerializesModels;
public $data;
/**
* Create a new message instance.
*
* #return void
*/
public function __construct()
{
$this->data = $data;
}
/**
* Build the message.
*
* #return $this
*/
public function build()
{ $sendemail =$this->data;
return $this->from('info#geleceginbilimi.com')->view('mail.ref_mail',compact('sendemail'))->subject('confirm recommended email');
}
}
ref_mail.blade.php
<h1>{{$sendemail->name}}</h1>
First replace OrderMail with RefMail
Mail::to($input->referance_email)->send(new RefMail($data));
Second add $data variable to the constructor of RefMail Class:
public function __construct($data)
{
$this->data = $data;
}
Third :
<h1>{{$sendemail['name']}}</h1>
For more : https://laravel.com/docs/8.x/mail#writing-mailables
i want to use sub fillable array in model
protected $fillable = [
'requestInfo'=>[
'companyname',
'province',
'district',
'village',
'phone',
],
'owner'=>[
'fullname',
'province',
'district',
'village',
'nationality',
'fax',
'phone',
'factorynamela',
'factorynameen',
'located',
'locatprovince',
'locatdistrict',
'locatvillage',
'locatein'
],
];
but have error:
C:\xampp\htdocs\mocbizrrequest\blog\vendor\laravel\framework\src\Illuminate\Database\Eloquent\Concerns\GuardsAttributes.php
/**
* Determine if the model is totally guarded.
*
* #return bool
*/
public function totallyGuarded()
{
return count($this->getFillable()) == 0 && $this->getGuarded() == ['*'];
}
/**
* Get the fillable attributes of a given array.
*
* #param array $attributes
* #return array
*/
protected function fillableFromArray(array $attributes)
{
if (count($this->getFillable()) > 0 && ! static::$unguarded) {
return array_intersect_key($attributes, array_flip($this->getFillable()));
}
return $attributes;
}
}
Arguments
"array_flip(): Can only flip STRING and INTEGER values!"
ErrorException (E_WARNING)
array_flip(): Can only flip STRING and INTEGER values!
please help me thank
i want to use sub fillable array in model
in my model file
<?php
/**
* Created by IntelliJ IDEA.
* User: EXTRA
* Date: 4/5/2019
* Time: 11:48 AM
*/
namespace App\Model;
use Jenssegers\Mongodb\Eloquent\Model as Eloquent;
class RequestFrom extends Eloquent
{
protected $connection = 'mongodb';
protected $collection = 'requestForm';
protected $fillable = [
'requestInfo'=>[
'companyname',
'province',
'district',
'village',
'phone',
],
'owner'=>[
'fullname',
'province',
'district',
'village',
'nationality',
'fax',
'phone',
'factorynamela',
'factorynameen',
'located',
'locatprovince',
'locatdistrict',
'locatvillage',
'locatein'
],
];
in controller file
namespace App\Http\Controllers;
use App\Model\RequestFrom;
use Illuminate\Http\Request;
class RequestFromController extends Controller
{
public function index()
{
$requestForms = RequestFrom::all();
return view('requestForm.index',compact('requestForms'))
->with('i', (request()->input('page', 1) - 1) * 5);
}
public function create()
{
return view('requestForm.create');
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
request()->validate([
'requestInfo'=>[
'companyname' => 'required',
'province' => 'required',
'district' => 'required',
'village' => 'required',
'phone' => 'required'
],
'owner'=>[
'fullname' => 'required',
'province' => 'required',
'district' => 'required',
'village' => 'required',
'nationality' => 'required',
'fax' => 'required',
'phone' => 'required',
'factorynamela' => 'required',
'factorynameen' => 'required',
'located' => 'required',
'locatprovince' => 'required',
'locatdistrict' => 'required',
'locatvillage' => 'required',
'locatein' => 'required'
],
]);
RequestFrom::create($request->all());
return redirect()->route('requestForm.index')
->with('success','created successfully.');
}
I use postman to add user in my laravel project I get null token but the user has added
why?
{
"token": null }
how I can fix this error?
I use laravel 5.6
and
this my user model :
<?php
namespace App;
use Tymon\JWTAuth\Contracts\JWTSubject;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password','username','lastname','tel','tel',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
public function getJWTIdentifier()
{
return $this->getKey();
}
/**
* Return a key value array, containing any custom claims to be added to the JWT.
*
* #return array
*/
public function getJWTCustomClaims()
{
return [];
}
}
and this my register controller
<?php
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\User;
use JWTFactory;
use JWTAuth;
use Validator;
use Response;
class APIRegisterController extends Controller
{
//
public function register( Request $request){
$validator = Validator::make($request -> all(),[
'email' => 'required|string|email|max:255|unique:users',
'username' =>'required',
'tel' => 'required',
'name' => 'required',
'lastname' => 'required',
'adress' => 'required',
'password'=> 'required'
]);
if ($validator -> fails()) {
# code...
return response()->json($validator->errors());
}
User::create([
'name' => $request->get('name'),
'email' => $request->get('email'),
'tel' => $request->get('tel'),
'username' => $request->get('username'),
'lastname' => $request->get('lastname'),
'adress' => $request->get('adress'),
'password'=> bcrypt($request->get('password'))
]);
$user = User::first();
$token = JWTAuth::fromUser($user);
return Response::json( compact('token'));
}
}
and this is my controller
<?php
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\User;
use Illuminate\Support\Facades\Response;
use Tymon\JWTAuth\Facades\JWTAuth;
use Tymon\JWTAuth\Facades\JWTFactory;
use Validator;
class APIRegisterController extends Controller
{
//
public function register( Request $request){
$validator = Validator::make($request -> all(),[
'email' => 'required|string|email|max:255|unique:users',
'username' =>'required',
'tel' => 'required',
'name' => 'required',
'lastname' => 'required',
'adress' => 'required',
'password'=> 'required'
]);
if ($validator -> fails()) {
# code...
return response()->json($validator->errors());
}
User::create([
'name' => $request->get('name'),
'email' => $request->get('email'),
'tel' => $request->get('tel'),
'username' => $request->get('username'),
'lastname' => $request->get('lastname'),
'adress' => $request->get('adress'),
'password'=> bcrypt($request->get('password'))
]);
$user = User::first();
$token = JWTAuth::fromUser($user);
return Response::json( compact('token'));
}
}
I alreday get a error and this my question question and I fiwx it
how I can fix this error?
I use laravel 5.6
I already had a similar problem before, but I realize my$user->password holds the encrypted password, not the pain text required for login(). Change your code to call
$token = JWTAuth::fromUser($user);
with $user holding the plain text password comming from $request
I solve my problem adding if condition on register function after create user
if ($this->loginAfterSignUp) {
$token = $this->login($request);
}
return $this->respondWithToken($token);
I'm trying to use the RegisterController in Laravel, but I can't get the Validator to work. I don't understand what the problem is, because it should just take an array and validate it.
When I try to send a JSON with the right fields to the register route, I get this error:
BadMethodCallException: Method validate does not exist. in file /home/deb85528n3/vendor/laravel/framework/src/Illuminate/Support/Traits/Macroable.php on line 96
Below is my code:
protected function validator(array $data)
{
$validator = Validator::make($data,
[
'first_name' => 'required|string|max:255',
'last_name' => 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:users',
'password' => 'required|string|min:6|confirmed',
'birth_year' => 'required|integer',
'lat' => 'required',
'lon' => 'required',
]);
echo $validator->errors();
if ($validator->fails())
{
return response()->json(['errors'=>$validator->errors()]);
}
if ($validator->passes())
{
$response = "validator passed";
return response()->json($response);
}
}
I also tried using the Validator in a different way:
public function validator(Request $request){
$validator = Validator::make($request->all(), [
'first_name' => 'required|string|max:255',
'last_name' => 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:users',
'password' => 'required|string|min:6|confirmed',
'birth_year' => 'required|integer|min:4',
'lat' => 'required|numeric',
'lon' => 'required|numeric',
]);
}
But then I get this error:
Symfony\Component\Debug\Exception\FatalThrowableError: Type error: Argument 1 passed to App\Http\Controllers\Auth\RegisterController::validator() must be an instance of App\Http\Controllers\Auth\Request, array given, called in /home/deb85528n3/vendor/laravel/framework/src/Illuminate/Foundation/Auth/RegistersUsers.php on line 31 in file /home/deb85528n3/app/Http/Controllers/Auth/RegisterController.php on line 103
Edited to include the whole RegisterController:
<?php
namespace App\Http\Controllers\Auth;
use App\User;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Validator;
use Illuminate\Foundation\Auth\RegistersUsers;
class RegisterController extends Controller
{
use RegistersUsers;
/**
* Where to redirect users after registration.
*
* #var string
*/
protected $redirectTo = '/home';
/**
* Create a new controller instance.
*
* #return void
*/
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)
{
$validator = Validator::make($data, [
'first_name' => 'required|string|max:255',
'last_name' => 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:users',
'password' => 'required|string|min:6|confirmed',
'birth_year' => 'required|integer|min:4',
'lat' => 'required|numeric',
'lon' => 'required|numeric',
]);
echo $validator->errors();
if ($validator->fails())
{
return response()->json(['errors'=>$validator->errors()]);
}
if ($validator->passes())
{
$response = "validator passed";
return response()->json($response);
}
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return \App\User
*/
protected function create(array $data)
{
//maybe check if facebook login here?
return User::create([
'first_name' => $data['first_name'],
'last_name' => $data['last_name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
'birth_year' => $data['birth_year'],
'lat' => $data['lat'],
'lon' => $data['lon'],
]);
}
}
change your function name
use Validator;
add this in your controller,
remove this
public function validator(Request $request){
Write your validation rules in model like below
public static function rules()
{
return [
'first_name' => 'required|string|max:255',
'last_name' => 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:users',
'password' => 'required|string|min:6|confirmed',
'birth_year' => 'required|integer|min:4',
'lat' => 'required|numeric',
'lon' => 'required|numeric',
];
}
and call this rule in your controller
$validator = Validator::make($request->all(), "Your model Name"::rules());
if ($validator->fails()) {
//throw exception
}
The register method calls the validator method and passes through an array, it then expects that an instance of \Illuminate\Contracts\Validation\Validator to be returned.
Unless you're needed to override the default responses for registering a user, you should just be able to have:
public function validator(array $data)
{
return Validator::make($data, [
'first_name' => 'required|string|max:255',
'last_name' => 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:users',
'password' => 'required|string|min:6|confirmed',
'birth_year' => 'required|integer|min:4',
'lat' => 'required|numeric',
'lon' => 'required|numeric',
]);
}
My controller is like this :
public function create()
{
$data = array(
'email' => 'chelsea#gmail.com'
);
$data = Order::where('email', $data['email'])->first();
dd($data);
}
My model order is like this :
<?php
namespace App\Models;
use Eloquent as Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Notifications\Notifiable;
class Order extends Model
{
use SoftDeletes, Notifiable;
public $table = 'orders';
protected $dates = ['deleted_at'];
public $fillable = [
'number',
'user_id',
'store_id',
'total_amount',
'total_product',
'service_amount',
'status',
'checkout_at'
];
protected $casts = [
'number' => 'string',
'user_id' => 'integer',
'store_id' => 'integer',
'total_amount' => 'integer',
'total_product' => 'integer',
'service_amount' => 'integer',
'status' => 'integer',
'checkout_at' => 'date'
];
public static $rules = [
'user_id' => 'required',
'store_id' => 'required'
];
public function user()
{
return $this->belongsTo(User::class,'user_id','id');
}
public function store()
{
return $this->belongsTo(Store::class,'store_id','id');
}
}
table user have field id, name, email etc
table store have field id, name, email etc
I want get user name and store name from table user and table store. Then, I want store it on variable $data
How can I do it?
UPDATE
My model user is like this :
<?php
namespace App\Models;
use Eloquent as Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class User extends Model
{
use SoftDeletes;
public $table = 'users';
protected $dates = ['deleted_at'];
public $fillable = [
'name',
'email',
'password',
'full_name',
'birth_date',,
'mobile_number',
];
protected $casts = [
'name' => 'string',
'email' => 'string',
'password' => 'string',
'full_name' => 'string',
'birth_date' => 'date',,
'mobile_number' => 'string',
];
public static $rules = [
'name' => 'required',
'email' => 'required'
];
}
My model store is like this :
<?php
namespace App\Models;
use Eloquent as Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Store extends Model
{
use SoftDeletes;
public $table = 'stores';
protected $dates = ['deleted_at'];
public $fillable = [
'user_id',
'domain',
'name',
'email'
];
protected $casts = [
'user_id' => 'integer',
'domain' => 'string',
'name' => 'string',
'email' => 'string'
];
public static $rules = [
'user_id' => 'required',
'domain' => 'required',
'name' => 'required'
];
public function user()
{
return $this->belongsTo(User::class,'user_id','id');
}
}
First you need to make model for User Table and Store table then define respective table names in both model after that......
public function create(Request $request)
{
$data = $request->all();
$email = 'chelsea#gmail.com';
$user = User::where('email', $email)->first();
$store = Store::where('email', $user->email)->first();
$order = Order::where('user_id', $user->id)->where('store_id', $store->id)->first();
$result = array();
$result['orderTable'] = $order;
return $result;
}
Use with in your order controller query, just pass the array of relationships that you have declared in your order model query will fetch the related tables data based on model relations, like below
In order controller
$data = Order::where('col', 'val')->with(['user','store'])->first();
In order model
public function user()
{
return $this->belongsTo(User::class,'user_id','id');
}
public function store()
{
return $this->belongsTo(Store::class,'store_id','id');
}