I need the delete query within this controller
public function del($id)
{
$x=App\ImageMod::find();
// $x->where("id='$id'");
$x->delete();
return view('show');
}
How can I fetch the id dynamically and delete it?
you can delete for eg blog in this way:
public function destroy($id)
{
$blog = Blog::findOrFail($id);
$blog->delete();
return redirect()->back()->with('success','Blog deleted');
}
Use the Request dependency injection. Then, get the id property from your route. Then you can access the id from the request. Your code would looks like:
Controller
public function del(Request $request) {
$id = $request->id;
$x=App\ImageMod::destroy($id);
return view('show');
}
And then in routes/web.php you should have:
Route::delete('imagemod/delete/{id}', 'App\YourController#delete')->name('imagemod.delete');
Pass the $id from your page (ajax or even a direct request) by placing it within the route. If using ajax, something like:
$.ajax({ url: "{{url('ImageMod')}}/" + id, // <-- id from an input, pulling the val()
type: "DELETE",
data: {
_method: 'DELETE'
},
success: function (success) { .. }
In your web.php:
Route::delete('ImageMod/{id}', 'ImageModController#destroy');
Then, the routing binds that variable to the destroy method:
public function destroy($id)
{
ImageMod::destroy($id);
return 1; // if going back to ajax
}
You can also use:
public function destroy($id)
{
DB::table('blogs')->where('id', '=', $id)->delete();
}
Related
Is there the possibility to get whole database's table with it's associates?
My example
class Gambler extends Model
{
use HasFactory;
public function horse()
{
return $this->belongsTo(Horse::class, 'horse_id', 'id');
}
}
I am fetching data of Gamblers with axios, which is being returned with this code in controller
public function getGamblers () {
echo Gambler::all();
}
However I would like to get all associated Horses as well. I can get one pretty easy just like this
public function getGamblers () {
echo Gambler::find(1)->horse;
}
but maybe there is possibility to do something like this, which in my case does not work
public function getGamblers () {
echo Gambler::all()->horse;
}
You should use return in Controllers, not echo.
Because you are using axios, a JsonResponse will be more appropriate:
public function getGamblers () {
return response()->json(Gambler::all(), 200);
}
Gambler::all() will return a Collection of Gambler.
On frontend, loop over the data you get from Laravel:
let gamblers = [];
axios.get('/your-get-gamblers-url')
.then(function (response) {
gamblers = response.data;
})
gamblers.forEach(gambler => console.log(gambler))
If for some reson you need to do something with each Gambler in php, you can loop over the collection like this:
$gamblers = Gambler::all()
foreach($gamblers as $gambler) {
//$gambler->horse
}
I want to send my data from controller to xedit.blade.php, but I get the same error
in controller:
public function index5()
{
$users=User::all();
return view('xedit')->with('users',$users);//xedit is from xedit.blade.php
}
my route:
Route::get('admin/edit', function () {
return view('xedit');
})->name('edit');
Route::get('edit', 'Admin\UserController#index5');
I get the error:
Undefined variable: users
Remove this route
Route::get('admin/edit', function () {
return view('xedit');
})->name('edit');
Because when you go to this route there is no users variable. You can pass here also if you want.
If you want named route then you can also named 2nd one like -
Route::get('edit', 'Admin\UserController#index5')->name('edit');
Also you can send user variable in first one like this-
Route::get('admin/edit', function () {
$users = App\User::all();
return view('xedit', compact('users'));
})->name('edit');
I am trying to return view where Task Created will have each user assigned to them.
Example
In my view blade, I click on Task Name -> it should return a view of task assign under task id 1 to add users to work on the task
Task Controller
public function show($id)
{
$task = Task::find($id);
$task->task_assignments = TaskAssignment::where('task_id', $task->id)->get();
return view('tAssignments.index')->with('task', $task);
}
Task Assignment Controller
public function show($id)
{
$task = Task::find($id);
$task_assignments = TaskAssignment::find($id);
return view('tAssignments.index', compact('task', 'task_assignments'));
}
Just fetch the data for that user about whom you want to know
Use
->findOrFail(id)
Return that data in the view file and render it according to use.
If you want it more perfectly you may use a ajax call .
This is how i manage to answer and pass the variable. Please let me know if there is any better view
public function show($id)
{
$task = Task::findOrFail($id);
$task_assignment = TaskAssignment::find($id);
$task->task_assignments = TaskAssignment::where('task_id', $task->id)->get();
return view('tAssignments.index', compact('task', 'task_assignment'))->with('task_id', $task->id);
}
I've looked at a few similar issues on SO, but I can't work out why recipes is being called?
I'm building a recipes website, and the user can create tags, create a recipe, create ingredients which are assigned to the recipe, and will be able to create steps which use the ingredients.
The following are my models:
Ingredient.php
class Ingredient extends Model
{
protected $touches = ['recipes'];
public function recipes(){
return $this->belongsToMany('App\Recipe', 'recipe_ingredients', 'ingredient_id', 'recipe_id');
}
public function step(){
return $this->belongsToMany('App\Step', 'step_ingredients');
}
}
Recipe.php
class Recipe extends Model
{
public function ingredients(){
return $this->belongsToMany ('App\Ingredient', 'recipe_ingredients', 'recipe_id', 'ingredient_id');
}
public function tags(){
return $this->belongsToMany('App\Tag', 'recipe_tag');
}
public function user(){
return $this->belongsTo('App\User');
}
public function steps(){
return $this->hasMany('App\Step');
}
}
Step.php
class Step extends Model
{
protected $touches = ['recipes'];
public function recipe(){
return $this->belongsTo('App\Recipe');
}
public function ingredient(){
return $this->belongsToMany('App\Ingredient', 'step_ingredient');
}
}
The following is my StepsController which I'm saving to from my steps/create.blade.php file via an Ajax submit with jQuery.
use Illuminate\Http\Request;
//use Session;
use App\Recipe;
use App\Tag;
use App\Step;
use App\Ingredient;
class StepsController extends Controller
{
public function __construct()
{
$this->middleware('auth');
}
public function create($recipe_id)
{
$recipe = Recipe::find($recipe_id);
return view('steps.create')->withRecipe($recipe);
}
public function store(Request $request)
{
$step = new Step;
$step->recipe_id = 2;
$step->step_no = 2;
$step->is_prep = 1;
$step->duration = '00:14:01';
$step->method = 'test';
$step->save();
$data = [
'success' => true,
'message'=> 'Your AJAX processed correctly',
'ing' => json_decode($request->ingredients),
'desc' => $request->description
] ;
return response()->json($data);
}
}
I'm using static values for the new Step to make sure that it writes to the db correctly, and it is.
If I comment out writing the step to the db, and just leave the $data array and return response... then it works fine, and I get the success response returned to the view.
When I include it, I get the error in the console:
[Error] Failed to load resource: the server responded with a status of 500 (Internal Server Error) (steps, line 0)
"message": "Method Illuminate\\Database\\Query\\Builder::recipes does not exist.",
But I'm not sure where the recipes method is being called?! I think it has something to do with my relationships in the model?
Any insight would be extremely appreciated.
Not sure if it's required, but the following is the part of my script that I"m using so submit data with Ajax.
$("#addStepNew").click(function() {
var step_ingredients = JSON.stringify(stepIngredients)
var step_description = $('#stepDescription').val();
// var prep_step = $('input[name=prepStep]:checked').val();
$.ajax({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
type: "post",
data: {ingredients: step_ingredients, description: step_description},
dataType:'json',
url: "{{ route('steps.store', ['id' => $recipe->id]) }}",
success: function (data) {
$("#ajaxOutput").html('<code>Description output: '+data.desc+'</code>');
$.each(data.ing, function (key, value) {
$("#ajaxOutput").append('<br><code>'+value.ingredient_name+'</code>');
});
},
error: function (xhr, ajaxOptions, thrownError) {
console.warn(xhr.responseText);
alert(xhr.status);
alert(thrownError);
}
});
});
It looks like it's the protected $touches = ['recipes']; from the Step model.
I guess it's trying to update a recipe that it's associated to, but that isn't being defined with a recipe_id.
I have following functions in Controller.
public function UpdateCountry(\App\Http\Requests\CountryRequest $request) {
$this->SaveChanges($request);
}
private function SaveChanges($request) {
if($request['CountryID'] == 0) {
$Country = new \App\Models\CountryModel();
}
else {
$Country = \App\Models\CountryModel
::where('CountryID', $request['CountryID'])->first();
}
$Country->Country = $request['Country'];
$Country->CountryCode = $request['CountryCode'];
$Country->save();
return redirect()->route('AllCountries');
}
public function AllCountries() {
$Countries = \App\Models\CountryModel::all();
return view('Country.List', array('Countries' => $Countries));
}
Issue is in below line: When I call function SaveChanges, I am not able to see List of countries page and when I write the code directly in UpdateCountry function, it redirect route successfully.
return redirect()->route('AllCountries');
Anybody faced this issue before ?
Your route is being handled by the UpdateCountry function. Laravel will take action based on the returned value from this function. However, you're not returning anything from this function.
You call SaveChanges, which returns a Redirect object, but then you don't return anything from your UpdateCountry function. You need that Redirect object from the UpdateCountry function in order for Laravel to actually return the redirect to the client.
Update your UpdateCountry function to this:
// added the return statement, so this function will return the redirect
// to the route handler.
public function UpdateCountry(\App\Http\Requests\CountryRequest $request) {
return $this->SaveChanges($request);
}
Maybe you missed a return in $this->SaveChanges($request). It has to be:
public function UpdateCountry(\App\Http\Requests\CountryRequest $request) {
return $this->SaveChanges($request);
}
I hope it works fine for you.