Laravel - delete specific post from logged in user - php

I'm trying to make a delete button on a post from a user that is logged in. The logged in user can see other peoples posts, and only delete his own. I already managed that the delete button only appears on his own posts. I think the problem is in the route in the view..
Controller:
public function destroy($id)
{
$post = Post::find($id);
$post->delete;
return view('/home', [
'posts' => $post
]);
}
view:
#if ($post->checkUser(Auth::user()))
<form action="{{ route('posts.destroy, $post') }}" method="POST">
<input type="hidden" name="_method" value="DELETE">
{{ csrf_field() }}
{{ method_field('DELETE') }}
<button>Delete</button>
</form>
#endif
Route:
Route::resource('posts', 'PostController');

Change $post->delete; to $post->delete(); because delete() method is a function. And if you use resource you should send request with delete method for call destroy method. but you can not do it from form because for support only post and get, another solution you can use hidden input and send with post method, <input name="_method" type="hidden" value="DELETE">

You need to specify post_id and user_id both.
public function destroy($id)
{
$user_id = Auth::user();
$post = Post::where('post_id', $id)->where('user_id',$user_id)-get();
$post->delete();
// do your rest of code
}
Change post_id and user_id name according to your table field name.

I think you should edit the route in your view to look like this,
route('posts.destroy, ['id' => $post->id]'), if that doesn't work check your named route again by doing php artisan route:list, and also try to post the full error for better understanding.

Related

Passing Collection from Blade to Controller

I am working on an application and need to pass data from Blade back to the controller
I am passing the data to the blade like this
$reports = $query->paginate();
return view('admin.report', compact('reports'));
this works fine, however I want to have a button to pass $reports collection to this function
public function exportToCSV(Document $reports)
this is going to create a CSV file that will be downloaded including every entry from $reports
I have doing a lot of googling on this and have even have someone help me try to figure it out to no avail.
One way to achieve this would be with a form. You can have a hidden input, with the collection as the value. You would define a route for the form to POST to, and call your function from the route in web.php.
<form action="/route/to/wherever/" method="POST">
{{ csrf_field() }}
<input type="hidden"
name="key"
value="{{ $collection }}"
>
</form>
Be sure to add a submit button. In your method you would receive the collection like:
public function myFunction(Request $request){
$data = $request->key;
}

why am i getting null value from my database in laravel when trying to find specific user?

