Is it possible to delete record without using forms in laravel 5.4 - laravel-5

I want to delete a record but I haven't been successful, apparently my code is wrong. Solutions i came across say i have to use a post in my form method and add the method_field helper. This would mean my view having a form in it, i want to avoid this if possible. Is it then possible to do my delete another way. Below is my code
snippet of my view
<div class="backbtn">
<a class="btn btn-savvy-delete" href="/tasks/{{$task->id}}" data-toggle="tooltip" title="Delete"><i class="fa fa-trash-o" aria-hidden="true"> Delete</i></a>
</div>
<div class="panel-body">
<p><strong>Owner:</strong> {{ ucfirst($task->employee->firstname) }} {{" "}} {{ ucfirst($task->employee->lastname) }}</p>
<p><strong>Task:</strong> {{ $task->title }}</p>
<p><strong>Description:</strong> {{ $task->description }}</p>
</div>
TaskController
public function destroy($id)
{
Task::destroy($id);
Session::flash('status', "Task was successfully deleted.");
return redirect('/tasks');
}
web.php
Route::delete('/tasks/{id}', 'TaskController#delete');

Im not sure what error you are getting, but i can point out a few things. For one use Route::get instead of ::delete, you are calling it via a link not a form method.
Secondly to delete follow what the laravel doc says here eg.
$task = App\Task::find(1);
$task->delete();

Related

Laravel returns 404 error when passing a parameter

