I am trying to generate slug in my URL instead of id. But I am getting this error message on my laravel window when I click on "Edit"----
"Attempt to read property "slug" on null"
in my web.php--
Route::get('/edit-client/{slug}', [App\Http\Controllers\backend\ClientController::class, 'EditClient'])->name('EditClient');
Route::post('/update-client/{slug}', [App\Http\Controllers\backend\ClientController::class, 'UpdateClient'])->name('UpdateClient');
in my model "OurClient.php" --
class OurClient extends Model{
use HasFactory;
protected $guarded = [];
public function getRouteKeyName()
{
return 'slug';
}
} in my Controller --
public function editClient($slug)
{
$clients = OurClient::find($slug);
return view('backend.clients.edit',compact('clients'));
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function updateClient(Request $request, $slug)
{
OurClient::find($slug)->update([
'clientName' => $request->clientName,
'slug' => Str::slug($request->clientName),
'companyName' =>$request->companyName,
'description' => $request->description,
'designation' => $request->designation,
]);
return Redirect()->back();
}
in my index.blade.php--
<a href="{{ route('EditClient',['slug' => $client->slug]) }}" type="button">Edit</a>
in my edit.blade.php---
<form action="{{ route('UpdateClient',$clients->slug) }}" method="POST"
enctype="multipart/form-data">
@csrf
@method('patch')
<input type="hidden" name="old_image" value="{{ $clients->photo }}">
<div >
...
</div>
<button type="submit">Update Client</button>
</form>
CodePudding user response:
Instead of OurClient::find($slug)
try using OurClient::where('slug',$slug)->first()