Am trying to display information of a specific student in my database using student ID. I seem to get null value yet the student exist in the database. i seriously do not know why am getting this null value.
this is what i did
public function showResult(Request $request, $std_id)
{
$user = Student::find($std_id);
if (empty($user)) {
return redirect('/user')
}
$academic = $request->input('academic_year');
$std = $request -> input('studentID');
$results = DB::table('students')
->select('*')
->join('results', 'students.std_id', 'results.student_results_id')
->where('student_results_id', '=', $std)
->where('academic_year', '=', $academic)
->get();
return view('resultsdisplay',[
'results' => $results,
]);
}
}
This is my Route:
Route::get('/student/resultshow/{std_id}', 'ResultsController#showResult');
My studentprofile.blade.php
<li class="list-group-item">
<form action="{{URL::to('/student/resultshow/{!! $studentprofilePage->std_id !!}')}}" method="GET" enctype="multipart/form-data">
<input type="text" name="studentID" value="{!! $studentprofilePage->std_id !!}" hidden="">
<input type="text" name="academic_year" placeholder="Academic year..">
<button>view</button>
</form>
</li>
A couple of things to test. First, check the $std_id variable as it comes into the method to make sure this is translating correctly from your form / route into the method.
public function showResult(Request $request, $std_id){
dd($std_id);
If this is a properly formed integer/id, check the database just to make sure that id is actually assigned within the students table, and it is not soft-deleted if you are using soft-deletes (deleted_at column).
If all good there, take a look at the Student model itself. Is the model pointing to the right table? Laravel assumes the table is named 'students'. If not, have you declared the table within the model?
public $table = 'mySpecialStudentsTableName';
Also, is the id type correct against what is coming in. IE I assume it is an integer, but if it is looking for a string / uuid, is that properly coming out of that $std_id variable?
Finally - your form is not sending the correct id:
<form action="{{URL::to('/student/resultshow/{!! $studentprofilePage->std_id !!}')}}"
Should be:
<form action="{{URL::to('/student/resultshow/'. $studentprofilePage->std_id)}}"

Laravel input feature didn't work and show error 404

Hello everyone. i just learn laravel this month, and i get some problem that haven't solved since yesterday.
So i want to make a feature where i input a token and submit it, and the page will redirect to view page. the token will used by the controller to find row of data that match the token and will return the data to view page. i already (seems) succeed made the feature. the value of input is (should be) the token, initialized with {$kodeunik}, but what's confused me is when i input the form with {$id} the feature works, but if i inputted with {$kodeunik}, it didn't works. (shows 404) any solution? what should i do? Thanks
For info: ({$id} is the primary key and {$kodeunik} is the unique key)
this is the Controller.
public function cek()
{
return view('cek');
}
public function show(Request $request)
{
$kodeunik = urlencode($request -> input('kodeunik'));
$blog = blog::find($kodeunik);
if (!$blog)
{
abort(404);
}
return view('tampil', ['blog' => $blog]);
}
This is the Form view
<form method="get" action="/">
<div class="form-group row">
<label for="kodeunik" class="col-md-4 col-form-label text-md-right">Kode Unik</label>
<div class="col-md-6">
<input id="kodeunik" type="text" name="kodeunik">
</div>
</div>
<input type="submit" name="submit" value="cek">
{{csrf_field()}}
<input type="hidden" name="_method" value="get">
this is the Show View
#section('content')
<h1>Detail Laporan kau</h1>
<table class="maxw600 no-padding">
<tr><td><b>Status: </b></td><td>{{ $blog -> tag}}</td><br>
<tr><td><b>Nama: </b></td><td>{{ $blog -> nama}}</td></tr>
<tr><td><b>Bagian: </b></td><td>{{ $blog -> bagian}}</td></tr>
<tr><td><b>Telp/Ext: </b></td><td>{{ $blog -> telp}}</td></tr>
<tr><td><b>Email: </b></td><td>{{ $blog ->email}}</td></tr>
<tr><td><b>Subjek: </b></td><td>{{ $blog -> title}}</td></tr>
<tr><td><b>Deskripsi: </b></td></tr>
</table>
<p>{{ $blog -> description }}</p>
<p>{{ $blog -> tanggapan }}</p>
#endsection
This is the Route
Route::get('/cek', 'UserController#cek'); //this is route for the form view
Route::get('/', 'UserController#show'); //this is route for showing the result
Note: Eloquent will also assume that each table has a primary key column named id. You may define a primaryKey property to override this convention. Likewise, you may define a connection property to override the name of the database connection that should be used when utilizing the model.
In your case, when you pass id it works because laravel know's that its the default primary key in your table. Now when you pass kodeunik, laravel will still find kodeunik in id field of your table.
So here are some solution how to solve this.
first : change the primary key of your table by putting this code in your model
protected $primaryKey = 'kodeunik_field';
Second : just use where clause to get a result, like this
$blog = blog::where('kodeunik_field', $kodeunik)->get()->first();

Laravel: Trying to get property of non-object when taking data via foreign key

I have a User and a Tag model. Both are linked by a 1:N relation.
I am trying to take col tag_name from user model. However I am receiving this error:
Trying to get Trying to get property 'tag_name' of non-object.
User model has
// linking with table tag
public function tags(){
return $this->hasMany('App\Tag');
}
Tag model has
public function user(){
return $this->belongsTo('App\User', 'user_id');
}
My view has
{{ Form::checkbox('tag[]',$user->tag_id,['class'=>'cats']) }}
{{ Form::label('tb',$user->tag_id->tag_name,['class'=>'btn btncategory']) }}
Controller has the following in index function
$user = User::find($user_id);
return view('user.create_post')->with('user', $user );
Route:
Route::get('create', 'PostsController#index');
Please help me where I am wrong.
Thanks in advance.
The problem is that your user has multiple tags you need to loop through each of them:
In blade file:
#foreach ($user->tags as $tag)
<label class="btn btncategory">
<input type="checkbox" name=tag[] value="{{$tag->id}}" class="cats" />
{{$tag->name}}
</label>
#endforeach
Now when you submit this you should have all checked tags in the array request()->input('tag')
Note I've removed the Form:: because I like to put the checkboxes inside the label but you can just use the Form:: style if you want like below:
#foreach ($user->tags as $tag)
{{ Form::checkbox('tag[]',$tag->id,['class' => 'cats']) }}
{{ Form::label('tb',$tag->name,['class' => 'btn btncategory']) }}
#endforeach

How to delete a single record in Laravel 5?

Using Laravel 5 I m trying to delete a single record within a controller, here is my code:
public function destroy($id)
{
$employee = Employee::find($id);
$employee->delete();
return Redirect::route('noorsi.employee.index');
}
My view page code is:
<td>Delete</td>
My route is:
Route::delete(employee.'/{id}', array('as' => 'noorsi.employee.destroy','uses' => Employeecontroller.'#destroy'));
That did not work.
How do I fix the implementation ?
From the official Laravel 5 documentation:
Delete an existing Model
$user = User::find(1);
$user->delete();
Deleting An Existing Model By Key
User::destroy(1);
User::destroy([1, 2, 3]);
User::destroy(1, 2, 3);
In every cases, the number between brackets represents the object ID, but you may also run a delete query on a set of models:
$affectedRows = User::where('votes', '>', 100)->delete();
http://laravel.com/docs/5.0/eloquent#insert-update-delete
So the Laravel's way of deleting using the destroy function is
<form action="{{ url('employee' , $employee->id ) }}" method="POST">
{{ csrf_field() }}
{{ method_field('DELETE') }}
<button>Delete Employee</button>
</form>
You can find an example here http://laravel.com/docs/5.1/quickstart-intermediate#adding-the-delete-button
And your route should look something like this
Route::delete('employee/{id}', array('as' => 'employee.destroy','uses' => 'Employeecontroller#destroy'));
It works with eg:Route::resource('employee', 'EmployeeController'); and it should also work with how you set up your destroy route.
Obviously you have a bad routing problem. You're trying to use a 'get' verb to reach a route defined with a 'delete' verb.
If you want to use an anchor to delete a record, you should add this route:
Route::get('/employee/{id}/destroy', ['uses' => 'EmployeeController#destroy']);
or keep using a delete verb, but then you need to use a form (not an anchor) with a parameter called _method and value 'delete' stating that you're using a 'delete' verb.
Route::get('/showcon/{del_id}/delete','MainController#deletemsg');
public function deletemsg($del_id){
$mail=Mail::find($del_id);
$mail->delete($mail->id);
return redirect()->back();
}
del

Categories