BrianA

BrianA

Member Since 3 Months Ago

Experience Points
840
Total
Experience

4,160 experience to go until the next level!

In case you were wondering, you earn Laracasts experience when you:

  • Complete a lesson — 100pts
  • Create a forum thread — 50pts
  • Reply to a thread — 10pts
  • Leave a reply that is liked — 50pts
  • Receive a "Best Reply" award — 500pts
Lessons Completed
0
Lessons
Completed
Best Reply Awards
0
Best Reply
Awards
  • start your engines Created with Sketch.

    Start Your Engines

    Earned once you have completed your first Laracasts lesson.

  • first-thousand Created with Sketch.

    First Thousand

    Earned once you have earned your first 1000 experience points.

  • 1-year Created with Sketch.

    One Year Member

    Earned when you have been with Laracasts for 1 year.

  • 2-years Created with Sketch.

    Two Year Member

    Earned when you have been with Laracasts for 2 years.

  • 3-years Created with Sketch.

    Three Year Member

    Earned when you have been with Laracasts for 3 years.

  • 4-years Created with Sketch.

    Four Year Member

    Earned when you have been with Laracasts for 4 years.

  • 5-years Created with Sketch.

    Five Year Member

    Earned when you have been with Laracasts for 5 years.

  • school-in-session Created with Sketch.

    School In Session

    Earned when at least one Laracasts series has been fully completed.

  • welcome-newcomer Created with Sketch.

    Welcome To The Community

    Earned after your first post on the Laracasts forum.

  • full-time-student Created with Sketch.

    Full Time Learner

    Earned once 100 Laracasts lessons have been completed.

  • pay-it-forward Created with Sketch.

    Pay It Forward

    Earned once you receive your first "Best Reply" award on the Laracasts forum.

  • subscriber Created with Sketch.

    Subscriber

    Earned if you are a paying Laracasts subscriber.

  • lifer Created with Sketch.

    Lifer

    Earned if you have a lifetime subscription to Laracasts.

  • evangelist Created with Sketch.

    Laracasts Evangelist

    Earned if you share a link to Laracasts on social media. Please email [email protected] with your username and post URL to be awarded this badge.

  • chatty-cathy Created with Sketch.

    Chatty Cathy

    Earned once you have achieved 500 forum replies.

  • lara-veteran Created with Sketch.

    Laracasts Veteran

    Earned once your experience points passes 100,000.

  • 10k-strong Created with Sketch.

    Ten Thousand Strong

    Earned once your experience points hits 10,000.

  • lara-master Created with Sketch.

    Laracasts Master

    Earned once 1000 Laracasts lessons have been completed.

  • laracasts-tutor Created with Sketch.

    Laracasts Tutor

    Earned once your "Best Reply" award count is 100 or more.

  • laracasts-sensei Created with Sketch.

    Laracasts Sensei

    Earned once your experience points passes 1 million.

  • top-50 Created with Sketch.

    Top 50

    Earned once your experience points ranks in the top 50 of all Laracasts users.

Level 1
840 XP
Oct
21
1 month ago
Activity icon

Replied to Remove Accessors From Object In Controller

Thank you @sinnbeck. I will look into the second point (resource/json collections once I finish working on another integral part of the project.

I will have to ask again here if I encounter further difficulties - Thanks for your help :)

Regards

Activity icon

Replied to Remove Accessors From Object In Controller

Thanks @martinbean!

I will consider using other features instead. I think I am understanding the issues related to my implementation. I

Thanks again, Brian

Oct
16
1 month ago
Activity icon

Replied to Remove Accessors From Object In Controller

@sinnbeck

Hi,

This looks interesting; how is it used exactly please? If you do not include the append in the model, and just include the functions getHas...Attribute, would the has_devices attributes still be available to use in my controllers?

Thanks

Activity icon

Replied to Remove Accessors From Object In Controller

@sinnbeck

Sometimes I am appending attributes to easily make decisions in blade views (for example if the organisations of which the logged in user is a member of, ha (the organisation has not the user) ble tag devices - thus has_ble_tag = true, show a menu/buttons).

On other occasions I am adding attributes like the number of devices each organisation has. Since I am using server side processing datatables (using ajax), I could not get the number of devices for each organisation (row in the table) as I used to do with regular tables where I had a foreach loop.

Activity icon

Replied to Remove Accessors From Object In Controller

Hi @nakov

Since I only needed the IDs of the organisations which match that particular search, what you suggested worked well :)

Thank you :)

Activity icon

Started a new Conversation Remove Accessors From Object In Controller

Hi,

