I have a function that is taking an id as a param, and updates the db using the DB method. however, when i run the code, the variable is not being passed to the method. to test, i replaced $id with an integer and it worked, so i think the DB method can not access the variable from the parameter
public function disable($id)
{
// Update the user status to 0 from 1
DB::table('employees')->where('id', $id)->update(['status' => 0]);
return redirect('/employee')->with('error', 'User is disabled, all related accounts are now shutdown!...');
}
Update:
Forgot to mention that i have already checked, and the param comes inside the function OK, i can return the id outside of the method
SOLUTION
As shown in the comment, the varDump was returning "id=9" where i need "9", i noticed in the form piece of my code, there was an extra "id=" before the id which caused a malfunction.
Use function as disable(Request $request) and get id as $request->id
public function disable(Request $request)
{
// Update the user status to 0 from 1
DB::table('employees')->where('id', $request->id)->update(['status' => 0]);
return redirect('/employee')->with('error', 'User is disabled, all related accounts are now shutdown!...');
}
Related
i have tried to update data of my database, but there is no error
this my method
public function update_pj_si(request $request)
{
$id = $request->id;
DB::table('tbl_profil_penyedia')
->where('id_profil_penyedia', $id)
->update(array('status' => 1));
return redirect('/verif/pj_si');
}
if i run this method, it run correctly and no error but the database is not updated.
how can i fix this?
The $id variable doesn't contain a value that exists in your table, tbl_profil_penyedia, for the field id_profil_penyedia. It is as simple as that.
You are trying to update a profil_penyedia that doesn't exist.
The update call returning 0, means it didn't update any rows, which means your where condition didn't yield any results to be updated.
I am trying to make my URL more SEO friendly on my Laravel application by replacing the ID number of a certain object by the name on the URL when going to that specific register show page. Anyone knows how?
This is what I got so far and it displays, as normal, the id as the last parameter of the URL:
web.php
Route::get('/job/show/{id}', ['as'=>'website.job.show','uses'=>'HomeController#show']);
Controller method
public function show($id){
$job = Job::findOrFail($id);
return view('website.job')->with(compact('job'));
}
Blade page where there is the link to that page
{{$job->name}}
You can overwrite the key name of your Job model:
public function getRouteKeyName()
{
return 'name';
}
Then in your route simply use {job}:
Route::get('/job/show/{job}', ...);
And to call your route:
route('website.job.show', $job);
So your a tag would look like this:
{{ $job->name }}
Inside your controller, you can change the method's signature to receive the Job automatically:
public function show(Job $job)
{
return view('website.job')
->with(compact('job'));
}
For more information, look at customizing the key name under implicit binding: https://laravel.com/docs/5.8/routing#implicit-binding
You need simply to replace the id by the name :
Route::get('/job/show/{name}', ['as'=>'website.job.show','uses'=>'HomeController#show']);
In the controller action:
public function show($name){
//Make sure to replace the 'name' string with the column name in your DB
$job = Job::where('name', $name)->first();
return view('website.job')->with(compact('job'));
}
Finally in the blade page :
{{$job->name}}
2 options:
1) one is like #zakaria-acharki wrote in his comment, by the name of the job and search by the name for fetching the data
2) the second is to do it like here in stackoverflow
to build the url with the id/name
in this way you will make sure to fetch and show the relevant job object by the unique ID
the route:
Route::get('/job/show/{id}/{name}', ['as'=>'website.job.show','uses'=>'HomeController#show']);
in the controller, update the check if the name is equal to the job name (in case it was changed) to prevent duplicate pages url's
public function show($id, $name){
$job = Job::findOrFail($id);
// check here if( $job->name != $name ) {
// redirect 301 to url with the new name
// }
return view('website.job')->with(compact('job'));
}
in the blade.php :
{{$job->name}}
in my controller in my show function in laravel i want the get the id that shows in browser show when i browse it it shows like this
http://localhost:8000/admin/invoices/1
i want to get that "1" and use it in show controller like below
public function show(Invoice $invoice)
{
$clients = Invoice::with('user','products')->get();
$invoice_id = 1;
$invoices = Invoice::with('products')->where('id', '=', $invoice_id)->firstOrFail();
return view('admin.invoices.show', compact('invoice','invoices'),compact('clients'));
}
and put it instead of $invoice_id so when every my client visit this page only sees the related invoice products . thanks you for help
If you're actually getting an instance of Invoice passed to your show method then it likely means you have Route-Model Binding set up for your project. Laravel is looking at the defined route and working out that the ID part (1) should map to an instance of Invoice and is doing the work to grab the record from the database for you.
The Invoice object passed through should refer to an item in your database with the ID of 1, so to get the ID that was mapped in the route you can simply just do:
public function show(Invoice $invoice)
{
echo $invoice->id; // This should be 1
Laravel supports route model binding out of the box these days, but in earlier versions you had to set it up in app/Providers/RouteServiceProvider.php. If you don't want it, try replacing your show method signature with this:
public function show($id)
{
echo $id; // Should be 1
By removing the type-hint you're simply expecting the value that was given in the route parameter and Laravel won't try to resolve it out of the database for you.
Simple way you may try this.
//Define query string in route
Route::get('admin/invoice/{id}','ControllerName#show')
//Get `id` in show function
public function show(Invoice $invoice,$id)
{
$invoice_id = $id;
}
Try using $invoiceId
public function show(Invoice $invoice, $invoiceId)
{
$clients = Invoice::with('user','products')->get();
$invoices = Invoice::with('products')->findOrFail($invoiceId);
return view('admin.invoices.show', compact('invoice','invoices'),compact('clients'));
}
do this if you want to get the url segment in controller.
$invoice_id = request()->segment(3);
if you want this in view
{{ Request::segment(3) }}
Goodluck!
Usually happens when giving a route name different from the controller name
Example:
Route::resource('xyzs', 'AbcController');
Expected:
Route::resource('abcs', 'AbcController');
I need a little help and I can’t find an answer. I would like to replicate a row from one data table to another. My code is:
public function getClone($id) {
$item = Post::find($id);
$clone = $item->replicate();
unset($clone['name'],$clone['price']);
$data = json_decode($clone, true);
Order::create($data);
$orders = Order::orderBy('price', 'asc')->paginate(5);
return redirect ('/orders')->with('success', 'Success');
}
and i got an error :
"Missing argument 1 for
App\Http\Controllers\OrdersController::getClone()"
.
I have two models: Post and Order. After trying to walk around and write something like this:
public function getClone(Post $id) {
...
}
I got another error
Method replicate does not exist.
Where‘s my mistake? What wrong have i done? Maybe i should use another function? Do i need any additional file or code snippet used for json_decode ?
First of all, make sure your controller gets the $id parameter - you can read more about how routing works in Laravel here: https://laravel.com/docs/5.4/routing
Route::get('getClone/{id}','YourController#getClone');
Then, call the URL that contains the ID, e.g.:
localhost:8000/getClone/5
If you want to create an Order object based on a Post object, the following code will do the trick:
public function getClone($id) {
// find post with given ID
$post = Post::findOrFail($id);
// get all Post attributes
$data = $post->attributesToArray();
// remove name and price attributes
$data = array_except($data, ['name', 'price']);
// create new Order based on Post's data
$order = Order::create($data);
return redirect ('/orders')->with('success', 'Success');
}
By writing
public function getClone(Post $id)
you are telling the script that this function needs a variable $id from class Post, so you can rewrite this code like this :
public function getClone(){
$id = new Post;
}
However, in your case this does not make any sence, because you need and integer, from which you can find the required model.
To make things correct, you should look at your routes, because the url that executes this function is not correct, for example, if you have defined a route like this :
Route::get('getClone/{id}','YourController#getClone');
then the Url you are looking for is something like this :
localhost:8000/getClone/5
So that "5" is the actual ID of the post, and if its correct, then Post::find($id) will return the post and you will be able to replicate it, if not, it will return null and you will not be able to do so.
$item = Post::find($id);
if(!$item){
abort(404)
}
Using this will make a 404 page not found error, meaning that the ID is incorrect.
I am learning Laravel, working on 5.22. I am trying to save two records into two tables but only commit the changes if there is success on both fronts, else I want it to fail and rollback.
My Controller code for the save is:
public function store(Request $request)
{
$all = $request->all();
// we need to fill in who is the creator of this new user,
$all['creator_user_id'] = Auth::user()->id;
// Commit both updates or fail and rollback
DB::transaction(function ($all) {
$client = Client::create($all);
$orgClient['organisation_id'] = $client->organisation_id;
$orgClient['client_id'] = $client->client_id;
OrganisationClient::create($orgClient);
});
return redirect()
->route('client.index')
->withMessage([
'type' => 'success',
'value' => 'Client <strong>' . $all->client_name . '</strong> successfully created.']);
}
This fails with the error:
Type error: Argument 1 passed to Illuminate\Database\Eloquent\Model::create() must be of the type array, object given, called in /home/vagrant/Code/simply-invoice/app/Http/Controllers/ClientController.php on line 80
My problem seems to be passing $all to the closure. If I remove $all from the closure parameter, then I get undefined variable all. How do I do this? Thanks!
You are setting $all as the callback parameter instead of useing it. The transaction callback is receiving an instance of Illuminate\Database\Connection as a parameter at the moment.
In order to get the actual variable you want you have to change your callback to this:
// ....
DB::transaction(function () use($all) {
// ...