I'm Doing a "take home assignment" for job interview. While I have some experience in web development, its not my forte. I am trying to delete a row in a SQLite table using a HTML DELETE button. I am using Laravel-php framework.
I've tried different solutions on google and stack Overflow, but none seem to solve the problem. I modeled my approach after this Laracasts video
Link to my code
The blade seems to be passing the correct info ($id from $contact->id) & the controller seems to be receiving. But the given contact associated with the id isn't being deleted.
FROM BLADE:
<div class="col-md-6">
<table class="table table-striped table-hover">
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Address</th>
</tr>
#foreach($contacts as $contact)
<tr>
<td> {{$contact->f_name}} </td>
<td> {{$contact->l_name}} </td>
<td> {{$contact->address}} </td>
<td>
<form method="POST" action="/delete/{{ $contact->id }}">
#method('DELETE')
#csrf
<div class="field">
<div class="control">
<button type="submit" class="button">Delete Contact</button>
</div>
</div>
</form>
</td>
</tr>
#endforeach
<tr>
<td></td>
<td></td>
<td></td>
</tr>
</table>
</div>
FROM CONTROLLER:
public function delete($id) {
Contact::find($id)->delete();
return view('index');
}
FROM ROUTE:
Route::delete('/delete', [
'uses'=>'ContactController#delete',
'as'=>'contacts.delete'
]);
you're not getting the id on your delete method, you need to include it on the url like
Route::delete('/delete/{id}', [
'uses'=>'ContactController#delete',
'as'=>'contacts.delete'
]);
in this case, you don't need to change the delete method.
you can also retrieve the id from the request object without changing the delete route, int this case you need to include the id as a hidden input on your view and your delete method will look like this
public function delete(Request $request) {
Contact::find($request->id)->delete();
return view('index');
}
Related
I faced an issue where I'm unable to retrieve data through the pivot table,
In my application there's a separate table to store the files data and a separate table to store the competition and a separate table to store the teams.
And there's a table named competition_file which has the competition_id, team_id, file_id.
a user can add multiple files to a competition by selecting a team or by not selecting a team as show in the below image
It will be synced to the competition_file table as shown in the below image
I need to show all data in the UI as a table shown in below image
I'm wondering how can I fill the team name selected using the pivot table
Relationship in File Model
public function teams()
{
return $this->belongsToMany(Team::class,'competition_file')->wherePivot('type','document');
}
Relationship in Competition Model
public function documents()
{
return $this->belongsToMany(File::class,'competition_file','competition_id', 'file_id')->wherePivot('type','document');
}
And this is my controller index function
public function index($id)
{
$competition = $this->competitionsRepo->find($id,[
'team',
'documents',
]);
return view('competitions.document',[
'competition'=>$competition,
]);
}
My Blade
#foreach ($competition->documents as $key=>$document)
<tr>
<td>{{ $key+1 }}</td>
<td>{{ $document->name }}</td>
<td>-</td>
<td>{{ $document->created_at->toDateString() }}</td>
<td>
<form class="confirm" action="{{ route('documents.destroy',['competition'=>$competition,'document'=> $document->id]) }}" method="POST"
data-confirm-title="Remove Document?"
data-confirm-message="Are you sure you want to remove this document?">
#csrf
#method('DELETE')
<button type="submit" name="button" class="button">Remove</button>
</form>
</td>
</tr>
#endforeach
Someone please help me out to get the team names to my foreach in the blade
I hope my question is clear, please comment if it isn't ill edit the question
I was able to fix my issue by learning Eager loading through a recommendation
Here are the changes I did
In controller
public function index($id)
{
$competition = $this->competitionsRepo->findOrFail($id);
$files = $competition->documents()->with(
[
'teams' => function($q) use ($competition) {
$q->with([
'documents' => function($q) use($competition) {
$q->where([
'competition_id' => $competition->id,
]);
}
]);
},
]
)->get();
return view('competitions.document',[
'id'=>$id,
'competition'=>$competition,
'files'=>$files,
]);
}
In my Blade table i used $file->teams->implode('name')
<table class="table light-td sports-tbl tb-chg2 table-condensed table-borderless">
<thead>
<tr>
<th>#</th>
<th>Document Name</th>
<th>Assigned Team</th>
<th>Date Added</th>
<th>Action</th>
</tr>
</thead>
<tbody>
#foreach ($files as $key=>$file)
<tr>
<td>{{ $key+1 }}</td>
<td>
<a href="{{ asset('storage/'. $file->file_path) }}" class="text-info" target="_blank">
<img src="{{ asset('/images/sketches/1x/file.png') }}" alt="file">
</a>
{{ $file->name }}
</td>
<td>
{!! $file->teams->isNotEmpty() ? $file->teams->implode('name') : '<span class="text-secondary">No teams selected</span>' !!}
</td>
<td>{{ $file->created_at->toDateString() }}</td>
<td>
<form class="confirm" action="{{ route('documents.destroy',['competition'=>$id,'document'=> $file->id]) }}" method="POST"
data-confirm-title="Remove Document?"
data-confirm-message="Are you sure you want to remove this document?">
#csrf
#method('DELETE')
<button type="submit" name="button" class="button">Remove</button>
</form>
</td>
</tr>
#endforeach
</tbody>
</table>
Hello i'm trying to display the authenticated user but i'm getting this error :
Undefined variable: users (View:
C:\wamp64\www\Blan\resources\views\users\index.blade.php)
this is my code :
usercontroller :
public function index()
{
return view('users.index')->with('user', Auth::user());
}
the view :
#extends('layouts.app')
#section('content')
<div class="card">
<div class="card-header">
Update Your Profile
</div>
<div class="card-body">
<table class="table table-hover">
<thead>
<th>Image</th>
<th>Name</th>
<th>Update</th>
</thead>
<tbody>
#if( $users -> count() > 0 )
#foreach ($users as $user)
<tr>
<td>
#if(isset($user->profile->avatar))
<img src="{{ asset($user->profile->avatar)}}" width="60px" height="60px" style="border-radius: 50%" alt="">
#else
No image
#endif
</td>
<td>
{{$user->name}}
</td>
<td>
Update
</td>
</tr>
#endforeach
#else
<tr>
<th colspan="5" class="text-center">No Users </th>
</tr>
#endif
</tbody>
</table>
</div>
</div>
#stop
But if i return all the users using this code in the controller :
return view('users.index')->with('users', User::all());
its work fine.
so how i can return only the current authenticated user ?
You don't need to send the auth user via your controller.Auth is the global facade in laravel.Also you don't need foreach because there is only 1 authenticated user. Just type Auth::user()->name in the blade
where you want to display the user
Yea and btw the error ur getting is because you are doing foreach for $users but sending $user to blade but im pretty sure it wont work even if you correct that typo
In your example
public function index()
{
return view('users.index')->with('user', Auth::user());
}
You have used "user"
But tried to access variable as "users"
Unless you just made a typo in your example?
I am new to Laravel. I am learning Laravel from tutorial and I drive into one problem which I can't solve.
I think I have problem somewhere into Routing, but I can't find it
Funny thing is that if the href is {{route('tag.create'}}, then it goes to creating page, but when I need to use ID it's not working...
I had same functionality for posts and categories, but everything worked fine for those two. So I really need your help to see what I can't see. I have these files:
index.blade.php:
#extends('layouts.app')
#section('content')
<div class="card">
<div class="card-body">
<table class="table table-hover">
<thead>
<th>
Tag name
</th>
<th>
Delete
</th>
</thead>
<tbody>
#if($tags->count()>0)
#foreach($tags as $tag)
<tr>
<td>
{{$tag->tag}}
</td>
<td>
<i class="fa fa-trash" aria-hidden="true"></i>
</td>
</tr>
#endforeach
#else
<tr>
<th colspan="5" class="text-center">
No tags yet
</th>
</tr>
#endif
</tbody>
</table>
</div>
</div>
#stop
web.php - this is the place where I define routes for tags for TagsController.php:
//Tags
Route::get('/tags',[
'uses'=>'TagsController#index',
'as'=> 'tags'
]);
Route::post('/tag/update/{$id}',[
'uses'=>'TagsController#update',
'as'=> 'tag.update'
]);
Route::get('/tag/create',[
'uses'=>'TagsController#create',
'as'=> 'tag.create'
]);
Route::post('/tag/store',[
'uses'=>'TagsController#store',
'as'=> 'tag.store'
]);
Route::get('/tag/delete/{$id}',[
'uses'=>'TagsController#destroy',
'as'=> 'tag.delete'
]);
TagsController.php - at first I tried to destroy the element, then I tried to return create view(because when I go through /tag/create rout everything works), but neither worked here
public function destroy($id)
{
return view ('admin.tags.create');
/*
Tag::destroy($id);
Session::flash('success', 'Tag deleted succesfully');
return redirect()->back();*/
}
I believe that you should set the route to Route::get('/tag/delete/{id}',[ 'uses'=>'TagsController#destroy', 'as'=> 'tag.delete' ]); because in your case you are telling the route to expect a variable called $id
Please change the parameters in the route setup in web.php from $id to id. I should solve your issue.
Eg: Route::get('/tag/delete/{id}',[
'uses'=>'TagsController#destroy',
'as'=> 'tag.delete'
]);
Thanks !!.
I am trying to use controller's update function on my dashboard.blade.php page, but when I press on "Save" it switches to show.blade.php page instead of updating.
My dashboard.blade.php page:
#if(count($posts) > 0 )
<table class="table table-striped">
<tr>
<th>Title</th>
<th>Body</th>
<th>Employee Number</th>
<th>Edit</th>
<th>Save</th>
</tr>
#foreach($posts as $post)
<tr>
<td>{{$post->title}}</td>
<td><input type='text' name='body'class='form-control' value='{{$post->body}}'></td>
<td>{{$post->employee_no}}</td>
<td><a href="{{ action("PostsController#update", $post->id) }}" >Save</a></td>
<td>Edit</td>
</tr>
#endforeach
</table>
#else
<p>You Have No Posts</p>
#endif
My update function on PostsController.php page:
public function update(Request $request, $id)
{
$this->validate($request,[
//'title' => 'required',
'body' => 'required'
]);
//Update Post
$post = Post::find($id);
//$post->title = $request->input('title');
$post->body = $request->input('body');
$post->save();
return redirect('/posts')->with('success','Post Updated');
}
I read that "action" will go to the first route that matches the pattern, but I do not know how to solve this problem.
My web.php page:
Route::get('/', 'PagesController#index');
Route::get('/about', 'PagesController#about');
Route::get('/services', 'PagesController#services');
Route::resource('posts','PostsController');
Auth::routes();
Route::get('/dashboard', 'DashboardController#index');
How can I call the update function correctly from dashboard.blade.php page?
To update data you have to use form with put method.
and route will be like this,
Route::put('dashboard/update/{id}',[
'uses' => 'DashboardController#update',
'as' => 'dashboard.update'
]);
For more Laravel Routing
Hope it helps :)
You can solve this by using form submit with hidden PUT method.
<form action="{{ url('customers') }}/{{$data['customer']->id}}" method="POST">
<input type="hidden" name="_method" value="PUT">
#csrf
</form>
How about having a simple form for each row in the table :
#if(count($posts) > 0 )
<table class="table table-striped">
<tr>
<th>Title</th>
<th>Body</th>
<th>Employee Number</th>
<th>Edit</th>
<th>Save</th>
</tr>
#foreach($posts as $post)
<tr>
<td>{{$post->title}}</td>
<td>{{$post->employee_no}}</td>
<td>
<!-- Form for each row -->
<form action="{{ route("posts.update", [ 'post' => $post->id ]) }}" method="POST">
#method('PUT')
#csrf
<input type='text' name='body'class='form-control' value='{{$post->body}}'></td>
<button type="submit">Save</button>
</form>
<!-- Form for each row -->
<td>Edit</td>
</tr>
#endforeach
</table>
#else
<p>You Have No Posts</p>
#endif
I'm initiating my tests using phpunit so, I have doubts about how to test things dynamically. I created a table dynamically as the image bellow
Here are my view:
<div class="panel-body">
#if(Session::has('success'))
<div class="alert alert-success">{{Session::get('success')}}</div>
#endif
<table class="table">
<th>Unity Name</th>
<th>Phone Number</th>
<th>Actions</th>
<tbody>
#foreach($companies as $company)
<tr>
<td>{{$company->name}}</td>
<td>{{$company->owner_number}}</td>
<td>
{{Form::open(['method' => 'DELETE', 'url'=>'/admin/company/'.$company->id, 'style' => 'display:inline'])}}
<button type="submit" class="btn btn-default fa fa-trash-o"></button>
{{Form::close()}}
</td>
</tr>
#endforeach
</tbody>
</table>
</div>
</div>
So, how can I test the href tag if I haven't previously the tag id?
I did some tests like these one in Symfony projects.
In dev environment, I insert some data in a dev database. After this step, I launch functionnal tests. In these tests, I analyze tag's content. Here is an example from your data :
$client = static::createClient();
$crawler = $client->request('GET', '/yourUrl');
$node = $crawler->filter('#show-company-1');
self::assertNotEmpty($node, "Node #show-company-1 does not exists");
self::assertEmpty( $node->html(), "#show-company-1 content is not empty");
self::assertContains('/admin/company/1', $node->attr('href'), "a#show-company-1.href has not a good value");
Before request, you can add some logic to determine the id of your company.