Deleting a record from table in Laravel - laravel

I am trying to delete a record within a table using Laravel. I've tried many different things.
I have the following in my view:
#foreach($providers as $provider)
<tr>
<td>{{$provider->{'Provider First Name'} }}</td>
<td>{{$provider->{'Provider Last Name (Legal Name)'} }}</td>
<td>{{$provider->{'Provider Credential Text'} }}</td>
<td>Link </td>
<form action="/blah/{{$provider->NPI}}" method="POST">
{{ csrf_field() }}
<td><button type="submit"> Delete </button> </td>
</form>
#endforeach
I have the following in my routes:
Route::post('/blah/{id}', function($id) {
//Get user id for currently logged in user
$user = Auth::id();
//Query UserToProviderMappings table to get record where provider is mapped to user
$query = DB::table('user_to_provider_mappings')
->where('user_id', $user)
->where('provider_npi', $id)
->delete();
// $query->delete();
// return back();
});;
The view works fine. When I click delete in the view, I get redirected to a search results page and the record is not deleted in the table. I did try both post and delete in the route/form.
The search results page I am being redirected to has the following route:
Route::resource ('search-results', 'SearchResultsController');
And the following in the SearchResultsController:
public function index()
{
{
//The search() function is accessed using 'scopeSearch' within NPIData Model
$providers = NPIData::search()->orderBy('NPI')->paginate(20);
return view('inc.searchresults', compact('providers'));
}

You are using Query Builder not Eloquent so you are not dealing with Models, so there is no delete method to be calling on anything that could be returned. You are also calling get which returns many results not 1 result.
Since you are using Query Builder you should just replace get() with delete() to do a DELETE query to remove the record(s).
It is entirely possible you are not deleting anything at all though. You should check the result of the delete().

Related

Display the connected customer information

I have 2 tables which are user and customer, The first table has the following fields: (id, name, email, password)
Then, the table customer has the following fields: (id, name, firstname).
In my Controller Customer, via my function index(), I have to retrieve id_user from my table user.
Question 1: Is my relationship correct between my 2 tables?
Model Customer
protected $fillable = ['name', 'firstname', 'user_id'];
public function user()
{
return $this->belongsTo('App\User');
}
Model User
public function customers()
{
return $this->hasOne('App\Customer');
}
Question 2: How do I retrieve ID of the user who is connected ?
I have for now this only...
public function index()
{
$customers = Customer::orderby('id', 'desc')->paginate(5);
return view('customers.index', compact('customers'));
}
Question 3: I want to understand the two answers, but I would also like to understand how I can adapt my file index.blade.php via my loop, please.
#foreach($customers as $customer)
<tr>
<td> {{$customer->name}}</td>
<td> {{$customer->firstname}}</td>
Thank you for your explanations.
Your models are good. If you want to return user relation for every customer you should try like this:
public function index()
{
$customers = Customer::with('user')->orderby('id', 'desc')->paginate(5);
return view('customers.index', compact('customers'));
}
And in your view you should have:
#foreach($customers as $customer)
<tr>
<td> {{$customer->name}}</td>
<td> {{$customer->firstname}}</td>
<td> {{$customer->user->id}}</td>
More about that here.
Question 1: Is my relationship correct between my 2 tables?
Yes, your relationship is correct.
Explanation:
For your customer table, you indicate that a customer profile belongs to one and only one user. This is an inverse one-to-one entity relationship.
For your user table, you indicate that a user has one and only one customer profile. This is a one-to-one entity relationship.
Question 2: How do I retrieve ID of the user who is connected?
Use Laravel's Eager Loading by calling the with() method to retrieve the customer data with the associated user data like this:
public function index()
{
$customers = Customer::with('user')->orderby('id', 'desc')->paginate(5);
return view('customers.index', compact('customers'));
}
Explanation:
The returned result can be visualized like this:
{Customer}
|
•id
•name
•firstname
•{user}
|
• id
• name
• email
Finally you can get the results including the user ID in your view like this:
#foreach($customers as $customer)
<tr>
<td>{{ $customer->user->id }}</td>
<td>{{ $customer->firstname }}</td>
<td>{{ $customer->name }</td>
</tr>
#endforeach
For more details on Laravel Entity Relationships see the relevant Laravel documentation.

Laravel - Populating view with info from single row (with pivot data)

I currently have a form/view that allows a User to save an Order. This also updates a pivot table with the respective Products and qtys. What I am trying to do, is after this information is inputted and saved into the database, I want to send the user to a checkout page that shows all the information they inputted for that Order.
Relationships
User hasMany Order
Order belongsToMany Product
Product belongsToMany Order
checkout.blade.php
#foreach ($orders as $order)
#foreach ($order->products as $product)
<tr>
<td>{{ $product->name }}</td>
<td>{{ $product->pivot->qty }}</td>
</tr>
#endforeach
#endforeach
OrderController.php
public function checkout($id)
{
$user = Auth::user();
$user->load("orders.products"); //eager load pivot table
$orders = $user->orders->where('order_id', $id);
return view('orders.checkout', compact('orders', 'user'));
}
I know I am calling the order incorrectly, because if I change
$orders = $user->orders->where('order_id', $id);
to
$orders = $user->orders;
It displays correctly, except of course, it populates with every Order's detail.
Or is there some elegant way for me to pass the data from the checkout function without this additional query? (I understand about moving data in Sessions, but I am working with a pivot table, and that complicates things.
If on the checkout page, you want to use just the latest order that the user has made, then you can just load that order using route model binding
Route::get('checkout/{order}', 'OrdersController#checkout');
Then in your controller:
public function checkout(Order $order)
so from here, you can pass this order to the view, and list all the products from this order, and also in your Order model you should have a reference to the user that this order belongs to:
public function user()
{
return $this->belongsTo(User::class);
}
Accessing columns from the pivot table will be:
#foreach($order->products as $product)
<div> {{ $product->pivot->column }} </div>
#endforeach

I am trying to delete a particular record from the table in Laravel 5.3

My view page code is
#foreach($clients as $client)
<tr>
<td>{{ $client->client_id }}</td>
<td>{{ $client->ip_address }}</td>
<td>{{ $client->netmask }}</td>
<td>
<a href= "del/{{$client->id}}"><button type = "button" class = "btn btn-danger ">
Delete
</button>
</td>
</tr>
#endforeach
My controller code for destroy method is :
public function destroy($id)
{
$clients = Subnet_behind_client::findOrFail( $id );
$clients->delete();
return view('view2',compact('clients'));
}
My route file is:
Route::get('del/{id}', 'Subnet_Behind_ClientController#destroy');
I am able to view the records in a table in my view page but I am unable to delete a record from that table.
Your code looks good to me.
By the way, if you are deleting a record using its primary key then you can use destroy()
https://laravel.com/docs/5.3/eloquent#deleting-models
Subnet_behind_client::destroy( $id );
This way you don't need to fetch the record you want to delete. It will optimize the performance a bit.
You're trying to call delete() method onto a collection of records returned from findOrFail() method.
By doing this you can't access the query builder as now you have an Collection instead of a QueryBuilder.
To make it work, you can do it like this:
$clients = Subnet_behind_client::findOrFail( $id )->delete();
return view('view2',compact('clients'));
Hope this helps!
Can you please use this way:
First of all print the data if exist or check for existing entry.
$clients = Subnet_behind_client::where('id', $id)->get();
// dd($clients);
if(count($clients)>0){
Subnet_behind_client::where('id', $id)->delete();
}
I think this trick will help you.
Make sure also if you forgot to mention define top of the controller:
use App\Subnet_behind_client;
This should work:
Subnet_behind_client::destroy( $id );
And for deleting, I would suggest to use DELETE request instead of GET.

How to view login user data in Laravel 5.2

I joined two table.
One classrooms and another joinclass table.
Here is my classrooms table
And here is my joinclass table
Here is my controller:
public function std_classes(Request $request)
{
$data = DB::table('classrooms')
->join('joinclass', 'classrooms.class_code', '=', 'joinclass.class_code')->get();
return View::make('std_classes')->with('data',$data);
}
And here is my view
#if(Auth::check())
#foreach($data as $data)
<h1>{{$data->class_name}}</h1>
#endforeach
#endif
Now in my view here show classrooms data.
But i want to view only login user data that's why i used #if(Auth::check())
But still now its view all data.
Why #if(Auth::check()) condition not working?
I need a clarifications, do you want to show only the data of the user that is actually logged in? In that case you should not use #if(Auth::check()) because it returns true if a user is logged and then cicle all the foreach data.
In that case you shoud check the logged user after the foreach, something like that:
#foreach($data as $data)
#if(Auth::user()->id == $data->user_id)
<h1>{{$data->class_name}}</h1>
#endif
#endforeach

Pagination in laravel 5 with realtion on where condition

Model smsHeader
protected $fillable = [
'type',
'imei',
'login',
'ver'
];
public function detail()
{
return $this->hasMany('App\Model\smsDetail', 'id_header');
}
Controller
$smsheader = smsHeader::orderBy('id', 'desc')->where('login', $user->email)->paginate(20);
return view('app.inbox')->with('smsheader', $smsheader);
Views
#foreach($smsheader as $header)
#foreach($header->detail->where('type', '1') as $detail)
<tr>
<td>{{$detail->number}}</td>
<td>{{$detail->name}}</td>
<td>{{$detail->text}}</td>
<td>{{$detail->date}}</td>
</tr>
#endforeach
#endforeach
but the result of pagination it was error, how i can set paginition in where smsdetail condition....??
sorry for my bad english
The error is showing for this line $header->detail->where('type', '1')
you can access $header->detail within foreach if you want to use where condition then you need to use get() at the end,like below
#foreach($smsheader as $header)
#foreach($header->detail->where('type', '1')->get() as $detail)
<tr>
<td>{{$detail->number}}</td>
<td>{{$detail->name}}</td>
<td>{{$detail->text}}</td>
<td>{{$detail->date}}</td>
</tr>
#endforeach
#endforeach
Laravel Queries within Blade views do not automatically execute. They simply prepare another QueryBuilder instance. You still need to run one of the "execute" methods (that will run PDOStatement::execute() underneath). These methods are:
first() (returns first result from result set as single object)
get() (which returns a Collection (ArrayObject with some added extra functionality))
paginate($numberPerPage) (which returns a Collection with extra meta information to pass to a $links property accessible via $collection->links())
In your example:
#foreach($smsheader as $header)
#foreach($header->detail->where('type', '1')->get() as $detail)
<tr>
<td>{{$detail->number}}</td>
<td>{{$detail->name}}</td>
<td>{{$detail->text}}</td>
<td>{{$detail->date}}</td>
</tr>
#endforeach
#endforeach

Resources