No query results for model App/Models/Country delete_all - laravel

I am working on project useing laravel and vuejs the problem is that I am trying to select multi rows and delete them the error is
No query results for model [App\Models\Country] delete_all
my route link
Route::delete('/delete_all','CountriesController#deleteAll');
delete function in the country controller
public function deleteAll(Request $request){
$ids = $request->ids;
DB::table("countries")->whereIn('id',explode(",",$ids))->delete();
return response()->json('Selected Countries Deleted Successfully',200);
}
the delete method in the component
delAll(){
axios.delete('/dashboard/countries/delete_all', {
ids: this.selected
}).then(response => {
toastr.success(response.data);
})
}
where can I find the Error

just trying
DB::table("countries")->whereIn('id',explode(",",$ids))->get()->delete();
or simple
Countries::destroy(explode(",",$ids));

Related

How to update multiple Rows In Laravel Controller

basically I want to update this table in one go or bulk update.
I wanted to update the "image_id" field on this table.
This is my code in the Controller
public function storebulk(Request $request,$id)
{
$ids= ['8','9','10']; //sent from the front-end
$barcode = Barcode::where('id', $ids)->update(['image_id'=>$id]);
return 'Done';
}
but for some reason it doesn't work. if anyone can point out what I missed here it will be great.
thanks
You should use whereIn:
public function storebulk(Request $request, $id)
{
$ids= ['8','9','10']; //sent from the front-end
$barcode = Barcode::whereIn('id', $ids)->update(['image_id'=>$id]);
return 'Done';
}
In Laravel, If you want to update multiple rows or get multiple rows of same type always use whereIn.
The Docs Define whereIn as -
The whereIn method verifies that a given column's value is contained within the given array
public function storebulk(Request $request,$id)
{
$ids= ['8','9','10']; //sent from the front-end
$barcode = Barcode::whereIn('id', $ids)->update(['image_id'=>$id]);
return 'Done';
}
Link to docs

How to get latest eloquent relationship by column name in Laravel

I am building a small application on Laravel 5.6 where I am having two models Project and Status. In this I am having a relation as such:
In Project Model I am having:
public function statusUpdate()
{
return $this->hasMany('App\Status','project_id','id');
}
and to retrieve latest status I have:
public function latestStatus()
{
return $this->hasOne('App\Status','project_id','id')->latest();
}
In status I have columns: date, status, sub_status, comments.
I want to retrieve Status where I am having latest status by date mentioned in the column
I tried doing this in my model:
public function latestStatus()
{
return $this->hasOne('App\Status','project_id','id')->latest('date');
}
But this thing is not working out, help me out in this. Thanks
edit
I am using this relation in eager loading something like this:
Project::when( $request->name , function( $q) use( $request ) {
$q->where('name', 'like', '%' . $request->name .'%');
})->with('latestStatus')
->orderBy($request->sort_by_col, $request->order_by)
->paginate(30);
You can use orderBy in the relationship.
public function latestStatus()
{
return $this->hasOne('App\Status','project_id','id')->orderBy('date', 'desc');
}
Try it out.
You got your models wrong. This is what should be in the Project model
public function statuses() //plural because a project has many statuses
{
return $this->hasMany('App\Status','id','project_id');
}
If you want the latest status, call this in your controller:
Project::where('name', 'like', "%{$request->name}%")->with('statuses', function($q) {
return $q->orderBy('date', $request->order_by);
})->paginate(30);
If you want the latest project where the status has changed, first the Status model:
public function project()
{
return $this->hasOne('App\Project','project_id','id');
}
And in your controller:
$project = Status::latest()->first()->project;
Add first to the end of the query.
public function latestStatus()
{
return $this->hasOne('App\Status','project_id','id')->latest()->first();
}
This is how it works
The statusUpdate method builds the query and does the setup for has many relationship
The latest method adds the order by clause
The first methods adds the limit 1 clause, then executes the query and returns the first result

Laravel HasMany create child record