Hello when I send a data press a link to show another view laravel returns a 404 error, what am I failing?, I have created other crud and I have had no problems so far
Expansion -> index.blade.php:
<a href="{{url('/cards/'.$expansion->exp_id.'/vcards')}}"class="btn btn-primary form-control" >Go!</a>
URL:
http://localhost/CardSystem/cartas/1/vcards
Route:
Route::resource('cards', 'cardControllerr');
cardController:
public function vcards($id){
$data['cards']= DB::table('cards')
->join('expansion','expansion.exp_id','=','cards.exp_id')
->select('cards.card_id','cards.card_nom','expansion.exp_nom')
->where('cards.exp_id','=',$id)
->orderBy('cards.card_num')
->paginate(5);
return view('cards.vcards',$data);
vcards.blade.php:
#extends('layouts.app')
#section('content')
<div class="container">
#foreach($cards as $card)
<div class="form-group">
<h5 class="card-title">{{$card->card_nom}}</h5>
</div>
#endforeach
</div>
#endsection
I think you misunderstood routing, views etc.
For your controller to be hit, you will need to make the following route.
Route::get('cartas/{card}/vcards', 'cardControllerr#vcards')->name('cartas.vcards');
If you wanna link to this route use route().
route('cartas.vcards', ['card' => $card]);

How do I use a row count in an #if in a Laravel view?

I am brand new to Laravel and I'm running Version 6.
I want my view to display a button if one of my MySQL tables has rows that meet a specific condition but I'm having trouble figuring out how to code it - and even WHERE to code it - within my Laravel application.
My MySQL table is called diary_entries and various users of the system will contribute zero to n rows to it. Each row of the table contains a user id called client. When a given user goes to the Welcome view, I want the view to determine if that user currently has any rows in the diary_entries table. If he does, I want to display a button that will take him to another page where the entries can be displayed or edited or deleted.
I think I want to construct an #if that counts the number of records for that user; if the count is greater than zero, I want to display the button, otherwise the button is not displayed.
The problem is that I can't figure out how to code this. I've looked at the examples in the Eloquent section of the manual but they aren't particularly clear to me. I found a note near the top that said the count() function expects a Collection as an argument and that the result of an Eloquent statement is always a Collection so I guessed that I just have to execute an Eloquent query, then apply count() to the resulting Collection. But every variation of that idea which I've tried has thrown exceptions.
Here was the guess that seemed most logical to me:
#extends('layout');
#section('content');
<div class="content">
<img class="centered" src="/images/sleeping-cat.jpg" alt="sleeping cat" height="250">
<div class="title m-b-md">
<h1> Sleep Diary </h1>
</div>
<div>
<h3>{{Auth::user()->name }}</h3>
</div>
<div>
#if (count(App\DiaryEntry::select('*')->where('client', Auth::user()->name) > 0))
<p>
<a class="btn btn-primary"> View / edit existing sleep diary entries </a>
</p>
#endif
</div>
<div>
<p>
<a class="btn btn-primary" href="/diaryEntries"> Create a new sleep diary entry </a>
</div>
</div>
#endsection
This is obviously wrong because it throws an exception so how do I make it right? Does the building of the collection have to move into the Controller? If so, how do I invoke the method and see its result? Or can I do something like I have already done but just adjust the syntax a bit?
EDIT
I've imitated Sehdev's suggestion but I get this error:
$count is undefined
Make the variable optional in the blade template. Replace {{ $count }} with {{ $count ?? '' }}
Here is my welcome view:
#extends('layout');
#section('content');
<div class="content">
<img class="centered" src="/images/sleeping-cat.jpg" alt="sleeping cat" height="250">
<div class="title m-b-md">
<h1>Sleep Diary</h1>
</div>
<div>
<h3>{{ Auth::user()->name }}</h3>
</div>
<div>
#if ($count) > 0))
<p>
<a class="btn btn-primary">View/edit existing sleep diary entries</a>
</p>
#endif
</div>
<div>
<p><a class="btn btn-primary" href="/diaryEntries">Create a new sleep diary entry</a>
</div>
</div>
#endsection
And this is the relevant function from DiaryEntryController:
public function countEntriesOneUser()
{
$count = DiaryEntry::select('*')->where('client', Auth::user()->name)->count();
view("welcome", compact("count"));
}
Should the compact function be returning $count instead of count? I can't find the compact function in the manual with the search function so I'm not clear what it does or what the proper syntax is. I just tried changing the last line of the function to
view("welcome", $count);
but that produced the same error.
Try this,
#php
$count=\App\DiaryEntry::where('client', Auth::user()->name)->count();
#endphp
#if($count>1)
<p><a class="btn btn-primary">View/edit existing sleep diary entries</a></p>
#endif
Using App\DiaryEntry::select('*')->where('client', Auth::user()->name) directly on your blade template is a bad practise.
You can execute your question in your controllers method and then pass the result on your view file
Your function
function test(){
$count = DiaryEntry::select('*')->where('client', Auth::user()->name)->count(); // get the total no of records using count
view("index", compact("count")) // pass your count variable here
}
then you can directly use $count in your #if condition
Your blade template
<div>
#if ($count > 0)
<p><a class="btn btn-primary">View/edit existing sleep diary entries</a></p>
#endif
</div>

Laravel WhereIn Doesn't Accept Array Value

I have this on my blade file:
{{ Form::open(['route' => 'my_route_name']) }}
<button type="submit" class="btn btn-sm btn-success">
<i class="fa fa-file-excel-o" aria-hidden="true"></i> Download
</button>
{{ Form::hidden('my_ids', $my_ids) }}
{{ Form::close() }}
Checking on the chrome's developer mode, the value of my hidden textbox named my_ids is:
[1,2,3,4,5,6]
Upon clicking the Download button, it goes on my controller:
$results= Model::whereIn('id', $request->my_ids)->get();
This is where I am getting an error.
DD-ing dd($request->my_ids) on my controller gives me "[1,2,3,4,5,6]".
However, if I just put the values directly on the eloquent query like below, it would work.
$results= Model::whereIn('id', [1,2,3,4,5,6])->get();
Am I missing something here?
Your dd shows that $request->my_ids is a string, therefore you must parse it before you use it as array.
Try
$results= Model::whereIn('id', json_decode($request->my_ids))->get();

Laravel: How to create link buttons on a view dynamically?

I'm making a College Administration website where a professor can log in.
I have a dashboard, where my dynamically generated button should be placed: (right now it just has dummy buttons!)
Generated by this view file, which I will have to modify soon:
<div class="container d-flex flex-column align-items-center justify-content-center">
<h1>IA DASHBOARD</h1>
<br>
<div class="grid2">
SUBCODE 1</button>
SUBCODE 2</button>
SUBCODE 3</button>
</div>
Tables in the Database:
the table iamarks contains the data (student info, and marks) that is to be displayed after /subcode/{subcode} narrows it down to records of just the students that are in the class assigned to current logged-in professor.
classroom_mappers is a table used to map a professor to a classroom with a subject. It makes sure that one classroom only has one professor for a particular subject.
the routes currently in my web.php:
route::get('/ia', 'IAController#show')->middleware('auth');
Route::get('/subcode/{subcode}', 'IAController#showTable')->middleware('auth');
...and these are the methods inside my controller:
//shows buttons to the user:
public function show(){
$subcodes = DB::table('classroom_mappers')
->select('subcode')
->where([['PID','=', auth()->user()->PID]])
->get();
return view('ia',compact('subcodes'));
}
//when user clicks a button, subcode is to be generated and a table is to be shown:
//it works, I tried it by manually typing in subcode value in URL.
public function showTable($subcode){
$sem = DB::table('classroom_mappers')
->where([['PID','=', auth()->user()->PID],
['subcode','=',$subcode]])
->pluck('semester');
$division = DB::table('classroom_mappers')
->where([['PID','=', auth()->user()->PID],
['semester','=',$sem],
['subcode','=',$subcode]])
->pluck('division');
$data = DB::table('iamarks')
->where([['semester','=',$sem],
['division','=',$division],
['subcode','=',$subcode]])
->get();
return view('subcode',compact('data'));
}
My Problem:
To be able to generate the {subcode} in the URL dynamically, I want to create buttons in the dashboard using the data $subcodes. The controller hands over the $subcodes (an array of subject codes which belong to logged in professor) which are to be made into buttons from the show() method.
The buttons should have the name {subcode} and when clicked, should append the same subject code in the URL as {subcode}.
How do I make use of $subcodes and make the buttons dynamically?
How do I make sure the buttons made for one user are not visible to another user?
I managed to find the solution, thanks to Air Petr.
Apparently, you can't nest blade syntax like {{some_stuff {{ more_stuff }} }} and it generates a wrong php code. I modified the solution by Air Petr to:
<div class="grid2">
#foreach ($subcodes as $subcode)
<a href="<?php echo e(url('/subcode/'.$subcode->subcode));?>">
<button class="btn btn-outline-primary btn-custom-outline-primary btn-custom">
<?php
echo e($subcode->subcode);
?>
</button>
</a>
#endforeach
</div>
It generates the buttons perfectly. The buttons for one user are not visible to another, since I'm using PID constraint in a query (['PID','=', auth()->user()->PID]).
Pass the passcodes array to view:
$subcodes = []; // Array retrieved from DB
return view('subcode', compact('subcodes'));
And in subcode.blade.php, loop through each subcode:
<div class="grid2">
#foreach($subcodes as $subcode)
<a href="{{ url('/subcode/' . $subcode->subcode) }}">
<button class="btn btn-outline-primary btn-custom-outline-primary btn-custom">SUBCODE {{ $subcode->subcode }}</button>
</a>
#endforeach
</div>
You can loop your codes to create buttons. Something like this (it's for "blade" template engine):
<div class="grid2">
#foreach ($subcodes as $subcode)
{{ $subcode->subcode }}</button>
#endforeach
</div>
Since you're using PID constrain in a query (['PID','=', auth()->user()->PID]), you'll get buttons for that specific PID. So there's no problem.

Laravel 4 how to display flash message in view?

I'm trying to get my flash message to display.
This is in my routing file
Route::post('users/groups/save', function(){
return Redirect::to('users/groups')->withInput()->with('success', 'Group Created Successfully.');
});
This is in my view
{{ $success = Session::get('success') }}
#if($success)
<div class="alert-box success">
<h2>{{ $success }}</h2>
</div>
#endif
But nothing is working.
When I try this, I get an error Variable $success is undefined. But it actually shows the flash message too.
{{ Session::get('success') }}
#if($success)
<div class="alert-box success">
<h2>{{ $success }}</h2>
</div>
#endif
This works for me
#if(Session::has('success'))
<div class="alert-box success">
<h2>{{ Session::get('success') }}</h2>
</div>
#endif
if you are using bootstrap-3 try the script below for Alert Style
#if(Session::has('success'))
<div class="alert alert-success">
<h2>{{ Session::get('success') }}</h2>
</div>
#endif
when you set variable or message using ->with() it doesn't set the variable/message in the session flash, rather it creates an variable which is available in your view, so in your case just use $success instead of Session::get('success')
And in case you want to set the message in the session flash the use this Session::flash('key', 'value'); but remember with session flash the data is available only for next request.
Otherwise you can use Session::put('key', 'value'); to store in session
for more info read here
two methods:
Method 1 - if you're using
return Redirect::to('users/groups')->withInput()->with('success', 'Group Created Successfully.');
under your controller create(), add in
$success = Session::get('success');
return View::make('viewfile')->with('success', $success);
then on view page,
#if (isset($success))
{{$success }}
#endif
What's happening in method 1 is that you're creating a variable $success that's passed into your create(), but it has no way of display $success. isset will always fail unless you set a variable to get the message and return it.
Method 2 - use return Redirect withFlashMessage
return Redirect::route('users/groups')->withFlashMessage('Group Created Successfully.');
then on your view page,
#if (Session::has('flash_message'))
{{ Session::get('flash_message') }}
#endif
Method 2 is much cleaner and does not require additional code under create().
{{ Session::get('success') }}
This just echos the session variable 'success'. So when you use
{{ Session::get('success') }}
#if($success)
<div class="alert-box success">
<h2>{{ $success }}</h2>
</div>
#endif
you are seeing it's output along with the error of the next statement. Because with() function only sets the value in Session and will not set as a variable. Hence #if($success) will result in undefined variable error.
As #Andreyco said,
#if(Session::has('success'))
<div class="alert-box success">
<h2>{{ Session::get('success') }}</h2>
</div>
#endif
This should work.
The reason you are not seeing it might be because the action you are performing is not success. And this does not require you to either reinstall xampp or modify php.ini.
Laravel 4.2
Personally i use
Session::flash('key', 'value');
return Redirect::to('some/url');
then in the view id first check if there is a session of that key in the view
#if(Session::has('key'))
{{Session::get('key')}} //this prints out the message or your 'value' in the session::flash method
#endif
it works for me most of the time and i usually have that blade template integrated into my view just so i can push success messages to the view from my codes.
please do note that it is stated in the documentation that "Sometimes you may wish to store items in the session only for the next request. You may do so using the Session::flash method" so yes it expires after the next page.
hope this helps
i just realized in using the Redirect::to(), when you use the withInput() method, chaining a with() function to pass variables will not work. the only way is either you flash your inputs separately using Input::flash(), and use the with() to pass your variables or you pass your variable via session using Session::flash('key','val') and retrieve in the view via session::get('key').
This link describes how to do this http://vegibit.com/flash-messages-in-laravel/
Just tried with laravel 5 - works to me.
Inside of the routes.php file try to create your routes within the
Route::group(['middleware' => ['web']], function () {
//routes here
}
then use
#if(Session::has('success'))
<div class="alert-box success">
<h2>{{ Session::get('success') }}</h2>
</div>
#endif
I fixed mine by changing the session driver in config/session.php from array to file !

Resources