In my BleTag model, I added the following accessors/mutators:

// Add custom attributes
    protected $appends = [
        'has_iot_park',
        'has_ble_tag',
        'has_smart_timer',
    ];

and

 public function getHasIotParkAttribute()
    {
        // Check if the organisation has any iot park devices
        $iotParkDevice = IotParkDevice::where('organisation_id', '=', $this->id)->first(); // At least one
        if ($iotParkDevice) {
            $has_iot_park = true;   // Organisation has IoT Park devices
        } else {
            $has_iot_park = false;
        }
        return $has_iot_park;
    }

etc ...

Now in one of my controllers, I need to get the id of each organisation.

If I do the following:

$organisations = Organisation::where('name', 'LIKE', '%' . $searchOrgName . '%')->get();

This also returns 'has_iot_park', 'has_ble_tag', 'has_smart_timer', apart from the id.. How can I remve these from my object to get an array of ids only please?

Thanks , Brian

Oct
14
1 month ago
Activity icon

Replied to Laravel Where Clause To Search In Columns Which Are Not In The Database

Thanks @bugsysha and @michaloravec

In my organisation model I already have the following:

// An organisation can have multiple devices
    public function devices()
    {
        return $this->hasMany(Device::class, 'organisation_id');
    }
Activity icon

Replied to Laravel Where Clause To Search In Columns Which Are Not In The Database

Hi @bugsysha :)

I tried the following:

$organisations = Organisation::query();
$organisations = $organisations->doesntHave('devices');
$organisations = $organisations->get();

return $organisations;

To try and get the organisations which do not own any devices, and got this error now:

[2020-10-14 13:03:32] local.ERROR: Call to undefined method App\Organisation::devices() {"userId":18,"exception":"[object] (BadMethodCallException(code: 0): Call to undefined method App\Organisation::devices() at C:\xampp\htdocs\iot_eol\vendor\laravel\framework\src\Illuminate\Support\Traits\ForwardsCalls.php:50)
[stacktrace]

Is there something else I must define?

Thanks

Activity icon

Replied to Laravel Where Clause To Search In Columns Which Are Not In The Database

Hi @saurav77 ,

It seems as if the same thing occurs.

This is the error I got:

[2020-10-14 12:48:20] local.ERROR: Property [iot_park_count] does not exist on the Eloquent builder instance. ...

Thanks

Activity icon

Started a new Conversation Laravel Where Clause To Search In Columns Which Are Not In The Database

Hello all,

I have a table organisations with a number of columns, namely id, name, created_at and updated_at.

In my Organisation model, I added a custom attribute by adding the following code in the model:

// Add custom attributes
    protected $appends = [
        'device_count',
    ];

and:

public function getDeviceCountAttribute()
    {
        // Count organisation's devices
        $device_count = Device::where('organisation_id', '=', $this->id)->count();
        return $device_count;
    }

In my controller, I am trying to search (using the where clause) by the device_count attribute, but I'm getting an error since this is not a real column in my database table.

  • This is how I'm searching:
$organisations = Organisation::query();
$organisations = $organisations->where('device_count', '=', 0);
$organisations = $organisations->get();
  • This is the error:
[2020-10-14 12:29:27] local.ERROR: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'device_count' in 'field list'...

Is there an alternative to the where clause in order to search by device_count please?

Activity icon

Awarded Best Reply on Record Loss In Database Table/Data Record Not Being Stored In Databaase Table

Hi @automica,

Thanks for the tips. I agree with you about transactions. After going through some documentation, that's what I found out too. I'll go through the validation part again to ensure that the request data is valid before being saved in the table.

Regards, Brian

Activity icon

Awarded Best Reply on Loading An Image From Public Storage - 403 (Forbidden)

Hi,

I ended up using a controller (ImageController) and protected route (using middleware) to 'return' the image requested by the view, to the view itself.

This is a different approach from the one above, because I then realized that I needed to have my images accessible only for the users requiring them in the view.. I could not place them in a public directory.

Thanks for your suggestions! :)

Activity icon

Replied to Loading An Image From Public Storage - 403 (Forbidden)

Hi,

I ended up using a controller (ImageController) and protected route (using middleware) to 'return' the image requested by the view, to the view itself.

This is a different approach from the one above, because I then realized that I needed to have my images accessible only for the users requiring them in the view.. I could not place them in a public directory.

Thanks for your suggestions! :)

Activity icon

Replied to Loading An Image From Storage In Blade View (Protected)

Hi @sinnbeck

That's what I did and it is working well, as I wanted now. I'm using a controller (the route is protected by middleware) to 'return' the image to the view.

