I have the following model.
class Training extends \Eloquent {
// Add your validation rules here
public static $rules = [
'name' => 'required',
'city' => 'required',
'province' => 'required',
'budget_year' => 'required|integer',
's_date' => 'required|date',
'e_date' => 'required|date'
];
// Don't forget to fill this array
protected $fillable = [
'name',
'city',
'province',
'budget_year',
's_date',
'e_date'
];
public function material(){
return $this->hasMany('Material');
}
public function budget(){
return $this->belongsToMany('Budget')->withPivot('amount');
}
public function budgetById($training_id){
$this->belongsToMany('Budget')->where('training_id', '=', $training_id)->get();
}
}
when I debug the budgetById method using DB::getQueryLog, the query is as follow
select budgets.*,
budget_training.training_id as pivot_training_id,
budget_training.budget_id as pivot_budget_id
from budgets inner join budget_training on budgets.id = budget_training.budget_id
where budget_training.training_id is null and training_id='6'
which return 0 rows, but when I try to modify the query and run it in pgadmin, the following script works well.
select budgets.*,
budget_training.training_id as pivot_training_id,
budget_training.budget_id as pivot_budget_id
from budgets inner join budget_training on budgets.id = budget_training.budget_id
where budget_training.training_id='6'
notice I remove training_id is null and from Laravel generated query. What is wrong with my budgetById method?
You have called get() and didn't use return here:
public function budgetById($training_id){
// = in where is optional in this case
$this->belongsToMany('Budget')->where('training_id', '=', $training_id);
}
You should use like this:
public function budgetById($training_id){
// = in where is optional in this case
return $this->belongsToMany('Budget')->where('training_id', '=', $training_id);
}
In Lavarel 7.X, you can use the wherePivot method to filter columns on the pivot table, like this:
return $this->belongsToMany('Budget')->wherePivot('training_id', '=', $training_id);
or
return $this->belongsToMany('Budget')->wherePivotNotNull('training_id');
Related
I am using brackets ui in my laravel admin panel
I am trying to sort my list by desc order with search as well but it is not working
My Controller and I have tried that
public function index(Request $request)
{
// create and AdminListing instance for a specific model and
$data = AdminListing::create(Order::class)->attachOrdering('id', 'desc')->processRequestAndGet(
// pass the request with params
$request,
// set columns to query
['id', 'name', 'created_at', 'phone', 'total_amount', 'status','discount','user_order_note'],
// set columns to searchIn
['id', 'name', 'created_at', 'phone', 'total_amount', 'status','discount','user_order_note']
);
if ($request->ajax()) {
return ['data' => $data];
}
return view('admin.orders.index', ['data' => $data]);
}
Have done this according to the documentation.
It does not give an error, but does not work as well.
Please add get() method
please modify the query like below.
$data = AdminListing::create(Order::class)->attachOrdering('id', 'desc')->processRequestAndGet(
// pass the request with params
$request,
// set columns to query
['id', 'name', 'created_at', 'phone', 'total_amount', 'status','discount','user_order_note'],
// set columns to searchIn
['id', 'name', 'created_at', 'phone', 'total_amount', 'status','discount','user_order_note']
)->get();
I'm staring with Laravel and I'm having troubles trying to make a simple insert, but It seems that all of my fillable fields are not being included. This is the error:
SQLSTATE[HY000]: General error: 1364 Field 'name' doesn't have a default value
(SQL: insert into `addresses` (`updated_at`, `created_at`)
values (2017-12-25 09:31:49, 2017-12-25 09:31:49))
As you can see, only created_at and updated_at are about to be inserted, I thought that maybe I forgot my fillable vars, but this is my Model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Addresses extends Model
{
protected $fillable = [
'name',
'city',
'suburb',
'street',
'o_number',
'i_number',
'postal_code',
'phone_s',
'email_s',
'google_map',
'customer_id'
];
}
And the Controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Addresses;
use App\Customers;
class AddressesController extends Controller
{
public function __construct()
{
$this->middleware('auth');
}
public function store(Request $request){
$create = Addresses::create([
'name' => request('name'),
'city' => request('city'),
'suburb' => request('suburb'),
'street' => request('street'),
'o_number' => request('o_number'),
'i_number' => request('i_number'),
'postal_code' => request('postal_code'),
'phone_s' => request('phone_s'),
'email_s' => request('email_s'),
'google_map' => request('google_map'),
'customer_id' => Customers::where('code',$request->session()->get('customer_code'))->first()->id
]);
$success = $create ? $request->session()->flash('success', '¡Registro exitoso!') : $request->session()->flash('success', 'Ooops! Algo salio mal :(');
return redirect('addresses/'.$request->session()->get('customer_code'));
}
}
Echo the request() values works! So I'm missing right now, I have some other Models and Controller working good in the same way. Please Help!
This error show because you the NAME field is required on your database. Try to edit your migration script and put default value on this field or make it nullable.
eg.
$table->string('name')->nullable();
OR
$table->string('name')->default('');
Then run a migration refresh.
Goto "phpmyadmin" >> "Variables" then find "sql_mode" edit and remove "STRICT_ALL_TABLES or STRICT_TRANS_TABLES"
It is working for me.
Hope it will help for All.
This is late answer for this question, but it might help for others.
This error can be occurred due to error in $fillable data in modal.
You can try using
protected $guarded = []
instead of
protected $fillable = [
'name',
'city',
'suburb',
'street',
'o_number',
'i_number',
'postal_code',
'phone_s',
'email_s',
'google_map',
'customer_id'
];
But You have to validate the data that you passed within the controller.
The error occurs due to the strict mode of MYSQL5.7. Please change your config/database.php in the connections.mysql section by putting 'strict' => false.
I solved it using save()
$addresses = new Addresses;
$customer_id = Customers::where('code',$request->session()->get('customer_code'))->first()->id;
$addresses->name = $request->name;
$addresses->city = $request->city;
$addresses->suburb = $request->suburb;
$addresses->street = $request->street;
$addresses->o_number = $request->onumber;
$addresses->i_number = $request->inumber;
$addresses->postal_code = $request->postal_code;
$addresses->phone_s = $request->phone_s;
$addresses->email_s = $request->email_s;
$addresses->google_map = $request->map;
$addresses->customer_id = $customer_id;
$success = $addresses->save() ? $request->session()->flash('success', '¡Registro exitoso!') : $request->session()->flash('success', 'Ooops! Algo salio mal :(');
return redirect('addresses/'.$request->session()->get('customer_code'));
It's working properly
When you use the nullable() method on a field, that field will default to NULL.
For example, add this to your migration file:
$table->string('name')->nullable();
Update:
You can add:
$table->string('name')->nullable()->default(null);
You can check Null option in table structure, like this -
Make sure request() has key 'name'.Replace request('name') to random string and try again.
In my case I forgot to change - this is my code on my Controller
public function store(Request $request)
{
$message = new Message();
$message->name = $request->input('name');
$message->name = $request->input('message');
$message->save();
}
I made a duplication of the 'name' that's why it happened and made this
public function store(Request $request)
{
$message = new Message();
$message->name = $request->input('name');
$message->message = $request->input('message');
$message->save();
}
This way the solution to the problem.
I was having this problem because I didn't add a correct column under $fillable list.
class Chirp extends Model
{
use HasFactory;
protected $fillable = [
'message', // This line should be added.
];
}
I am working with laravel 5.5 to update entries. The problem is after changing the primary key 'id', which is elequoent default pk to 'project_id'. adding an item works fine but updating an item is not working properly. Here is the error I am getting.
Method save does not exist.
Here is my Model.
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Project extends Model
{
protected $primaryKey = 'project_id';
public function user()
{
return $this->belongsTo(User::class);
}
public function tasks()
{
return $this->hasMany(Task::class);
}
}
Here is my controller function.
public function editProject($id){
$project = Project::where('project_id', $id)->firstOrFail();
$data = ["project_info" => $project];
return view('projects.edit')->with($data);
}
public function updateProject(Request $request){
$data = $request->all();
$validator = Validator::make($data, [
'project_title' => 'required',
'project_description' => 'required',
'project_start_date' => 'required',
'project_end_date' => 'required',
'project_status' => 'required',
]);
$response = [];
if ($validator->fails()){
$response["errors"] = [$validator->messages()->first()];
$response["success"] = false;
return json_encode($response);
}
else{
$project = Project::where("project_id", $request->input('project_id'))->get();
$project->project_title = $request->project_title;
$project->user_id = Session::get('user_id');
$project->project_description = $request->project_description;
$project->project_start_date = $request->project_start_date;
$project->project_end_date = $request->project_end_date;
$project->project_status = $request->project_status;
$project->save();
return redirect('/listProjects');
}
}
Using get() returns a collection. Despite the fact you are passing in a 'unique' ID, the project_id, it will still return a collection - the collection will simply have one element in it.
Subsequently, your code will not work as you have experienced, or at least not without a few changes to make $project reference the first element in the collection.
It's a quick fix though, just change this:
$project = Project::where("project_id", $request->input('project_id'))->get();
to this:
$project = Project::where("project_id", $request->input('project_id'))->first();
By using first(), eloquent will return the first element that matches the query and actually return the element (as opposed to a collection with one element) and so you can directly edit and save it.
Here is the solution I found.
$project_id = $request->input('project_id');
$project = Project::find($project_id);
$project->save();
You can find it by id using
Project::find($id);
Or get the first element like James said:
$project = Project::where("project_id", $request->input('project_id'))->first();
I have a issue, Please take a look below.
I have a edit user profile section where we update user account, i want to check if no image exists in table & user too not provided image then we have to validate the image & show an error. if there is already a image exists in table then no image validation suppose to check. Everything works good except image validation.
i am using from request for validation. below is my validation rules in request file.
public function rules()
{
return [
'user_type' =>'required',
'first_name' =>'required|max:100',
'last_name' =>'required|max:100',
'email' =>'required|email|max:100',
'image' =>'required|image',
'zip_code' =>'required|numeric|min:5',
];
}
I am using Laravel 5.2, Thanks in advance.
Finally i figure out the solution using help of #Amir. below is the complete solutions of this issue.
//add this in user model
public function notHavingImageInDb(){
return (empty($this->image))?true:false;
//return true;
}
//import the User model & Auth class in request class.
use App\User;
use Auth;
//add this in from request
public function rules()
{
$user = User::find(Auth::id());
$rules = [
'user_type' =>'required',
'first_name' =>'required|max:100',
'last_name' =>'required|max:100',
'email' =>'required|email|max:100',
'image' =>'image',
'zip_code' =>'required|numeric|min:5',
];
if ($user->notHavingImageInDb()){
$rules['image'] = 'required|image';
}
return $rules;
}
Now all done.
In the above code we check if the column has some value or not in validation, if yes then model function return true, this make the if condition active in request class, else, if condition remain inactive. works like charm.
Thanks
take a look at Conditionally Adding Rules:
so something like:
$v->sometimes(['image'], 'required|image', function($input) use ($user) {
return $user->notHavingImageInDb();
});
you can also use plain logic like:
public function rules()
{
$roles = [
'user_type' =>'required',
'first_name' =>'required|max:100',
'last_name' =>'required|max:100',
'email' =>'required|email|max:100',
'image' =>'image',
'zip_code' =>'required|numeric|min:5',
];
if ($user->notHavingImageInDb())
$rules['image'] = 'required|image';
return $rules
}
You can create another request class and name it UserUpdateRequest with artisan
like
php artisan make:request UserUpdateRequest
in this request class you just have to remove 'required' it will be like that
'image' => 'image'
and set UserUpdateResuest as parameter to update method like
public function update(UserUpdateRequest $userUpdateRequest, $id){
//
}
Using Yii 2.0 i'm trying to grab some $_POST values in my controller from my view but cannot do this. I will show you my code and talk you through it below.
Models/CaseSearch.php
<?php
namespace app\models;
use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use app\models\Cases;
/**
* CaseSearch represents the model behind the search form about `app\models\Cases`.
*/
class CaseSearch extends Cases
{
public $category;
public $subcategory;
public $childcategory;
public $newcategory;
/**
* #inheritdoc
*/
public function rules()
{
return [
[['case_id', 'year'], 'integer'],
[['name', 'judgement_date', 'neutral_citation', 'all_ER', 'building_law_R', 'const_law_R', 'const_law_J', 'CILL', 'adj_LR'], 'safe'],
];
}
/**
* #inheritdoc
*/
public function scenarios()
{
// bypass scenarios() implementation in the parent class
return Model::scenarios();
}
/**
* Creates data provider instance with search query applied
*
* #param array $params
*
* #return ActiveDataProvider
*/
public function search($params)
{
$query = Cases::find();
$dataProvider = new ActiveDataProvider([
'query' => $query,
]);
$this->load($params);
if (!$this->validate()) {
// uncomment the following line if you do not want to any records when validation fails
// $query->where('0=1');
return $dataProvider;
}
$query->andFilterWhere([
'case_id' => $this->case_id,
'judgement_date' => $this->judgement_date,
'year' => $this->year,
]);
$query->andFilterWhere(['like', 'name', $this->name])
->andFilterWhere(['like', 'neutral_citation', $this->neutral_citation])
->andFilterWhere(['like', 'all_ER', $this->all_ER])
->andFilterWhere(['like', 'building_law_R', $this->building_law_R])
->andFilterWhere(['like', 'const_law_R', $this->const_law_R])
->andFilterWhere(['like', 'const_law_J', $this->const_law_J])
->andFilterWhere(['like', 'CILL', $this->CILL])
->andFilterWhere(['like', 'adj_LR', $this->adj_LR]);
return $dataProvider;
}
public function searchByCategory($category){
$query = Cases::find();
$dataProvider = new ActiveDataProvider([
'query' => $query,
]);
if (!$this->validate()) {
// uncomment the following line if you do not want to any records when validation fails
// $query->where('0=1');
return $dataProvider;
}
$query->andFilterWhere([
'category_id' => $category
]);
return $dataProvider;
}
}
Okay so now is my view:
<?php
$form = ActiveForm::begin();
echo $form->field($searchModel, 'category')
->dropDownList(
ArrayHelper::map($allCategory, 'id', 'name'),
[
'onchange'=>'getSubcategory()',
]
);
//To stop errors, if first category not chosen make subcategory and empty drop down.
$subcategory = array(
"empty" => ""
);
echo $form->field($searchModel, 'subcategory')
->dropDownList(
ArrayHelper::map($subcategory, 'id', 'name'),
[
'onchange'=>'getChildcategory()',
]
);
//To stop errors, if second category not chosen make childcategory and empty drop down.
$childcategory = array(
"empty" => ""
);
echo $form->field($searchModel, 'childcategory')
->dropDownList(
ArrayHelper::map($childcategory, 'id', 'name'),
[
//'onchange'=>'getChildCategory()',
'onchange'=>'submitNow()',
]
);
echo '<div class="form-group">';
echo Html::submitButton('Submit', ['class' => 'btn btn-primary']);
echo '</div>';
ActiveForm::end();
Ok, so when i click the submit button i want to capture the value in my controller so that i can use this to alter the results given in the gridview.
When i inspect the element on the drop down lists the names are weird so i am not sure if this is making a different. for example the name for subcategory is actually: CaseSearch[subcategory]
Now for my controller:
public function actionIndex()
{
//
// This is for the first render of index
//
$model = new Cases;
$searchModel = new CaseSearch();
$allCategory = Category::find()->all();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
//
// This is for when i click the submit button on the view. I want it to submit and then grab the subcategory in variable $subtest. I make $subtest = 1 so that when i first render the page it doesn't throw an error and when submitted it should change to the post value
//
$subtest = 1;
if($searchModel->load(Yii::$app->request->post())){
$subtest = $_POST['subcategory'];
}
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
'allCategory' => $allCategory,
'model' => $model,
'subtest' => $subtest
]);
}
However when i try to print_r() the variable $subtest in my view i get the error:
Undefined index: CaseSearch[subcategory]
and its for the line:
$subtest = $_POST['CaseSearch[subcategory]'];
In my controller.
Can anyone please advise as i cannot figure out why?
I think your application design is improvable. Read the Yii guide.
However I think the solution to the question is:
$subtest = $_POST['CaseSearch']['subcategory];
Don't use $_GETand $_POST directly in your controller there are some abstraction layer which filter that input.
$get = $request->get();
// equivalent to: $get = $_GET;
$post = $request->post();
// equivalent to: $post = $_POST;
You should use that classes and methods to get your params.
http://www.yiiframework.com/doc-2.0/guide-runtime-requests.html