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');
}
Related
When I load the page, it gives me an error and tells me to reload.
However, when I add data to the database it works properly.
So, basically my list function isn't working and I don't know why.
I checked for typos, it can't be something like updating, because of all my other CRUD's work fine with the same method.
Controller :
<?php
namespace App\Http\Controllers\Admin;
use App\Http\Requests\ProjectRequest;
use Backpack\CRUD\app\Http\Controllers\CrudController;
use Backpack\CRUD\app\Library\CrudPanel\CrudPanelFacade as CRUD;
/**
* Class ProjectCrudController
* #package App\Http\Controllers\Admin
* #property-read \Backpack\CRUD\app\Library\CrudPanel\CrudPanel $crud
*/
class ProjectCrudController extends CrudController
{
use \Backpack\CRUD\app\Http\Controllers\Operations\ListOperation;
use \Backpack\CRUD\app\Http\Controllers\Operations\CreateOperation;
use \Backpack\CRUD\app\Http\Controllers\Operations\UpdateOperation;
use \Backpack\CRUD\app\Http\Controllers\Operations\DeleteOperation;
use \Backpack\CRUD\app\Http\Controllers\Operations\ShowOperation;
public function setup()
{
$this->crud->setModel('App\Models\Project');
$this->crud->setRoute(config('backpack.base.route_prefix') . '/project');
$this->crud->setEntityNameStrings('project', 'projects');
}
protected function setupListOperation()
{
$this->crud->setColumns([
'name' => 'status',
'type' => 'text',
'label' => 'Status'
]);
$this->crud->setColumns([
'name' => 'topic',
'type' => 'text',
'label' => 'Topic'
]);
$this->crud->setColumns([
'name' => 'leader',
'type' => 'text',
'label' => 'Leader'
]);
$this->crud->setColumns([
'name' => 'email',
'type' => 'text',
'label' => 'Name'
]);
$this->crud->setColumns([
'name' => 'tags',
'type' => 'text',
'label' => 'Tags'
]);
}
protected function setupCreateOperation()
{
$this->crud->setValidation(ProjectRequest::class);
$this->crud->addField([
'name' => 'status',
'type' => 'text',
'label' => 'Status'
]);
$this->crud->addField([
'name' => 'topic',
'type' => 'text',
'label' => 'Topic'
]);
$this->crud->addField([
'name' => 'leader',
'type' => 'text',
'label' => 'Leader'
]);
$this->crud->addField([
'name' => 'email',
'type' => 'text',
'label' => 'Name'
]);
$this->crud->addField([
'name' => 'tags',
'type' => 'text',
'label' => 'Tags'
]);
}
protected function setupUpdateOperation()
{
$this->setupCreateOperation();
}
public function store()
{
$this->crud->hasAccessOrFail('create');
// execute the FormRequest authorization and validation, if one is required
$request = $this->crud->validateRequest();
// insert item in the db
$item = $this->crud->create($this->crud->getStrippedSaveRequest());
$this->data['entry'] = $this->crud->entry = $item;
// show a success message
\Alert::success(trans('backpack::crud.insert_success'))->flash();
// save the redirect choice for next time
$this->crud->setSaveAction();
return $this->crud->performSaveAction($item->getKey());
}
}
Model:
<?php
namespace App\Models;
use Backpack\CRUD\app\Models\Traits\CrudTrait;
use Illuminate\Database\Eloquent\Model;
class Project extends Model
{
use CrudTrait;
/*
|--------------------------------------------------------------------------
| GLOBAL VARIABLES
|--------------------------------------------------------------------------
*/
protected $table = 'projects';
// protected $primaryKey = 'id';
// public $timestamps = false;
protected $guarded = ['project_id'];
protected $fillable = ['topic', 'status', 'leader', 'email', 'tags'];
// protected $fillable = [];
// protected $hidden = [];
// protected $dates = [];
/*
|--------------------------------------------------------------------------
| FUNCTIONS
|--------------------------------------------------------------------------
*/
/*
|--------------------------------------------------------------------------
| RELATIONS
|--------------------------------------------------------------------------
*/
/*
|--------------------------------------------------------------------------
| SCOPES
|--------------------------------------------------------------------------
*/
/*
|--------------------------------------------------------------------------
| ACCESSORS
|--------------------------------------------------------------------------
*/
/*
|--------------------------------------------------------------------------
| MUTATORS
|--------------------------------------------------------------------------
*/
}
Request:
<?php
namespace App\Http\Requests;
use App\Http\Requests\Request;
use Illuminate\Foundation\Http\FormRequest;
class ProjectRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
// only allow updates if the user is logged in
return backpack_auth()->check();
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [
'topic' => 'required|min:5|max:255',
'status' => '',
'leader' => 'required|min:5|max:255',
'email' => 'required|min:5|max:255',
'tags' => 'required|min:5|max:255'
];
}
/**
* Get the validation attributes that apply to the request.
*
* #return array
*/
public function attributes()
{
return [
//
];
}
/**
* Get the validation messages that apply to the request.
*
* #return array
*/
public function messages()
{
return [
//
];
}
}
protected $primaryKey = 'project_id';
Database had project_id instead of just id, so this should work.
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
is there a shorter way to insert data in Laravel over the Eloquent ORM?
at the moment i'm doing it this way:
$newCustomerGsale = new CustomersGsale();
$newCustomerGsale->email = $gsalesCustomer->getEmail();
$newCustomerGsale->customerno = $gsalesCustomer->getCustomerNumber();
$newCustomerGsale->created = $gsalesCustomer->getCreated();
$newCustomerGsale->company = $gsalesCustomer->getCompany();
$newCustomerGsale->firstname = $gsalesCustomer->getFirstname();
$newCustomerGsale->lastname = $gsalesCustomer->getLastname();
$newCustomerGsale->save();
like you see all the columns are named like the attributes.
I know u can use the $request object with all() function and fetch().
but I get the data from a other object (soap server).
is there a way to convert this? maybe over the model?
Your controller
Assume CustomersGsale is your model
public function store(CustomersGsaleFormRequest $request)
{
CustomersGsale::create($request->all());
}
CustomersGsaleFormRequest.php Laravel Form Requests Validation
public function rules()
{
return [
'email' => 'required|email',
'customerno' => 'required',
'created' => 'required',
'company' => 'required',
'firstname' => 'required'
];
}
CustomersGsale.php Model
your attributes and columns should be the same.
If you are using the create method for store the data then you will need to specify either a fillable or guarded attribute on the model
class CustomersGsale extends Model
{
protected $fillable = [
'email', 'customerno', 'created', 'company', 'firstname', 'lastname'
];
}
//MyControllerClass
public function store(myCustomValidator $request){
CustomersGsale::insert($request->all());
}
//myCustomValidator class
public function rules(): array
{
return [
'email' => 'required|numeric',
'customerno' => 'required',
'created' => 'required',
'company' => 'required',
'firstname' => 'required'
'lastname' => 'nullable'
];
}
Try the above method, hope this will work for you.
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 currently working on a project with Laravel 5.7. As I implemented the MustVerifyEmail class in my User model, the application does not send email as expected. The case is:
1) I have followed the Laravel documentation here: https://laravel.com/docs/5.7/verification
2) I used https://mailtrap.io to test the function, but I didn't receive any verification email from the application.
3) I tried to use Auth::routes() instead of Auth::routes(['verify' => true]) and was expecting errors, but no error occurred, the application just redirected me to the home page after the user registration.
Here's my User model:
<?php
namespace App;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
class User extends Authenticatable implements MustVerifyEmail
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'first_name', 'last_name', 'email', 'password', 'phone_number', 'username', 'role'
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token'
];
public function freelancer()
{
return $this->hasOne('App\Freelancer', 'freelancer_id', 'id');
}
public function employer()
{
return $this->hasOne('App\Employer', 'employer_id', 'id');
}
}
This is my create() function in RegisterController.php:
protected function create(array $data)
{
if ($data['role'] == 'freelancer') {
$user = User::create([
'first_name' => $data['first_name'],
'last_name' => $data['last_name'],
'email' => $data['email'],
'phone_number' => $data['phone_number'],
'username' => $data['username'],
'password' => Hash::make($data['password']),
'role' => $data['role'],
])->freelancer()->create([
'overview_description' => '',
]);
} else {
$user = User::create([
'first_name' => $data['first_name'],
'last_name' => $data['last_name'],
'email' => $data['email'],
'phone_number' => $data['phone_number'],
'username' => $data['username'],
'password' => Hash::make($data['password']),
'role' => $data['role'],
])->employer()->create([
'overview_description' => '',
'number_of_employees' => 0,
]);
}
return $user;
}
My Freelancer and Employer model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Freelancer extends Model
{
protected $table = 'freelancer';
public $timestamps = false;
protected $fillable = [
'overview_description'
];
}
--
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Employer extends Model
{
protected $table = 'employer';
public $timestamps = false;
protected $fillable = [
'overview_description', 'number_of_employees'
];
}
I think there is something wrong in the RegisterController, but I'm not sure where it is. Is there any logic error?
You forget to use the Illuminate\Auth\MustVerifyEmail trait in your User model, this trait define the sendEmailVerificationNotification method which is responsible for sending the verification email.
use Illuminate\Contracts\Auth\MustVerifyEmail as MustVerifyEmailContract; // this is an interface
use Illuminate\Auth\MustVerifyEmail; // this the trait
class User extends Authenticatable implements MustVerifyEmail
{
use MustVerifyEmail, Notifiable;
// all the other code goes here
}
The issue solved after I updated the create function in RegisterController.php as follows:
protected function create(array $data)
{
$user = User::create([
'first_name' => $data['first_name'],
'last_name' => $data['last_name'],
'email' => $data['email'],
'phone_number' => $data['phone_number'],
'username' => $data['username'],
'password' => Hash::make($data['password']),
'role' => $data['role'],
]);
return $user;
}
As for the creation process of the Freelancer and Employer instances, I placed it after the email verification.