Thanks! :)

Oct
13
1 month ago
Activity icon

Started a new Conversation Loading An Image From Storage In Blade View (Protected)

Hi,

I need to show an image in a Blade view , however, I do not want the images to be public. Only the users who need to see a particular image can have access to it.

This is what I was doing before realizing that the images must not be accessible by anyone if the path is known/guessed:

  • I was storing images (which are uploaded by an admin) in storage/app/public/uploads/iotpark/warranty/

  • The same images were available in public/storage/... (I ran php artisan storage:link)

  • In my Bade view, I was getting and displaying the image using <img src="<?php echo asset("storage/uploads/iotpark/warranty/$currentFile")?>"></img>

I would now like to store my images in storage/uploads/iotpark/warranty/ instead.

  • What is the best way of displaying an image (which is not public) in a Blade view please? I think the ideal would be to pass the specific file from the controller to the blade view if possible.

Note: I have the Image Intervention package installed, so maybe I could use this package for this application/case?

Thanks in advance, Brian

Activity icon

Replied to Loading An Image From Public Storage - 403 (Forbidden)

@laracoft

Thanks for your reply.

  1. I do have the image file 48_00C1D156_1602499479.jpg in storage/app/public/uploads/iotpark/warranty/

  2. When I tried loading https://my-website.com/uploads/iotpark/warranty/ I got a 404, page does not exist

  3. When checking the permissions for the folders/files on the server hosting the web application, all folders and JPG files have Read and Execute/Search permissions enabled for the 'other users', and Write permissions only enabled for the 'owner'

Thanks

Oct
12
1 month ago
Activity icon

Started a new Conversation Loading An Image From Public Storage - 403 (Forbidden)

Hi,

In one of my blade views, I am trying to display an image by doing:

<img src="<?php echo asset("storage/uploads/iotpark/warranty/$currentFile")?>"></img>

The image is stored in my-website.com>public>storage>uploads>iotpark>warranty.

However, when visiting the page on my browser, the image is not loaded and when inspecting in Chrome's console, the following error is shown:

GET https://my-website.com/storage/uploads/iotpark/warranty/48_00C1D156_1602499479.jpg 403 (Forbidden)

I have run php artisan storage:link in my server's command prompt, and the links were created.

  • This worked well locally and I did not have any errors. Only happening online.

What could it be caused by please?

Thanks! Brian

Activity icon

Replied to Laravel Image Intervention Resizing

Hi :)

Thank you for the information and for your recommendations. I will go through them and decide what might be the best for my application.

In my case, I have section where admins can upload photographs of damaged devices which are returned back by the client. These are stored in a folder within the project so that admins can refer to the photographs at any time, or to show them to the clients and explain what might be the cause.

This means that I must find a compromise between image quality and byte size. Damages/features must remain recognizable while minimizing the file byte size (due to the large number of image that might accumulate over time).

Brian

Oct
09
1 month ago
Activity icon

Started a new Conversation Laravel Image Intervention Resizing

Hi,

In one of my blade views of my project, I have an input where the user can upload an image. When storing the image in my project's storage folder (online), I want to resize the image uploaded.

After visiting some forums, I went for the Image intervention package.

This is how I am resizing the image:

use Intervention\Image\Facades\Image;
use Illuminate\Support\Facades\Storage;

Part of the image storing/resizing function:

// Check if an image has been chosen and save to DB
        if($request->hasFile('image')) {
            $image = $request->file('image');
            $path = public_path('../storage/uploads/iotpark/warranty/');
            $filename = $id . '_' . $device->sigfox_transceiver_id . '_' . time() . '.' . $image->getClientOriginalExtension();
            // Image resizing
            $img = Image::make($image->getRealPath());
            $img->resize(500, 500, function ($constraint) {
                $constraint->aspectRatio();
            })->save($path.$filename);
            
            $device->warranty_photo = $filename;
            $device->save();
            $message = 3;
        }

Could someone explain how the resizing function works exactly please?

  • What is the best way to decide what resizing parameters to choose?

  • How does this affect uploaded images of different sizes and ratios?

  • Is there a way to compress the image instead of resizing it?

Thank you in advance for your suggestions :)

Brian

Activity icon

Awarded Best Reply on Laravel - Scripts In @push Directive Not Available In Parent @stack Directive

SOLVED:

After asking in other forums and contacting the author of the HTML layouts I am using for this project, disabling the pjax library and the ajax from the Laravel Blade layout solved the issue.

