Laravel Flashcards
How can you use ‘request()->is()’ to check if the current url matches the ‘/home’ route?
@if(request()->is(‘home’))
This is the home route.
@else
This is not the home route.
@endif
How would you apply the ‘active’ class to a navigation link if it matches the ‘/about’ route?
<a href=“/about” class=“{{ request()->is(‘/about’) ? active : ‘’ }}”>About</a>
What does ‘request()->is()’ do in Laravel?
It is a method used to check if the current request matches a given pattern or route.
What does {id} represent in the route definition /jobs/{id}?
{id} is a route parameter, which can be any value and will be captured and passed to the callback function as an argument.
Explain the purpose of the Arr::first() function in the provided code snippet.
Route::get(‘/jobs/{id}’, function ($id) {
$jobs = [
[
‘id’ => 1,
‘title’ => ‘Director’,
‘salary’ => 50000
],
[
‘id’ => 2,
‘title’ => ‘Programmer’,
‘salary’ => 10000
],
[
‘id’=> 3,
‘title’ => ‘Teacher’,
‘salary’ => 40000
]
];
$job = Arr::first($jobs, fn($job) => $job['id'] == $id); return view('job', ['job' => $job]); });
Arr::first() is a helper function provided by Laravel for working with arrays. It returns the first element of the array that passes a given truth test. In this case, the truth test is defined as an anonymous function that checks if the ‘id’ key of a job matches the $id parameter passed to the route.
How do you delete a row from table “Post” with id 1 from a database table using Laravel Eloquent?
$post = Post::find(1);
$post->delete();
What does Post::find(1) do in Laravel Eloquent?
Post::find(1) retrieves the post with the primary key value of 1 from the posts table. It returns a model instance representing that post.