I want to add to the wishlist; after I click add, I get an error. I believe that the way I want to access the product is wrong.
public function addToFavorie($id)
{
$user = Auth::user();
$product = produit::find($id);
if (!$product || !$user) {
abort(404);
}
// I believe this is the part responsible for the error
$favorie = $user->favorie;
$favprds = $favorie->produits;
//
for ($i = 0; $i < count($favprds); $i++) {
if ($favprds[$i]->id == $id)
return redirect()->back()
->with('error', 'produit deja dans votre favorie');
}
$favorie->produits()->attach($product->id);
return redirect()->back()->with('info', 'produit ajoute a votre favorie');
}
Model
public function user()
{
return $this->belongsTo("App\Models\User");
}
public function produits()
{
return $this->belongsToMany('App\Models\Produit', 'produits_favories');
}
I tried this in the controller, and it returned 404.
$user = Auth::user()->favorie;
$product = produit::find($id);
if (!$product || !$user) {
abort(404);
}
$favprds = $favorie->produits;
Instead of Using "belongsToMany" in
public function produits() { return $this->belongsToMany('App\Models\Produit', 'produits_favories'); }
use "hasMany" like this
public function produits() { return $this->hasMany('App\Models\Produit', 'produits_favories'); }
It should work
public function addToFavorie($id)
{
$product = produit::findOrFail($id);
$favorie = Favorie::firstOrCreate([
'user_id' => auth()->id()
], [
/* attributes for a `Favorie` instance */
]);
$favorie->produits()->syncWithoutDetaching($product->id);
return redirect()->back()->with('info', 'produit ajoute a votre favorie');
}
Related
I have create a filter method in my project where I filtered the data using this method but now I want to refactor the code using queryScope method in laravel can anyone suggest me how to refactor this code.
This code is working fine.
This is my controller index method
public function index(Request $request)
{
$status = Ticket_status::pluck('name');
$tickets = Ticket::with('users','ticketStatus','ticketType','tbl_contacts')
->where('user_id','=',Auth::user()->id)
->latest();
if (request('Open')) {
$tickets = $tickets->where('status_id',1)->get();
} elseif (request('Pending')) {
$tickets = $tickets->where('status_id',2)->get();
} elseif (request('Close')) {
$tickets = $tickets->where('status_id',3)->get();
} else {
$tickets = $tickets->get();
}
return view('ticketing.user.index',compact('tickets','status'));
}
and this is my blade file.. In this all code is running good but I want to some refactor
<div class="col-md-8">
<a
href="{{route('tickets.index')}}"
class="btn btn-sm btn-outline-secondary mr-1">
All
</a>
#foreach ($status as $status_name)
<a
href="/tickets?{{Str::lower($status_name)}}={{ Str::lower($status_name) }}"
class="btn btn-sm btn-outline-secondary mr-1">
{{$status_name}}
</a>
#endforeach
</div>
And this is my model.
<?php
namespace App;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Ticket extends Model
{
use SoftDeletes;
//Table Name
protected $table = 'tickets';
//Primary key
public $primaryKey = 'id';
protected $fillable = [
'ticket_number',
'name',
'description',
'contact_id',
'product_id',
'status_id',
'type_id',
'priority',
'user_id',
'ticket_image',
'start_date',
];
protected $casts = [
'start_date' => 'datetime',
];
protected $dates = [
'start_date',
'deleted_at',
];
protected $filepath = '/storage/';
public function getRouteKeyName()
{
return 'ticket_number';
}
public function setStartDateAttribute($date)
{
$this->attributes['start_date'] = Carbon::parse($date)->format('Y-m-d H:i:s');
}
public function getTicketImageAttribute($value)
{
return asset($value ? $this->filepath.$value: 'uploads/default/products.jpg');
}
public function ticketType() {
return $this->belongsTo( 'App\Ticket_type', 'type_id' );
}
public function ticketStatus() {
return $this->belongsTo( 'App\Ticket_status', 'status_id' );
}
public function tbl_contacts() {
return $this->belongsTo('App\Tbl_contacts', 'contact_id');
}
public function tbl_products() {
return $this->belongsTo('App\Tbl_products', 'product_id');
}
public function users() {
return $this->belongsTo('App\User', 'user_id');
}
public function getPriorityAttribute($value) {
if ($value == 1) {
// return "<span class='dot dot-sm dot-success'></span> Low";
return $value;
} elseif($value == 2) {
// return "<small class='dot dot-sm dot-warning'></small> Medium";
return $value;
} else {
// return "<span class='dot dot-sm dot-danger'></span> High";
return $value;
}
}
/**
* Get all of the Ticket's comments.
*/
public function comments()
{
return $this->morphMany('App\Comment', 'commentable');
}
// public function scopeFilter($query, $filters) {
// if ($stauts = $filters['open']) {
// $query->where('status_id','=',$stauts);
// } elseif ($stauts = $filters['pending']) {
// $query->where('status_id','=',$stauts);
// } elseif ($stauts = $filters['close']) {
// $query->where('status_id','=',$stauts);
// }
// }
}
You can define local scopes on the model to refactor the query. Here are few:
class Ticket extends Model
{
use SoftDeletes;
public function scopeByAuthUser($query)
{
return $query->where('user_id','=', \Auth::user()->id);
}
public function scopeOpen($query)
{
return $query->where('status_id', 1);
}
public function scopePending($query)
{
return $query->where('status_id', 2);
}
public function scopeClose($query)
{
return $query->where('status_id', 2);
}
}
Here's how you can refactor your condition:
// for the first query
$tickets = Ticket::with('users','ticketStatus','ticketType','tbl_contacts')
->byAuthUser()
->latest();
if(request('Open') || request('Pending') || request('Close')) {
$scope = strtolower(request('Open') ?? request('Pending') ?? request('Close'));
$tickets = $tickets->{$scope}()->get();
} else {
$tickets = $tickets->get();
}
I have this formrequest that contains rules and a withValidator as a second layer of validation.
Note: I am aware that having it unique on the rules would supress the need for this example, but I'll need to do further validations here.
public function rules(Request $request) {
return [
"name" => "required|max:191",
"begin_date" => "required|after_or_equal:today|date_format:d-m-Y",
"end_date" => "required|after:begin_date|date_format:d-m-Y",
];
}
public function withValidator($factory) {
$result = User::where('name', $this->name)->get();
if (!$result->isEmpty()) {
$factory->errors()->add('User', 'Something wrong with this guy');
}
return $factory;
}
I am positive that it enters the if as I've placed a dd previously it to check if it's going inside. However, it proceeds to this method on the Controller and I don't want it to.
public function justATest(UserRequest $request) {
dd("HI");
}
I'm an idiot and didn't read the full doc.
It needs to specify with an after function,like this:
public function withValidator($factory) {
$result = User::where('name', $this->name)->get();
$factory->after(function ($factory) use ($result) {
if (!$result->isEmpty()) {
$factory->errors()->add('User', 'Something wrong with this guy');
}
});
return $factory;
}
I was facing this problem too.
I changed my withValidator to this:
public function withValidator($validator)
{
if (!$validator->fails()) {
$validator->after(function ($validator) {
if (Cache::has($this->mobile)) {
if (Cache::get($this->mobile) != $this->code) {
$validator->errors()->add('code', 'code is incorrect!');
} else {
$this->user = User::where('mobile', $this->mobile)->first();
}
} else {
$validator->errors()->add('code', 'code not found!');
}
});
}
I have two relashionships in laravel v4.2. When I merge these two relashion into third function and then I call third function then I receive Uncought exception. Below is my code
public function following_friend() {
return $this->hasOne('Friend', 'following_id', 'id');
}
public function follower_friend() {
return $this->hasOne('Friend', 'follower_id', 'id');
}
public function mutual_friends() {
return $this->following_friend->merge($this->follower_friend);
}
public static function get_users_infomation_by_ids($login_id, $users_arr = array()) {
$users = User::where(function($sql) use($login_id, $users_arr) {
$sql->whereIn('id', $users_arr);
})
->with('mutual_friends')
->get(array('id', 'username', 'full_name', 'is_live', 'message_privacy', 'picture'));
return (!empty($users) && count($users) > 0) ? $users->toArray() : array();
}
I don't know that where is the problem in merging these two relashionships.
Try to write like below :-
public static function get_users_infomation_by_ids($login_id, $users_arr = array()) {
$users = User::with('mutual_friends')
->where(function($sql) use($login_id, $users_arr) {
$sql->whereIn('id', $users_arr);
})
->get(array('id', 'username', 'full_name', 'is_live', 'message_privacy', 'picture'));
return (!empty($users) && count($users) > 0) ? $users->toArray() : array();
}
Since I have used like this for one of my Project :-
public function getShipmentDetails($shipmentId = null) {
$response = Shipment::with('pdDetails','shipmentDocuments')
->where('id', $shipmentId)
->first();
if($response) {
return $response->toArray();
}
}
It works for me.
I am having this issue where I'm only able to get the error message. I have some tables where student id is the foreign key, however even thou the id number is not any of the tables it still gives the message "You cannot delete this Student" but won't pass there if it can be deleted
public function findBystudentid($studentid)
{
$record= $this->getEntityManager()->getRepository('AcmeDemoBundle:record')->findBy(['studentid' => $studentid]);
$lecture = $this->getEntityManager()->getRepository('AcmeDemoBundle:lecture')->findBy(['studentid' => $studentid]);
$faculty = $this->getEntityManager()->getRepository('AcmeDemoBundle:faculty')->findBy(['studentid' => $studentid]);
if ($record||$lecture||$faculty){
return true;
} else {
return false;
}
}
public function deleteAction(Request $request, $studentid)
{
$form = $this->createDeleteForm($studentid);
$form->handleRequest($request);
$em = $this->getDoctrine()->getManager();
$deletable = $em->getRepository('AcmeDemoBundle:Student')->findBystudentid($studentid);
if ($deletable) {
$this->addFlash('error','ERROR! You cannot delete this Student' );
}
else
{
$em->remove($deletable);
$em->flush();
$this->addFlash('error','Student Deleted');
}
return $this->redirect($this->generateUrl('Student'));
}
First, your naming is a bit off. You need to fix it as it tends to be a bit confusing. With that in mind, I suggest you do it like this:
1. Controller method to check if student is deletable:
private function isStudentDeletable($studentid)
{
$em = $this->getEntityManager();
$record= $em->getRepository('AcmeDemoBundle:record')->findBy(['studentid' => $studentid]);
if ( $record ){
return false;
}
$lecture = $em->getRepository('AcmeDemoBundle:lecture')->findBy(['studentid' => $studentid]);
if ( $lecture ){
return false;
}
$faculty = $em->getRepository('AcmeDemoBundle:faculty')->findBy(['studentid' => $studentid]);
if ( $faculty ){
return false;
}
return true;
}
2. Controller's action to invoke the above
public function deleteAction(Request $request, $studentid)
{
$form = $this->createDeleteForm($studentid);
$form->handleRequest($request);
$deletable = $this->isStudentDeletable($studentid);
if (!$deletable) {
$this->addFlash('error','ERROR! You cannot delete this Student' );
}
else
{
$em = $this->getDoctrine()->getManager();
$student = $em->getRepository('AcmeDemoBundle:Student')->find($studentid)
$em->remove($student);
$em->flush();
$this->addFlash('error','Student Deleted');
}
return $this->redirect($this->generateUrl('Student'));
}
Hope this help and clarifies a bit.
I think you are calling findBystudentid wrong because findBystudentid is not in the Entity.
Here is the updated version
public function deleteAction(Request $request, $studentid)
{
$form = $this->createDeleteForm($studentid);
$form->handleRequest($request);
$em = $this->getDoctrine()->getManager();
$deletable = $this->findBystudentid($studentid);
if ($deletable) {
$this->addFlash('error','ERROR! You cannot delete this Student' );
} else {
$em->getRepository('AcmeDemoBundle:Student')->findBy(['studentid' => $studentid])
$em->remove($deletable);
$em->flush();
$this->addFlash('error','Student Deleted');
}
return $this->redirect($this->generateUrl('Student'));
}
Also findBystudentid should be a private function
private function findByStudentId() ...
Hi I take user data to two models If the user clicks the checkbox (company) it show him the additional data that needs to complete. I needs to work on scenario if checbox = 1 the data fields of the form must be passed. It is my action from the controller:
public function actionCreate() {
$model = new UrUserForm();
$userDate = new UserDataForm();
$model->scenario = 'create';
if (($userDate->load(Yii::$app->request->post()) && $userDate->validate() && $model->load(Yii::$app->request->post()) && $model->validate()) || $model->load(Yii::$app->request->post()) && $model->validate()) {
if ($userDate->IsCompany()) {
$userDate->scenario = 'setFirm';
} else {
$userDate->scenario = 'notFirm';
$userDate->clearData();
}
var_dump($userDate->scenario);
exit();
$userDate->saveOptionalData();
$model->RoyalUserData=$userDate->data['Id'];
$model->saveUser();
Yii::$app->session->setFlash('success', 'Użytkownik został dodany');
return $this->redirect(['index']);
} else {
return $this->render('create', [
'model' => $model,
'userDate' => $userDate
]);
}
}
An my model:
<?php
namespace backend\modules\users\models;
use common\models\UserData;
use frontend\modules\settings\models\Profile;
use yii\base\Model;
use Yii;
class UserDataForm extends Model
{
public $Address;
public $NIP;
public $CompanyName;
public $Website;
public $Phone;
public $IsCompany;
public $IsPhoneConfirmed;
public $CreatedAt;
public $UpdateAt;
public $Rel_State;
public $Rel_Currency;
public $IsDeleted;
public $data;
public function rules()
{
return [
[['Address', 'Phone', 'Rel_State', 'Rel_Currency','IsCompany'], 'safe', 'on' => 'notFirm'],
[['Address', 'Phone', 'Rel_State', 'Rel_Currency','IsCompany'], 'required', 'on' => 'setFirm'],
[['NIP','IsCompany', 'Phone', 'IsPhoneConfirmed', 'CreatedAt', 'UpdateAt', 'Rel_State', 'Rel_Currency', 'IsDeleted'], 'integer'],
[['Address', 'CompanyName', 'Website'], 'string', 'max' => 45],
[['Phone'], 'common\components\validators\PhoneValidator'],
[['NIP'], 'common\components\validators\NipValidator'],
['IsCompany', 'safe']
];
}
public function scenarios()
{
$scenarios = parent::scenarios();
$scenarios['setFirm'] = ['Address', 'Phone', 'Rel_State', 'Rel_Currency','IsCompany'];
$scenarios['notFirm'] = ['Address', 'Phone', 'Rel_State', 'Rel_Currency','IsCompany'];
return $scenarios;
}
public function saveOptionalData() {
$model = new UserData();
$model->Address=$this->Address;
$model->Phone=$this->Phone;
$model->Rel_State=$this->Rel_State;
$model->Rel_Currency= $this->Rel_Currency;
$model->NIP=$this->NIP;
$model->IsCompany = $this->IsCompany;
$model->IsPhoneConfirmed = $this->IsPhoneConfirmed;
$model->CompanyName = $this->CompanyName;
$model->Website = $this->Website;
$this->data=$model;
if ($model->validate() && $model->save()) {
return $model;
}
return false;
}
public function clearData() {
$this->Address = NULL;
$this->Phone = NULL;
$this->Rel_State = NULL;
$this->Rel_Currency = NULL;
$this->NIP = NULL;
$this->IsCompany = NULL;
$this->IsPhoneConfirmed = NULL;
$this->CompanyName = NULL;
$this->Website = NULL;
}
public function IsCompany() {
if ($this->IsCompany == 1) {
return true;
}
return false;
}
}
I read the documentation but it does not help me. In the create action I created
var_dump($userDate->scenario);
exit();
which indicates that there is everything okay because when checkobox is off vardump spits: string (7) "notFirm" and when he's on spits: string (7) "setFirm." I do not know where the fault but each time validation is safe, that should work that if checkbox is on data from rules(addres, phone) should be required. Anyone see my bad and can help me?
I hope you have found an answer, but in case you haven't here's one. You're setting the scenario after you validate the data. Scenarios must be set before you have run the validation in order to use different validation rules.
In your code you have
if ($userDate->IsCompany()) {
$userDate->scenario = 'setFirm';
} else {
$userDate->scenario = 'notFirm';
$userDate->clearData();
}
But in the first if in your code you have already validated
if (($userDate->load(Yii::$app->request->post()) && $userDate->validate() ...
In order to use a scenario I suggest the following:
$userDate->load(Yii::$app->request->post();//load data into model
if ($userDate->IsCompany()) {//check if company was set and is equal to 1
$userDate->scenario = 'setFirm';
} else {
$userDate->scenario = 'notFirm';
}
if($userDate->validate()...)//Validation code according to the scenario