It was something related to the way different pages are loaded when the user navigates through the web application - Which was defined in the pjax and ajax scripts by the author of the templates being used.

Brian :)

Activity icon

Replied to Laravel - Scripts In @push Directive Not Available In Parent @stack Directive

SOLVED:

After asking in other forums and contacting the author of the HTML layouts I am using for this project, disabling the pjax library and the ajax from the Laravel Blade layout solved the issue.

It was something related to the way different pages are loaded when the user navigates through the web application - Which was defined in the pjax and ajax scripts by the author of the templates being used.

Brian :)

Sep
30
2 months ago
Activity icon

Replied to Laravel - Scripts In @push Directive Not Available In Parent @stack Directive

UPDATE:

After some debugging, I noticed that when clicking on menu href links/a-tags, the URL changes to the respective route URL, however, the page is not refreshed. It seems as if the layout is not loading again and only the 'title', 'page-subtitle', 'page-content' etc... sections are changing.

I am using a template (Basik - Web Application and Admin Template) - Could there be something in the template's scripts that is preventing the entire page from 'refreshing'/reloading?

  • When placing the same href link inside the @section('page-content') ... @endsection - i.e. inside the child blade view instead of the layout's menu, this solved the issue.

  • How can I check that the template is not preventing the following a-tag from acting as a regular href link please?

<div id="aside" class="page-sidenav no-shrink bg-light nav-dropdown fade" aria-hidden="true">
	<div class="sidenav h-100 modal-dialog bg-light">
		<div class="flex scrollable hover">
			<div class="nav-active-text-primary" data-nav>
				<ul class="nav bg">
					<ul class="nav-sub nav-mega">
						<li>
							<a href="/users" class="">
        							<span class="nav-text">View All</span>
       							</a>
      						</li>
					</ul>

Thanks, Brian

Activity icon

Replied to Laravel - Scripts In @push Directive Not Available In Parent @stack Directive

@sinnbeck Was about to tell you that I solved the error - Thanks! :)

Sep
28
2 months ago
Activity icon

Replied to Laravel - Scripts In @push Directive Not Available In Parent @stack Directive

Hello @sinnbeck

Thanks for pointing that out for me.

I have just tried changing <script src="../../../assets/js/theme.js"></script> to <script src="{{assets('assets/js/theme.js')}}"></script> but got the following 500 error:

[2020-09-28 14:19:41] local.ERROR: Call to undefined function assets() (View: C:\xampp\htdocs\...
  • What could be causing this error please? Should the function assets() be defined somewhere in my project?

Thanks!

Activity icon

Replied to Laravel - Scripts In @push Directive Not Available In Parent @stack Directive

Hi @s4muel unfortunately that did not change anything, however, hitting the browser's refresh button/F5 always causes the JS to be included in the layout and in turn the table to be displayed correctly, as required.

What could be causing the page-content section to be included and the custom-scripts not?

Thanks, Brian

Activity icon

Replied to Record Loss In Database Table/Data Record Not Being Stored In Databaase Table

Hi @snapey,

Sorry for the late reply, and thanks for your message!

I would have to check again to be sure, however, when testing the project and inserting a duplicate entry, a 500 error, and a 'Could Not Save Device' error were returned, indicating that the device could not be saved. In fact, the device could not be added again to the database from the user's application and a warning message was displayed.

Thanks again, Brian

Activity icon

Started a new Conversation Laravel - Scripts In @push Directive Not Available In Parent @stack Directive

Hi :)

I have a question about the @push and @stack directives.

My project has a parent view/layout named admin.blade.php and various child views, including one named datatable.blade.php. The second file is used to display a datatable with all users, and this datatable requires some JS script which is unique for this particular file (datatable.blade.php) and does not have to be included in other child blade view files.

  • In my datatable.blade.php (the child view), I have the following:
@section('page-content')

... Here I have my page contect (the table which shows all the users registered, and other information) ...	
   	
@endsection

