Reputation: 81
I have problem with laravel framework where i have two parameters in web route and exact value to find something in my database. When i remove one character, there is error.
Route is:
Route::get('/serije/prikaz/{id}/{naziv}', 'SerijeController@prikaz')->where(['id' => '[0-9]+', 'naziv' => '^[a-z0-9]+(?:-[a-z0-9]+)*$']);
Controller is:
public function prikaz($id, $naziv)
{
$serija = DB::table('serije')
->where(
[
['id', '=', $id],
['slug', '=', $naziv],
]
)
->first();
return view('serije.prikaz', ['serija' => $serija,);
}
So my url is like: http://localhost/serije/prikaz/418/elite
ID=418 slug=elite
That is in database, when i remove only one character, like http://localhost/serije/prikaz/418/elit
There is error
ErrorException
Trying to get property 'naziv' of non-object
http://localhost/serije/prikaz/418/elit
How can i create custom error message like "There is no data for that", or "You make wrong url".
Thanks.
Upvotes: 1
Views: 199
Reputation: 198
Laravel Parameter Validation Docs
Import Class:
use Illuminate\Support\Facades\Validator;
Within Function:
$validator = Validator::make($request->all(), [
'id' => 'required',
'naviz' => 'required'
]);
if($validator->fails()) {
$errors = $validator->errors();
return response()->json(['status' => 'error', 'data' => null, 'message' => $errors], 422);
}
Upvotes: 1
Reputation: 3085
You could add some messaging to your controller:
public function prikaz($id, $naziv)
{
$serija = DB::table('serije')
->where(
[
['id', '=', $id],
['slug', '=', $naziv],
]
)
->first();
$message = $serija ? '': 'There is no data for that';
return view('serije.prikaz', compact('serija', 'message'));
}
Then check to make sure $serija
is not null in your view and display the message if it is.
Upvotes: 1