I have read as many posts as possible, but none of them can solve my problem.
The route:
Route::model('user', 'User');
Route::group(array('prefix' => 'admin'), function() {
Route::get('users/force-delete/{user}', array(
'as' => 'admin-users-force-delete',
'uses' => 'AdminController#handleUserForceDelete'
));
});
The html:
<li>Force Delete</li>
The handler:
public function handleUserForceDelete(User $user)
{
$username_tmp = $user->username;
$message = 'Success! User ' . $username_tmp . ' has been deleted.';
if($user->trashed())
{
$user->forceDelete();
return Redirect::action('AdminController#showUsers')->with('message', $message);
} else {
return Redirect::action('AdminController#showUsers')->with('message', 'User deletion error! Please try again!');
}
}
I tried to put delete and force-delete at the same handler, and the delete action took place but force-delete generated NotFoundHttpException. So I guess the problem is from the force-delete action??
I solved it!
For anyone with the same trouble, soft deleted user(or anything) will not generate an instance passed to the handler (or closure). Therefore, for this case I manually create an instance.
So instead of using this:
//will not handle soft deleted model.
Route::model('user', 'User');
Use this:
Route::bind('user', function($value, $route)
{
return User::withTrashed()->where('id', '=', $value)->first();
});
Related
So I have an API route
Route::group(['prefix' => 'users'], function() {
Route::group(['prefix' => 'seminar'], function() {
Route::get('/{employee_number}', [UserProfileController::class, 'getSeminar']);
Route::post('/{user}', [UserProfileController::class, 'createSeminar']);
Route::put('/{seminar}', [UserProfileController::class, 'updateSeminar']);
Route::delete ('/{seminar}', [UserProfileController::class, 'deleteSeminar']);
});
});
And a controller
public function createSeminar(User $user, Request $request)
{
return $this->allowIfRecordOwner($user->id, function() use ($user, $request) {
$seminar = Seminar::create([
"user_id" => $user->id,
"dates" => $request->dates,
"name" => $request->name,
"certificate_number" => $request->certificate_number
]);
return response()->json($seminar->toArray(), 200);
});
}
And im using that from my angular app
private saveSeminar(index) {
event.preventDefault();
const seminar = this.userSeminars[index];
if (seminar.id) {
this.updateUserSeminar(index);
} else {
this.storeStudentAddress(index);
}
}
private storeStudentAddress(index) {
this.apiService.create('users/seminar', this.userSeminars[index])
.subscribe(
response => {
this.userSeminars[index].edit = false;
this.userSeminars[index].id = response.id;
this.getUserSeminar(index.employee_number);
this.toastr.success('Seminar Successfully saved', 'Success');
});
}
I have done php artisan route:list and found my router here
And I have now been staring at the error for over three hours and can't see why I'm getting the error. Any help would be wonderful
Your API endpoint in Laravel doesn't look like it lines up with your API endpoint in your JavaScript.
You need to hit this endpoint in order to create a seminar: api/users/seminar/{user}, where {user} is the user's ID.
Your line here: this.apiService.create('users/seminar', this.userSeminars[index]) looks like it's instead hitting api/users/seminar, without the user's ID appended to the end.
You just need to change it to this.apiService.create('users/seminar/' + USER_ID, ... where USER_ID is whatever variable you're using to store the user's ID, or alternatively a method which returns it.
I am getting this error (Route [companies.show] not defined.) and I don't know what to do.
Actually I am updating the data in CompaniesController and data is updating but the route is not working
Here is the code for that:
public function update(Request $request, Company $company){
$companyUpdate = Company::where('id', $company->id)->update(['name'=> $request->input('name'),'description'=> $request->input('description')]);
if($companyUpdate){
return redirect()->route('companies.show', ['company'=> $company->id])
->with('success' , 'Company updated successfully');
}
return back()->withInput();
And My web.php file is as follow `
Route::get('/', function () {
return view('welcome');});
Auth::routes();
Route::get('/home', 'HomeController#index')->name('home');
Route::resource('/company','CompaniesController');
Thanks in advance for helping me
change companies.show to
return redirect()->route('company.show', ['company'=> $company->id])
->with('success' , 'Company updated successfully');
}
companies.show is undefined because you didn't give your route a name.
Route::get('/companies/{id}', 'CompaniesController#showCompanyForID')->name('companies.show');
Create a function called showCompanyForID in your CompaniesController and return the company which has the id requested for in your Request.
use Illuminate\Http\Request;
public function showCompanyForID(Request $request)
{
$id = isset($request->id) ? $request->id : 0;
if ($id) {
// do work here
}
return view('companies.company')->with(compact('var1', 'var2'));
}
You can now redirect to that route:
return redirect()
->route('companies.show')
->with(['company'=> $company->id, 'success' => 'Company updated successfully']);
To see all routes, cd to your project in cmd / Terminal and type: php artisan route:list
As we can read here, we can listen the eloquent events and use it in the AppServiceProvider. It goes like this:
public function boot()
{
User::creating(function ($user) {
Log::create(['message' => 'create method']);
});
User::deleting(function ($user) {
Log::create(['message' => 'delete method']);
});
}
For all my eloquent models, I want to log in the database when it is created and who created it. This would mean that I need to copy paste this snippet 20 times and only change the User::creating part.
Is there a way that I can catch the eloquent events from all models and make something like this:
public function boot()
{
AllModels::creating(function ($model) { // <--- something like this here?
Log::create([
'message' => 'create method',
'model' => get_class($model) // <--- and then get the class name
]);
AllModels::deleting(function ($user) {
/***/
}
});
}
You can try something like this:
$models = ['User', 'Post', 'Comment', ....];
foreach ($models as $model) {
$model::creating(....);
$model::deleting(....);
}
Similar approach worked for me (I used DI instead of facades though).
Another approach I found and bookmarked some time ago:
Event::listen(['eloquent.creating: *'], function() {
....
});
I am using Hashid to hide the id of a resource in Laravel 5.
Here is the route bind in the routes file:
Route::bind('schedule', function($value, $route)
{
$hashids = new Hashids\Hashids(env('APP_KEY'),8);
if( isset($hashids->decode($value)[0]) )
{
$id = $hashids->decode($value)[0];
return App\Schedule::findOrFail($id);
}
App::abort(404);
});
And in the model:
public function getRouteKey()
{
$hashids = new \Hashids\Hashids(env('APP_KEY'),8);
return $hashids->encode($this->getKey());
}
Now this works fine the resource displays perfectly and the ID is hashed.
BUT when I go to my create route, it 404's - if I remove App::abort(404) the create route goes to the resource 'show' view without any data...
Here is the Create route:
Route::get('schedules/create', [
'uses' => 'SchedulesController#create',
'as' => 'schedules.create'
]);
The Show route:
Route::get('schedules/{schedule}', [
'uses' => 'Schedules Controller#show',
'as' => 'schedules.show'
]);
I am also binding the model to the route:
Route::model('schedule', 'App\Schedule');
Any ideas why my create view is not showing correctly? The index view displays fine.
Turns out to solve this, I had to rearrange my crud routes.
Create needed to come before the Show route...
There's a package that does exactly what you want to do: https://github.com/balping/laravel-hashslug
Also note, that it's not a good idea to use APP_KEY as salt because it can be exposed.
Using the above package all you need to do is add a trait and typehint in controller:
class Post extends Model {
use HasHashSlug;
}
// routes/web.php
Route::resource('/posts', 'PostController');
// app/Http/Controllers/PostController.php
public function show(Post $post){
return view('post.show', compact('post'));
}
In Laravel, I want to have two different routes that have the same URL, but that runs a different controller based upon the datatype of the input. For example:
Route::get('/name/{id}/', function($id)
{
return 'id is an int:' . $id;
})->where('id', '[0-9]+');
Route::get('/name/{id}/', function($id)
{
return 'id is a string: ' . $id;
})->where('id', '[a-z]+');
This doesn't seem to work, though - the second route seems to overwrite the first completely, so the app wouldn't support ids that were integers. How do you actually accomplish this in Laravel without doing the checking manually inside the route?
Thanks
To not overwrite the first route, use different parameter name
Route::get('/name/{id}/', function($id)
{
return 'id is an int:' . $id;
})->where('id', '[0-9]+');
Route::get('/name/{stringId}/', function($id)
{
return 'id is a string: ' . $id;
})->where('stringId', '[a-z]+');
I think you can seperate this two routing mechanish from each other.
Route::get('user/{id}', function($id)
{
//
})
->where('id', '[A-Za-z]+');
Route::get('user/{id}', function($id)
{
})
->where('id', '[0-9]+');
This code sample from Laravel site. If you want seperate logic more than that you can use filter.
Filter sample:
Route::filter('foo', function()
{
if (Route::input('id') == 1)
{
//
}
});
I hope i can help you.