{{-- @push directive in the child view, pushing content to the parent/master @stack directive --}}
@push('custom-scripts')
	<script>

	... My custom JS script here (required by the datatable in the ```page-content``` section above ... 
       
    	</script>
@endpush
  • In my parent view/layout admin.blade.php, I included the following @stack directive:
...
	<!-- theme -->
        <script src="../../../assets/js/theme.js"></script>
        <script src="../../../assets/js/utils.js"></script>
        
	<script src="../../../libs/parsleyjs/dist/parsley.min.js"></script>
        
	{{-- Datatables - Always here as these are common for all datatables, then just add JS script in page-content 							section --}}
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
        <script type="text/javascript" src="https://cdn.datatables.net/v/dt/dt-1.10.22/datatables.min.js"></script>

        @stack('custom-scripts')
        
	 <!-- endbuild -->
    </body>
</html>
  • However, when visiting the dashboard, my custom script code in not included in my layout admin.blade.php (parent), leading to missing JS code required by the datatable, which in turn causes the datatable to be displayed incorrectly.

  • Upon refreshing the page from my browser, this custom-script JS code script loads as expected, and the code in included in the layout admin.blade.php (parent) - This was also confirmed from the browser's console.

  1. Could it be that the original layout/parent without the custom-script is being cached, which causes the @stack directive to not get the required JS script?

  2. In this case, how is the content loaded, and the JS code in the @push directive not?

Any siggestions would be greatly appreciated - Thanks! :)

Sep
22
2 months ago
Activity icon

Replied to Record Loss In Database Table/Data Record Not Being Stored In Databaase Table

Hi @automica,

Thanks for the tips. I agree with you about transactions. After going through some documentation, that's what I found out too. I'll go through the validation part again to ensure that the request data is valid before being saved in the table.

Regards, Brian

Sep
18
2 months ago
Activity icon

Started a new Conversation Record Loss In Database Table/Data Record Not Being Stored In Databaase Table

Hi,

I am currently storing records (data parameters belonging to different devices) in a phpMyAdmin database (devices table). A piece of equipment and an application is being used to obtain the data from each device, and then storing it into the database table via a post request with all the parameters, using an API route.

The API route, defined in the routes file api.php, being used to store the data/add a device to the devices table is the following:

Route::post('/devices/add','Api\[email protected]');

The store method, found in the DeviceController is as follows:

public function store(Request $request)
    {
        $validatedData = Validator::make($request->all(), [
            'qr' => 'required|unique:App\Device,qr',
            'fw' => 'required|numeric',

            ... (more data) ...

            'comments' => 'required',
        ], $messages = ['required' => 'Missing :attribute', 
                        'boolean' => 'Not Boolean :attribute', 
                        'numeric' => 'NaN :attribute',
                        'integer' => 'NaN :attribute',
                        'unique' => 'Duplicate :attribute',
                        'between' => 'Invalid :attribute',
                        'in' => 'Failed :attribute']);

        if ($validatedData->fails()) {
            return response()->json([
                'message' => $validatedData->errors()->first()
            ], 400);

        } else {
            // QR code format validation
            $key   = $request->qr;
            $regex = '$[A-Z]{4}[0-9]{9}$';

            if (!preg_match($regex, $key)) {
                return response()->json([
                    'message' => 'Invalid QR Format'
                ], 400);
            }

            // Save data
            $requestData = $request->all();
            $device = Device::make($requestData);
            $saved = $device->save();

            if ($saved) {
                return response()->json([
                    'message' => 'Device Saved'
                ], 200);
            } else {
                return response()->json([
                    'message' => 'Could Not Save Device'
                ], 500);
            }
        }
    }
  • After each successful 'save', a 200 (OK) response is returned and the application beiing used to scan the physical devices and get the data checks for this error before allowing the user to scan the next device (to store it in the table).

After scanning a number of devices, I noticed that one record (entire data belonging to one device) was missing from the devices table. This means that if 300 devices were scanned, only 299 records were present. However, if a 500 error was returned at any time, this would have been detected by the application.

  • I know that there may be various reasons for issues like this, but could someone kindly point out some common reason why this could happen? Could it be that data is saved successfully (and hence a 200 error is returned and interpreted by the user application as a 'go-ahead' for the next post request), and then 'deleted' immediately after?

I am now implementing Laravel Transactions in my code, for example:

// Save data
DB::beginTransaction();
try {
	$requestData = $request->all();
	$device = BleTag::make($requestData);
	$saved = $device->save();
	DB::commit();
} catch (\Exception $e) {
	DB::rollback();
	//throw $e;
	return response()->json([
		'message' => 'Could Not Save Device'
	], 500);
}
  • Could this help prevent something like this from happening, or it is only useful when performing a group of database operations which are different in nature?

Thank you in advance, Brian

Sep
07
2 months ago
Activity icon

Replied to Hide/Show Bootstrap Table Columns When Using Laravel Pagination

Hi,

Sorry for the late reply! Thanks for your opinion. I will probably use DataTables then as it would probably save me some time and seems good for my application. However I would try building my own in the future :)

Thanks again, Brian

Sep
01
3 months ago
Activity icon

Replied to Hide/Show Bootstrap Table Columns When Using Laravel Pagination

