Laravel Closure Request - laravel

Assalamualaikum guys, i have some problems with my code. i tried to make search by using request parameters on laravel. and here is my code views.
$maintenance->with([
'user_post' => function($query, Request $request){
if($request->has('searchBy') && $request->has('searchQuery'))
{
$parse_query = explode('.',$request->query('searchBy'));
$is_user = $parse_query[0] == 'user_post'? true : false;
if($is_user)
{
$query->where($parse_query[1],'LIKE','%'.$request->query('searchQuery').'%');
}
}
},
'dt_project'
]);
when i tried to execute on browser, it return
1/1) ErrorException
Undefined variable: request
what should i do? thanks to the moon and back. hehehe

try this, change your line 2 to:
'user_post' => function($query) use($request){
explanation:
Request $request can only be used in controller functions like:
public function store(Request $request)
{
//code here
}
in order to pass the $request parameter inside another function, use use (this is also known as variable inheriting):
public function store(Request $request)
{
$user= User::with(['roles' => function($query) use($request){
^^^
$query->where('roles.id', $request['role_id'])->first();
}])->get();
}

Related

How to remove or unfriend through API

This is database structure
This is API
Route::post('/friend', 'FriendController#index');
Route::post('/removerequest/{id}', 'FriendController#removerequest');
This is controller code which into friend request method and remove method, but error in remove friend method..
public function index(Request $request) {
$sender = Friend::where('sender_id', $request->sender_id)->where('receiver_id',$request->receiver_id)->first();
if(empty($sender)){
Friend::create(['sender_id'=>$request->sender_id,'receiver_id'=>$request->receiver_id, 'approved'=>'pending']);
$response = ['message'=>'Friend Request has been sent','status'=>200];
return response()->json($response);
}else{
$response = ['message'=>'Request has been sent already','status'=>200];
return response()->json($response);
}
}
public function removerequest($id){
$friends = Friend::all()
->where('receiver_id')
->where('sender_id')
->approved('accept')
->delete();
}
Error is
BadMethodCallException: Method Illuminate\Database\Eloquent\Collection::approved does not exist. in file /home/ynvih0l26evc/public_html/vendor/laravel/framework/src/Illuminate/Support/Traits/Macroable.php on line 104
enter code here
Update your Route to
Route::delete('/removerequest/{id}', 'FriendController#removerequest');
//change
->approve('approved', 'accept')
to
->where('approved', 'accept')
Update your controller method to
public function removerequest($id){
$friends = Friend::Find($id)->delete(); //see update here
//->where('receiver_id')
//->where('sender_id')
//->where('approved', 'accept')
//->delete();
}
OR
public function removerequest($id){
Friend::where( ['id' => $id, 'approved' => 'accept'])->delete();
}

can't store when using [IF] in eloquent din't work

I need to Store when have data in [Booking] but din't store anything to [scan]
public function store(Request $request, $id){
$event = event::findOrFail($id);
$booking = booking::where('student_id',Auth::user()->student_id)
->where('name',Auth::user()->name)
->where('event_id',$event->id);
if($booking!=NULL){
$requestData = $request->all();
scan::create($requestData);
return redirect('event/' . $event->id .'/scan');
return view('event.scan', compact('event','scan','booking'));
}else{
return redirect('event/' . $event->id .'/scan');
}
}
but when using $booking==null
it store anything can't check in booking
Your query is incomplete. It lacks of any final query method like get(), first() or exists()
Also you have two return statements inside the if block. Only the first will be executed, the second one will be ignored.
The correct code should be like this:
public function store(Request $request, $id){
$event = event::findOrFail($id);
$booking = booking::where('student_id',Auth::user()->student_id)
->where('name',Auth::user()->name)
->where('event_id',$event->id)
->get(); // look this line
if($booking!=NULL){
$requestData = $request->all();
scan::create($requestData);
return redirect('event/' . $event->id .'/scan'); // I think this should not be here, right?
return view('event.scan', compact('event','scan','booking')); // this is being ignored.
}else{
return redirect('event/' . $event->id .'/scan');
}
}
you can update your method like so. its much clearer and readable (i think anyway).
public function store(Request $request, $id)
{
//use first to get a booking or use get() for collections of booking
$booking = Booking::where('student_id', auth()->user()->student_id)
->where('event_id', $id)
-first();
if (is_null($booking)) {
return redirect('event/' . $id . '/scan');
}
return view('event.scan', [
'event' => Event::findOrFail($id),
'scan' => Scan::create($request->all()),
'booking' => $booking
]);
}
Hope this helps
Cheers

Laravel - request validation

I extedned request class to create my own valdiation rules. In that class I added my custom validation function. In function I check if tags are pass regEx and I would like to filter tags to remove tags shorter then 2 characters.
And later keep in request only tags that passed validation.
public function createPost(PostRequest $request)
{
dd($request->all()); //In this place I would like to keep only tags passed through validation not all tags recived in request
}
Is it possibile to do it? How to set it in Request class?
'tags' => [
'nullable',
'string',
function ($attribute, $value, $fail){
$tagsArray = explode(',', $value);
if(count($tagsArray) > 5) {
$fail(__('place.tags_max_limit'));
}
$tagsFiltered = [];
foreach ($tagsArray as $tag){
$tag = trim($tag);
if(preg_match('/^[a-zA-Z]+$/',$tag)){
$tagsFiltered[] = $tag;
};
}
return $tagsFiltered;
}
],
EDIT:
I think we miss understanding. I would like to after validation have only tags that returned in variable $tagsFiltered; Not the same as recived in input.
You have to create this custom regex rule and use it into rules() function.
Like so:
public function rules()
{
return [
'tag' => 'regex:/[^]{2,}/'
];
}
public function createPost(PostRequest $request)
{
$request->validated();
}
And then just call it via validated() function wherever you want.
first define validation rule with this command:
php artisan make:rule TagsFilter
navigate to TagsFilter rule file and define your filter on passes method:
public function passes($attribute, $value)
{
$tagsArray = explode(',', $value);
$tagsFiltered = [];
foreach ($tagsArray as $tag){
$tag = trim($tag);
if(preg_match('/^[a-zA-Z]+$/',$tag)){
$tagsFiltered[] = $tag;
};
}
return count($tagsArray) > 5 && count($tagsFiltered) > 0;
}
then include your rule in your validation on controller:
$request->validate([
'tags' => ['required', new TagsFilter],
]);

how to use $request->all() on controller and blade view in laravel 5.5

in Controller
public function index(Request $request)
{
$search_cons = $request->all();
$search_con = $search_cons->name; //error place
return $search_cons.$search_con;
}
->name this place has the error
Trying to get property of non-object
Or in blade.view
<p>{{$search_cons->name}}</p> has the error
Trying to get property of non-object
But if I use
$search_cons=$request->input('name');
on controller
the blade view
<p>{{$search_cons}}</p> will work ok!
I want the $search=request->all() so I can freely use $search->name on my blade view
How can I fix the question?
PS: I tried $resquest('name') still not to work
Request::all() ->tell me the
When you do $request->all() it returns all the inputs submitted in array format. So in your case, you can do
$search_cons = $request->all(); // dd($search_cons) so you can see its structure
$search_con = $search_cons['name']; // instead of ->name since it's not an object anymore
And anyway, you can skip the $request->all() thing - you can actually just do this directly:
$request->name.
EDIT:
You can cast the array as an object using (object)
$search_cons = (object) $request->all();
this will still let you use $search_cons->name
$search_cons is an array, not an object:
$search_con = $search_cons['name']
public function index(Request $request)
{
$search_cons = $request->all(); //returns array
$search_con = $search_cons['name']; //error place
return $search_cons.$search_con;
}
Or you can do like this
request()->name //request() isa global helper function
Try
In Controller
public function index(Request $request)
{
$search = $request->all();
return ['search' => $search];
}
In Blade
<p>Name : {{$search['name'] ? $search['name'] : ''}} </p>

Passing route parameter to controller Laravel 5

I'm trying to pass a route parameter to controller, but I get this error : Argument 2 passed to App\Http\Controllers\JurnalController::store() must be an instance of App\Http\Requests\JurnalRequest, none given
Below are the codes ..
Route :
Route::get('/edisi/{id}', 'JurnalController#store');
Controller :
public function store($id, JurnalRequest $request) {
$input = $request->all();
//Input PDF
if ($request->hasFile('file')) {
$input['file'] = $this->uploadPDF($request);
}
$jurnal = Edisi::findOrFail($id)->jurnal()->create($input);
return redirect('jurnal');
}
So my question is how to pass the route parameter properly ? Thank you
new routes :
Route::get('/', function () {
return view('pages/home');
});
Route::group(['middleware' => ['web']], function () {
Route::get('edisi', 'EdisiController#index');
Route::get('edisi/create', 'EdisiController#create');
Route::get('edisi/{edisi}', 'EdisiController#show');
Route::post('edisi', 'EdisiController#store');
Route::get('edisi/{edisi]', 'EdisiController#edit');
Route::patch('edisi/{edisi}', 'EdisiController#update');
Route::delete('edisi/{edisi}', 'EdisiController#destroy');
});
Route::get('/edisi/{id}', 'JurnalController#storejurnal');
Route::group(['middleware' => ['web']], function () {
Route::get('jurnal', 'JurnalController#index');
Route::get('jurnal/create', 'JurnalController#create');
Route::get('jurnal/{jurnal}', 'JurnalController#show');
Route::post('jurnal', 'JurnalController#storejurnal');
Route::get('jurnal/{jurnal}/edit', 'JurnalController#edit');
Route::patch('jurnal/{jurnal}', 'JurnalController#update');
Route::delete('jurnal/{jurnal}', 'JurnalController#destroy');
});
new storejurnal method :
public function storejurnal(JurnalRequest $request, $id) {
$input = $request->all();
//Input PDF
if ($request->hasFile('file')) {
$input['file'] = $this->uploadPDF($request);
}
//Insert data jurnal
$jurnal = Edisi::findOrFail($id)->jurnal()->create($input);
return redirect('jurnal');
}
When you are using resource controller, the store method does not accept any other argument except the Request instance. Try changing the method name or remove the second argument. store() method be default accepts post requests not get requests. Either put your route on top of the resource controller or change the method name.
Route::get('/edisi/{id}', 'JurnalController#store');
Route::resource('jurnals', 'JurnalController');
I hope this helps.
The correct format is:
public function store(JurnalRequest $request, $id) {
// your code
}
If you receive an argument such as Missing argument 2 as suggested in your comments, it means that either you aren't generating the routes correctly, or the url doesn't include the id segment.

Resources