I'm having a problem when I'm trying to create a child model associated to his parent.
I have 2 models:
Instituion (has many addresses)
Address (has 1 Institution)
When I click a Institution and I go to show.blade.php where I have a form to create an Address for that Institution I can't get from the request the field "instituion_id" which relates child with parent.
This is shown in the request:
Request Data
From the form I'm calling the following route: action="/institution/{{ $institution->id }}/addresses"
This is the code in AddressController:
public function store(Request $request)
{
// dd($request->all());
Address::create($request->all());
return back();
}
When I test it, the DB is asking for the isntitution_id column:
SQLSTATE[HY000]: General error: 1364 Field 'institution_id' doesn't
have a default value (SQL: insert into addresses (address_name,
address_number, address_full_name, address_city,
address_state, address_postal_code, address_country,
updated_at, created_at) values (a, a, a, a, a, a, a, 2017-12-14
14:06:47, 2017-12-14 14:06:47))
So, how to I pass from the form the field "institution_id" and how do I get it in the controller and assocuiated to the child record?
I read many posts but in all of them they are just create a child record with one field but I want to process the complere request with all Addres fields.
Regards
You can access the id from the parameters of the store method like this :
In the routes file :
Route::post('/institution/{institution_id}/addresses', 'YourController#store')
In the controller :
public function store($institution_id, Request $request)
{
$request->request->add(['institution_id' => $institution_id]);
// dd($request->all());
Address::create($request->all());
return back();
}
Ps : Don't forget to add institution_id to the fillable fields in the Address Model.
If all relationships are set, the documentation has what you're looking for
https://laravel.com/docs/5.5/eloquent-relationships#the-create-method
Example:
// Routes (If laravel version > 5.2 web.php I guess
Route::post('/institution/{institution_id}/addresses', 'Controller#store')
// app/Http/Controllers/Controller.php
public function store(Request $request)
{
$institution = Institution::find($request->institution_id);
$address = $institution->addresses()->create($request->all());
return back();
}
// app/Institution.php
class Institution extends Model
{
public function addresses()
{
return $this->hasMany('App\Address', 'institution_id', 'id');
}
}
Here's how I did it. I had 2 models/controllers: website and visitor. Visitor is dependent on website.
Routes:
Route::resource('website', 'WebsiteController');
Route::resource('website/{website}/visitor', 'VisitorController');
Don't forget to set all the relationships. I'll only show you the one that I'll use to save the data, in the Website model:
public function visitors()
{
return $this->hasMany('App\Visitor');
}
Then, in the store inside the VisitorController:
public function store(Request $request, Website $website)
{
return response()->json(
$website->visitors()->create([
... fields without website_id (the relationship field) ...
]),
201
);
}
$p=Parent::find($anId);
$ch=Child::create(['somekey0'=>value0,'somekey1'=>value1,
...,'somekeyN'=>valueN]);
$ch->my_parent()->associate($p);
$ch->save();

How to add data to additional column in pivot table in laravel

I'm trying to build an app in Laravel 5.3, I want to add additional column data in the pivot table. Following is my code:
My Users model:
public function relations()
{
return $this->belongsToMany('App\Plan')->withPivot('child');
}
My Plan model:
public function relations()
{
return $this->belongsToMany('App\User')->withPivot('child');
}
In my controller I'm fetching the user data from Auth::user(); and for plans and child element I'm getting through request. I want to store this to my pivot table. Following is the code which I tried in my controller:
$user = \Auth::user();
$plan_id = $request->plan_id;
$childid = $request->child_id;
$plan = App\Plan::find($plan_id);
$user->relations()->attach($plan, ['child' => $childid]);
Help me out in this.
You should use attach() like this:
$user->relations()->attach($plan_id, ['child' => $childid]);
Try the save method as:
$user->relations()->save($plan, ['child' => $childid]);
Docs
Both save and attach work. Just that attach will return null while save will return $user object when I try with tinker

Search with Relationship - Laravel 5.3

Im making a search functionality where users can type in a name. This is the query im doing:
public function api(Request $request)
{
$query = request()->get('query');
$results = Listing::searchAndCache($query);
return $results;
}
Which hits this:
public static function searchAndCache($query)
{
return self::where('name','like','%'.$query.'%')->where('live',true)->paginate(15);
}
I also need to search 'location' along with this query, the problem is its in a diffrent table. The models name is Location. My question is how would I attach the model Location to this query?
So ideally, I would want to do this for the query:
public static function searchAndCache($query)
{
return self::where('name','like','%'.$query.'%')->where('region','like','%'.$query.'%')->where('live',true)->paginate(15);
}
For search you can use searchable trait. so you can do this :
Listing::where('live',true)->search($query)->paginate(15);
if there is a relation between Listing And Location, you can use Laravel realations to do something like this
Listing::where('live',true)
->search($query)
->location
->search($query2)
->paginate(15);

Resources