Hi @bobbybouwmann, thanks for your reply.

Regarding the Laravel solution, in fact, currently for the search and sorting functions, I am adjusting the URL by appending the search 'keyword', sort selection, and sorting order (ascending or descending) to the URL:

In the search and sort function in the DevicesController:

$devices->appends(array('keyword'=>$request->input('keyword')));
$devices->appends(array('sort'=>$request->input('sort')));
$devices->appends(array('order'=>$request->input('order')));

The following is the URL when moving from page 1 of the paginated and tabulated results to page 2:

http://mywebsite/devices/results?keyword=sig&sort=id&order=ASC&page=2

This worked, but then, as discussed in my first post, I got stuck when trying to do the hide/show columns feature. As you said, this would need to adjust the URL and a lot of parameters would have to be added to keep track of the columns and each time load the data which 'belongs' to those parameters.

  • With regards to the AJAX solution you suggested, would you suggest using Laravel DataTables such as YajraBox?

Thanks for your suggestions/guidance!

Activity icon

Started a new Conversation Hide/Show Bootstrap Table Columns When Using Laravel Pagination

Hi :)

I am working on a Laravel project where I have a table containing tens of thousands of records, which I must display to the user in a blade view (in a table).

Currently, I am using a function in the controller to get all records ($devices) from the table (devices table) using Laravel's pagination, as shown below:

In the controller:

public function index()
{
    $devices = Device::paginate(50);
    return view('devices', [
    	'devices'=>$devices,
     ]);
}

In my devices.blade.php view, I am then displaying all rows and columns in a bootstrapTable, as shown below:

@if(count($devices))
			{{-- Show all devices table --}}
			<div 
				id="toolbar">
			</div>
			<table id="table" class="table table-responsive table-theme v-middle" data-plugin="bootstrapTable" data-toolbar="#toolbar" data-search="false" data-search-align="left" data-show-export="false" data-show-columns="true" data-detail-view="false" data-mobile-responsive="true"
			data-pagination="false" data-page-list="[10, 25, 50, 100, ALL]">
				<thead>
					<tr>
						<th data-field="id">ID</th>
						<th data-field="code">Device Code</th>
						<th data-field="comments">Comments</th>
						
						Other fields...

					</tr>
				</thead>
				{{-- Table content --}}
				<tbody>
					@foreach ($devices as $device)
						<tr class=" " data-id=" ">
							{{-- <td style="min-width:30px;text-align:center"> --}}
							<td class="flex">
								{{ $device->id }}
							</td>
							<td class="flex">
								{{ $device->code }}
							</td>
							<td class="flex">
								{{ $device->comments }}
							</td>
							
							Other fields...

						</tr>
					@endforeach
				</tbody>
			</table>
			<div>
				{{ $devices->links() }}
			</div>
		@else
			<div class="row row-sm sr">
	    		<p>Sorry, but nothing matched your search terms. Please try again with some different keywords.</p>
			</div>
		@endif

The issues I am encountering are the following:

  • Since I'm using Laravel's pagination feature to deal with the large quantity of data which I need to display, Bootstrap table features such as data-search, data-show-columns and data-sortable only work for the table on the current page. This means that when using the bootstrap table's search bar, you would only be searching in the current page and not in all records.

  • Similarly, when sorting the fields in ascending/descending order, the sorting is only applied to the 10/25/50/100 records currently being displayed and not to the entire list of records (even those which are in other pagination pages).

  • With regards to show/hide columns, when I click on the next page button (the one added when using Laravel Pagination, to go from mywebiste/devices/ to mywebiste/devices/?page=2 (the second page of the paginated results), all columns are displayed again, even if some were hidden in the previous page.

  • 'Passing' all records (thousands) to the view without Laravel's Pagination was not an option due to the large amount of data that needs to be displayed.

What would be the best solution to achieve the required search, sort, filter, hide columns features in the table, while not running into problems related to loading tens of thousands of records from the database please?

Note: I have successfully implemented search and sorting features using a POST form in my devices view and a search/sort method in the DeviceController, however, I still believe there is a better/cleaner and simpler way of achieving these features - And I still haven't managed to do something similar for 'hiding/showing columns' in the table.

Thanks!

Aug
28
3 months ago
Activity icon

Replied to Getting Large Amounts Of Data From A Table And Passing It To A View In Laravel

@newbie360

Hi, thanks for the tip. Yes I'm currently using a Bootstrap table with hoverable rows and where the user can select the number of rows displayed (for example 20, 50, 10, etc...) per 'table page'. The data is therefore still loaded all at once but just displayed in 'groups' of 20, 50 or 100 on the front-end.

I just had a quick look at the documentation for Laravel's Pagination and this may be what I'll be needing. The HTML generated is compatible with Bootstrap CSS framework and URIs can be customised.

Are there any other methods I can consider for this application?

Thanks a lot, Brian

Aug
27
3 months ago
Activity icon

Started a new Conversation Getting Large Amounts Of Data From A Table And Passing It To A View In Laravel

Hi :)

I currently have a devices table in my database, and in my DeviceController, I am getting a large number of records (thousands and even over ten thousand records) from the devices table, and then 'passing' these records (devices) to my view (the view is called devices.blade.php) using the below:

class DeviceController extends Controller
{
    public function index()
    {
        $id = auth()->user()->group->id;	// Group ID
   	    
        $devices = Device::where('group_id', $id)->get();

        return view('devices', [
            'devices'=>$devices,
        ]);
    }
}

Although this may work, and did work for some thousands of records, (say you have eight thousand records/rows or even more, with over 30 fields/columns each) I am sure that it is not the ideal way how to get a large amount of data from a table and 'send' it to your view.

  • I came across Laravel's chunk(), however, if I understood well, this is not what I need in this case. chunk() is used for processing large tables/large amounts of data in a database. In my case I am not processing the data of performing any actions on my data; just passing the data to the blade view and displaying it to the user using:
@foreach ($devices as $device)			
	{{ $device->field_1 }}
	{{ $device->field_2 }}
	{{ $device->field_3 }}
	{{-- This is just an example --}}
@endforeach

In my devices.blade.php file, I will be using a Bootstrap table which automatically 'splits'/shows data in pages (for instance 50 or 100 devices records at a time) while still remaining on the same blade view and in the same web route.

What would you suggest using to safely and efficiently fetch and display large amounts of data please? I appreciate your suggestions :)

Thanks!

Aug
25
3 months ago
Activity icon

Replied to Simple API Login Without Using Passport

For my Laravel project to function as required, I made some changes/custom modifications to the Laravel Auth Scaffolding. These include the addition and modification of functions in the RegisterController, the VerificationController, the ForgotPasswordController, and the ResetPasswordController.

I also modified and added some routes in my routes file web.php. In other words, instead of using

Auth::routes();

in the web.php file, I defined all auth routes being used by my application, and modified/added others, for instance:

...
// Password reset routes:
Route::post('password/email', 'Auth\[email protected]')->name('password.email');
Route::get('password/reset', 'Auth\[email protected]')->name('password.request');
Route::get('password/reset/{token}', 'Auth\[email protected]')->name('password.reset');
Route::post('password/reset', 'Auth\[email protected]')->name('password.update');
// Email verification routes:
Route::get('/verify/resend/{id}', 'Auth\[email protected]');
Route::get('/verify/email/{id}', 'Auth\[email protected]')->name('verify');
...
  • If I understood well after looking at the documentation of both Laravel Auth Scaffolding and Laravel Passport, these are separate from each other as one package is responsible for just the web part while the other for the authentication of mobile applications and other applications. Therefore, changes in the auth structure/code should not have an impact on the API authentication using Passport. Is this correct?

Thanks a lot, Brian

Activity icon

Replied to Simple API Login Without Using Passport

Thanks for the advice @martinbean.

I will definitely consider using Laravel Passport for API authentication then. I will go through the documentation to understand how I can implement this authentication package for my project.

Aug
23
3 months ago
Activity icon

Replied to Simple API Login Without Using Passport

Hi BOBBYBOUWMANN,

Thanks! I had a look at the documentation provided and it seems that Laravel's built-in API token system you suggested is what I need in this case. Will check if it is still supported in Laravel 7.x though.

If I understood well, when using hashed token, API tokens are not generated and stored when users register an account. Instead, these have to be generated and stored manual using an APITokenController for example:

  • So in this case, is the (hashed) token created and stored when the user sends a login request with the respective username and password via the API login route?

I have another question regarding the token expiration/timeout:

  • If a token is created and stored into the api_token field of the users table, does this mean that the token remains unchanged unless re-generated and re-stored manually, or is there a timeout associated to the api_token field?

I appreciate any advice on this topic; thank you :)

Regards, Brian

Aug
22
3 months ago
Activity icon

Started a new Conversation Simple API Login Without Using Passport

Hi,

I have a Laravel project in which I used Laravel's Authentication scaffolding to register, login and logout (amongst other auth actions) users is the web app. Users are stored in the Users table.

The complete system however will also need a way how users can login into their account (Users table) from a mobile application or from other web apps, using API routes. This means that I need a simple way of securely 'forwarding' the email address and password to an APILoginController via an API route (for instance http://localhost/api/login?email=...&password=...).

A function in the APILoginController will:

  • Check if the user with the provided email address exists in the Users table.
  • If the user is found, the provided password (for example from the mobile application via the API login route) matches the hashed password in the database/Users table, and if these match, the user using the mobile app can be logged in and can request data from other tables in the database of the Laravel project.

Currently, I was thinkng of implementing something like this:

In api.php:

Route::post('/login', 'API\[email protected]');

In APILoginController (a controller created under Http/Controllers/API):

public function loginUser(Request $request)
    {
    	$email = $request->input('email');
    	$password = $request->input('password');

    	$user = User::where(['email'=>$email)->first();
        if($user)       // If the user is found
        {
            // CHECK THAT API PASSWORD MATCHES DB PASSWORD
            // LOGIN USER
        }else{
            return 'user not found';       // You can create a page for this
        }
    }

My question is, how should I 'login' the user via an API login such that for example mobile app users can login and request data from the database?

I appreciate any advice and thank you in advance!

Brian

Aug
21
3 months ago
Activity icon

Replied to Validating Signed Route Requests With Additional Query Parameters Attached To The End Of The Signed URL

That worked well for me. Better than specifying what to remove in case other parameters are added to the URL. Thanks!

Aug
20
3 months ago
Activity icon

Replied to Validating Signed Route Requests With Additional Query Parameters Attached To The End Of The Signed URL

Thanks, that seems to be a good way of getting rid of all unwanted parameters. Will try it out and see if it works.

Activity icon

Replied to Validating Signed Route Requests With Additional Query Parameters Attached To The End Of The Signed URL

Hi,

Thank you Sinnbeck! It's working perfectly now after removing the source, medium and campaign parameters.

I'll try to find a way how to 'keep only' the fields needed to validate the signed URL (the expires and the signature fields). I tried using:

$request->only('expires', 'signature');

However this did not work for me. When returning $request, I still got {"expires":"1597911799","signature":"8b3a0889c3d9203417a563d2dacf9062d0dd3a0d6d97ac373867762496ba17b8","utm_source":"sendgrid.com","utm_medium":"email","utm_campaign":"website"}

I'll try some other ways and see what I get.

Regards, Brian

Activity icon

Replied to Validating Signed Route Requests With Additional Query Parameters Attached To The End Of The Signed URL

Hi Sinnbeck,

Thank you for your suggestions.

  • With regards to your first suggestion: In my first post I forgot to include that when I disabled the Google Analytics from Sendgrid, the mentioned query parameters (&utm_source=sendgrid.com&utm_medium=email&utm_campaign=website) were not added to the URL, and the link worked fine - It was validated successfully.

However, I am trying to find a way how these can be left on, and whatever is added to Laravel's generated URL, this URL still remains 'valid' (i.e. A solution in Laravel is needed, irrespective of Sendgrid's settings).

  • Regarding the second point: I modified my code in the controller as suggested (shown below) to try turning $absolute off:
public function checkLink($id, Request $request) 
    {
        if (!$request->hasValidSignature(false)) {
            //abort(401, 'This link is not valid.');
            $verified = false;
            return view('auth.login')->with('id', $id)->with('message', $verified);    // When we redirect, we will have the message in our session
        }
	// My actions	
}

This did not solve the issue and caused another problem, where even if I paste the generated URL only (without the query parameters/Google Analytics added by Sendgrid), this is still interpreted as invalid.

Is there maybe something else that should be added when turning $absolute off?

Thank you for your suggestions/help, Brian

Aug
19
3 months ago
Activity icon

Started a new Conversation Validating Signed Route Requests With Additional Query Parameters Attached To The End Of The Signed URL

Hi,

I am creating a signed URL to a name route (the route is named verify). To create the URL in a controller, I am using:

$url = URL::temporarySignedRoute('verify', now()->addMinutes(30), ['id' => $id]);

When returning this signed URL and inputting it into the search bar, the URL is validated successfully; However, when sending this ULR using Sendgrid, additional query parameters are being attached to the signed URL created by Laravel's URL generation, causing the URL to be interpreted as 'invalid'.

For instance:

To verify the URL I followed Laravel's URL generation documentation and example code (https://laravel.com/docs/7.x/urls)

Is there a way how the appended query parameters can be ignored when validating the URL, as to still be able to verify any URL irrespective of the query parameters attached to the end of the created URL?

I thank you in advance for your help.

Regards, Brian