Web  Dev

Web Dev

1595042052

The Access-Control-Allow-Origin Header Explained – With a CORS Example

Often times when calling an API, you may see an error in your console that looks like this:

Access to fetch at 'http://somesite.com' from origin 'http://yoursite.com' has been blocked by CORS policy: The 'Access-Control-Allow-Origin' header has a value that is not equal to the supplied origin

In this post, we are going to learn why this error happens and how you can fix it.

What is the Access-Control-Allow-Origin header?

Access-Control-Allow-Origin is a CORS header. CORS, or Cross Origin Resource Sharing, is a mechanism for browsers to let a site running at origin A to request resources from origin B.

Origin is not just the hostname, but a combination of port, hostname and scheme, such as - http://mysite.example.com:8080/

Here’s an example of where this comes into action -

  1. I have an origin A: http://mysite.com and I want to get resources from origin B: http://yoursite.com.
  2. To protect your security, the browser will not let me access resources from yoursite.com and will block my request.
  3. In order to allow origin A to access your resources, your origin B will need to let the browser know that it is okay for me to get resources from your origin.

Here is an example from MDN that explains this really well:

https://mdn.mozillademos.org/files/14295/CORS_principle.png

With the help of CORS, browsers allow origins to share resources amongst each other.

There are a few headers that allow sharing of resources across origins, but the main one is Access-Control-Allow-Origin. This tells the browser what origins are allowed to receive requests from this server.

#developer #javascript

What is GEEK

Buddha Community

The Access-Control-Allow-Origin Header Explained – With a CORS Example
Lawrence  Lesch

Lawrence Lesch

1677668905

TS-mockito: Mocking Library for TypeScript

TS-mockito

Mocking library for TypeScript inspired by http://mockito.org/

1.x to 2.x migration guide

1.x to 2.x migration guide

Main features

  • Strongly typed
  • IDE autocomplete
  • Mock creation (mock) (also abstract classes) #example
  • Spying on real objects (spy) #example
  • Changing mock behavior (when) via:
  • Checking if methods were called with given arguments (verify)
    • anything, notNull, anyString, anyOfClass etc. - for more flexible comparision
    • once, twice, times, atLeast etc. - allows call count verification #example
    • calledBefore, calledAfter - allows call order verification #example
  • Resetting mock (reset, resetCalls) #example, #example
  • Capturing arguments passed to method (capture) #example
  • Recording multiple behaviors #example
  • Readable error messages (ex. 'Expected "convertNumberToString(strictEqual(3))" to be called 2 time(s). But has been called 1 time(s).')

Installation

npm install ts-mockito --save-dev

Usage

Basics

// Creating mock
let mockedFoo:Foo = mock(Foo);

// Getting instance from mock
let foo:Foo = instance(mockedFoo);

// Using instance in source code
foo.getBar(3);
foo.getBar(5);

// Explicit, readable verification
verify(mockedFoo.getBar(3)).called();
verify(mockedFoo.getBar(anything())).called();

Stubbing method calls

// Creating mock
let mockedFoo:Foo = mock(Foo);

// stub method before execution
when(mockedFoo.getBar(3)).thenReturn('three');

// Getting instance
let foo:Foo = instance(mockedFoo);

// prints three
console.log(foo.getBar(3));

// prints null, because "getBar(999)" was not stubbed
console.log(foo.getBar(999));

Stubbing getter value

// Creating mock
let mockedFoo:Foo = mock(Foo);

// stub getter before execution
when(mockedFoo.sampleGetter).thenReturn('three');

// Getting instance
let foo:Foo = instance(mockedFoo);

// prints three
console.log(foo.sampleGetter);

Stubbing property values that have no getters

Syntax is the same as with getter values.

Please note, that stubbing properties that don't have getters only works if Proxy object is available (ES6).

Call count verification

// Creating mock
let mockedFoo:Foo = mock(Foo);

// Getting instance
let foo:Foo = instance(mockedFoo);

// Some calls
foo.getBar(1);
foo.getBar(2);
foo.getBar(2);
foo.getBar(3);

// Call count verification
verify(mockedFoo.getBar(1)).once();               // was called with arg === 1 only once
verify(mockedFoo.getBar(2)).twice();              // was called with arg === 2 exactly two times
verify(mockedFoo.getBar(between(2, 3))).thrice(); // was called with arg between 2-3 exactly three times
verify(mockedFoo.getBar(anyNumber()).times(4);    // was called with any number arg exactly four times
verify(mockedFoo.getBar(2)).atLeast(2);           // was called with arg === 2 min two times
verify(mockedFoo.getBar(anything())).atMost(4);   // was called with any argument max four times
verify(mockedFoo.getBar(4)).never();              // was never called with arg === 4

Call order verification

// Creating mock
let mockedFoo:Foo = mock(Foo);
let mockedBar:Bar = mock(Bar);

// Getting instance
let foo:Foo = instance(mockedFoo);
let bar:Bar = instance(mockedBar);

// Some calls
foo.getBar(1);
bar.getFoo(2);

// Call order verification
verify(mockedFoo.getBar(1)).calledBefore(mockedBar.getFoo(2));    // foo.getBar(1) has been called before bar.getFoo(2)
verify(mockedBar.getFoo(2)).calledAfter(mockedFoo.getBar(1));    // bar.getFoo(2) has been called before foo.getBar(1)
verify(mockedFoo.getBar(1)).calledBefore(mockedBar.getFoo(999999));    // throws error (mockedBar.getFoo(999999) has never been called)

Throwing errors

let mockedFoo:Foo = mock(Foo);

when(mockedFoo.getBar(10)).thenThrow(new Error('fatal error'));

let foo:Foo = instance(mockedFoo);
try {
    foo.getBar(10);
} catch (error:Error) {
    console.log(error.message); // 'fatal error'
}

Custom function

You can also stub method with your own implementation

let mockedFoo:Foo = mock(Foo);
let foo:Foo = instance(mockedFoo);

when(mockedFoo.sumTwoNumbers(anyNumber(), anyNumber())).thenCall((arg1:number, arg2:number) => {
    return arg1 * arg2; 
});

// prints '50' because we've changed sum method implementation to multiply!
console.log(foo.sumTwoNumbers(5, 10));

Resolving / rejecting promises

You can also stub method to resolve / reject promise

let mockedFoo:Foo = mock(Foo);

when(mockedFoo.fetchData("a")).thenResolve({id: "a", value: "Hello world"});
when(mockedFoo.fetchData("b")).thenReject(new Error("b does not exist"));

Resetting mock calls

You can reset just mock call counter

// Creating mock
let mockedFoo:Foo = mock(Foo);

// Getting instance
let foo:Foo = instance(mockedFoo);

// Some calls
foo.getBar(1);
foo.getBar(1);
verify(mockedFoo.getBar(1)).twice();      // getBar with arg "1" has been called twice

// Reset mock
resetCalls(mockedFoo);

// Call count verification
verify(mockedFoo.getBar(1)).never();      // has never been called after reset

You can also reset calls of multiple mocks at once resetCalls(firstMock, secondMock, thirdMock)

Resetting mock

Or reset mock call counter with all stubs

// Creating mock
let mockedFoo:Foo = mock(Foo);
when(mockedFoo.getBar(1)).thenReturn("one").

// Getting instance
let foo:Foo = instance(mockedFoo);

// Some calls
console.log(foo.getBar(1));               // "one" - as defined in stub
console.log(foo.getBar(1));               // "one" - as defined in stub
verify(mockedFoo.getBar(1)).twice();      // getBar with arg "1" has been called twice

// Reset mock
reset(mockedFoo);

// Call count verification
verify(mockedFoo.getBar(1)).never();      // has never been called after reset
console.log(foo.getBar(1));               // null - previously added stub has been removed

You can also reset multiple mocks at once reset(firstMock, secondMock, thirdMock)

Capturing method arguments

let mockedFoo:Foo = mock(Foo);
let foo:Foo = instance(mockedFoo);

// Call method
foo.sumTwoNumbers(1, 2);

// Check first arg captor values
const [firstArg, secondArg] = capture(mockedFoo.sumTwoNumbers).last();
console.log(firstArg);    // prints 1
console.log(secondArg);    // prints 2

You can also get other calls using first(), second(), byCallIndex(3) and more...

Recording multiple behaviors

You can set multiple returning values for same matching values

const mockedFoo:Foo = mock(Foo);

when(mockedFoo.getBar(anyNumber())).thenReturn('one').thenReturn('two').thenReturn('three');

const foo:Foo = instance(mockedFoo);

console.log(foo.getBar(1));    // one
console.log(foo.getBar(1));    // two
console.log(foo.getBar(1));    // three
console.log(foo.getBar(1));    // three - last defined behavior will be repeated infinitely

Another example with specific values

let mockedFoo:Foo = mock(Foo);

when(mockedFoo.getBar(1)).thenReturn('one').thenReturn('another one');
when(mockedFoo.getBar(2)).thenReturn('two');

let foo:Foo = instance(mockedFoo);

console.log(foo.getBar(1));    // one
console.log(foo.getBar(2));    // two
console.log(foo.getBar(1));    // another one
console.log(foo.getBar(1));    // another one - this is last defined behavior for arg '1' so it will be repeated
console.log(foo.getBar(2));    // two
console.log(foo.getBar(2));    // two - this is last defined behavior for arg '2' so it will be repeated

Short notation:

const mockedFoo:Foo = mock(Foo);

// You can specify return values as multiple thenReturn args
when(mockedFoo.getBar(anyNumber())).thenReturn('one', 'two', 'three');

const foo:Foo = instance(mockedFoo);

console.log(foo.getBar(1));    // one
console.log(foo.getBar(1));    // two
console.log(foo.getBar(1));    // three
console.log(foo.getBar(1));    // three - last defined behavior will be repeated infinity

Possible errors:

const mockedFoo:Foo = mock(Foo);

// When multiple matchers, matches same result:
when(mockedFoo.getBar(anyNumber())).thenReturn('one');
when(mockedFoo.getBar(3)).thenReturn('one');

const foo:Foo = instance(mockedFoo);
foo.getBar(3); // MultipleMatchersMatchSameStubError will be thrown, two matchers match same method call

Mocking interfaces

You can mock interfaces too, just instead of passing type to mock function, set mock function generic type Mocking interfaces requires Proxy implementation

let mockedFoo:Foo = mock<FooInterface>(); // instead of mock(FooInterface)
const foo: SampleGeneric<FooInterface> = instance(mockedFoo);

Mocking types

You can mock abstract classes

const mockedFoo: SampleAbstractClass = mock(SampleAbstractClass);
const foo: SampleAbstractClass = instance(mockedFoo);

You can also mock generic classes, but note that generic type is just needed by mock type definition

const mockedFoo: SampleGeneric<SampleInterface> = mock(SampleGeneric);
const foo: SampleGeneric<SampleInterface> = instance(mockedFoo);

Spying on real objects

You can partially mock an existing instance:

const foo: Foo = new Foo();
const spiedFoo = spy(foo);

when(spiedFoo.getBar(3)).thenReturn('one');

console.log(foo.getBar(3)); // 'one'
console.log(foo.getBaz()); // call to a real method

You can spy on plain objects too:

const foo = { bar: () => 42 };
const spiedFoo = spy(foo);

foo.bar();

console.log(capture(spiedFoo.bar).last()); // [42] 

Thanks


Download Details:

Author: NagRock
Source Code: https://github.com/NagRock/ts-mockito 
License: MIT license

#typescript #testing #mock 

How to Create Arrays in Python

In this tutorial, you'll know the basics of how to create arrays in Python using the array module. Learn how to use Python arrays. You'll see how to define them and the different methods commonly used for performing operations on them.

This tutorialvideo on 'Arrays in Python' will help you establish a strong hold on all the fundamentals in python programming language. Below are the topics covered in this video:  
1:15 What is an array?
2:53 Is python list same as an array?
3:48  How to create arrays in python?
7:19 Accessing array elements
9:59 Basic array operations
        - 10:33  Finding the length of an array
        - 11:44  Adding Elements
        - 15:06  Removing elements
        - 18:32  Array concatenation
       - 20:59  Slicing
       - 23:26  Looping  


Python Array Tutorial – Define, Index, Methods

In this article, you'll learn how to use Python arrays. You'll see how to define them and the different methods commonly used for performing operations on them.

The artcile covers arrays that you create by importing the array module. We won't cover NumPy arrays here.

Table of Contents

  1. Introduction to Arrays
    1. The differences between Lists and Arrays
    2. When to use arrays
  2. How to use arrays
    1. Define arrays
    2. Find the length of arrays
    3. Array indexing
    4. Search through arrays
    5. Loop through arrays
    6. Slice an array
  3. Array methods for performing operations
    1. Change an existing value
    2. Add a new value
    3. Remove a value
  4. Conclusion

Let's get started!

What are Python Arrays?

Arrays are a fundamental data structure, and an important part of most programming languages. In Python, they are containers which are able to store more than one item at the same time.

Specifically, they are an ordered collection of elements with every value being of the same data type. That is the most important thing to remember about Python arrays - the fact that they can only hold a sequence of multiple items that are of the same type.

What's the Difference between Python Lists and Python Arrays?

Lists are one of the most common data structures in Python, and a core part of the language.

Lists and arrays behave similarly.

Just like arrays, lists are an ordered sequence of elements.

They are also mutable and not fixed in size, which means they can grow and shrink throughout the life of the program. Items can be added and removed, making them very flexible to work with.

However, lists and arrays are not the same thing.

Lists store items that are of various data types. This means that a list can contain integers, floating point numbers, strings, or any other Python data type, at the same time. That is not the case with arrays.

As mentioned in the section above, arrays store only items that are of the same single data type. There are arrays that contain only integers, or only floating point numbers, or only any other Python data type you want to use.

When to Use Python Arrays

Lists are built into the Python programming language, whereas arrays aren't. Arrays are not a built-in data structure, and therefore need to be imported via the array module in order to be used.

Arrays of the array module are a thin wrapper over C arrays, and are useful when you want to work with homogeneous data.

They are also more compact and take up less memory and space which makes them more size efficient compared to lists.

If you want to perform mathematical calculations, then you should use NumPy arrays by importing the NumPy package. Besides that, you should just use Python arrays when you really need to, as lists work in a similar way and are more flexible to work with.

How to Use Arrays in Python

In order to create Python arrays, you'll first have to import the array module which contains all the necassary functions.

There are three ways you can import the array module:

  • By using import array at the top of the file. This includes the module array. You would then go on to create an array using array.array().
import array

#how you would create an array
array.array()
  • Instead of having to type array.array() all the time, you could use import array as arr at the top of the file, instead of import array alone. You would then create an array by typing arr.array(). The arr acts as an alias name, with the array constructor then immediately following it.
import array as arr

#how you would create an array
arr.array()
  • Lastly, you could also use from array import *, with * importing all the functionalities available. You would then create an array by writing the array() constructor alone.
from array import *

#how you would create an array
array()

How to Define Arrays in Python

Once you've imported the array module, you can then go on to define a Python array.

The general syntax for creating an array looks like this:

variable_name = array(typecode,[elements])

Let's break it down:

  • variable_name would be the name of the array.
  • The typecode specifies what kind of elements would be stored in the array. Whether it would be an array of integers, an array of floats or an array of any other Python data type. Remember that all elements should be of the same data type.
  • Inside square brackets you mention the elements that would be stored in the array, with each element being separated by a comma. You can also create an empty array by just writing variable_name = array(typecode) alone, without any elements.

Below is a typecode table, with the different typecodes that can be used with the different data types when defining Python arrays:

TYPECODEC TYPEPYTHON TYPESIZE
'b'signed charint1
'B'unsigned charint1
'u'wchar_tUnicode character2
'h'signed shortint2
'H'unsigned shortint2
'i'signed intint2
'I'unsigned intint2
'l'signed longint4
'L'unsigned longint4
'q'signed long longint8
'Q'unsigned long longint8
'f'floatfloat4
'd'doublefloat8

Tying everything together, here is an example of how you would define an array in Python:

import array as arr 

numbers = arr.array('i',[10,20,30])


print(numbers)

#output

#array('i', [10, 20, 30])

Let's break it down:

  • First we included the array module, in this case with import array as arr .
  • Then, we created a numbers array.
  • We used arr.array() because of import array as arr .
  • Inside the array() constructor, we first included i, for signed integer. Signed integer means that the array can include positive and negative values. Unsigned integer, with H for example, would mean that no negative values are allowed.
  • Lastly, we included the values to be stored in the array in square brackets.

Keep in mind that if you tried to include values that were not of i typecode, meaning they were not integer values, you would get an error:

import array as arr 

numbers = arr.array('i',[10.0,20,30])


print(numbers)

#output

#Traceback (most recent call last):
# File "/Users/dionysialemonaki/python_articles/demo.py", line 14, in <module>
#   numbers = arr.array('i',[10.0,20,30])
#TypeError: 'float' object cannot be interpreted as an integer

In the example above, I tried to include a floating point number in the array. I got an error because this is meant to be an integer array only.

Another way to create an array is the following:

from array import *

#an array of floating point values
numbers = array('d',[10.0,20.0,30.0])

print(numbers)

#output

#array('d', [10.0, 20.0, 30.0])

The example above imported the array module via from array import * and created an array numbers of float data type. This means that it holds only floating point numbers, which is specified with the 'd' typecode.

How to Find the Length of an Array in Python

To find out the exact number of elements contained in an array, use the built-in len() method.

It will return the integer number that is equal to the total number of elements in the array you specify.

import array as arr 

numbers = arr.array('i',[10,20,30])


print(len(numbers))

#output
# 3

In the example above, the array contained three elements – 10, 20, 30 – so the length of numbers is 3.

Array Indexing and How to Access Individual Items in an Array in Python

Each item in an array has a specific address. Individual items are accessed by referencing their index number.

Indexing in Python, and in all programming languages and computing in general, starts at 0. It is important to remember that counting starts at 0 and not at 1.

To access an element, you first write the name of the array followed by square brackets. Inside the square brackets you include the item's index number.

The general syntax would look something like this:

array_name[index_value_of_item]

Here is how you would access each individual element in an array:

import array as arr 

numbers = arr.array('i',[10,20,30])

print(numbers[0]) # gets the 1st element
print(numbers[1]) # gets the 2nd element
print(numbers[2]) # gets the 3rd element

#output

#10
#20
#30

Remember that the index value of the last element of an array is always one less than the length of the array. Where n is the length of the array, n - 1 will be the index value of the last item.

Note that you can also access each individual element using negative indexing.

With negative indexing, the last element would have an index of -1, the second to last element would have an index of -2, and so on.

Here is how you would get each item in an array using that method:

import array as arr 

numbers = arr.array('i',[10,20,30])

print(numbers[-1]) #gets last item
print(numbers[-2]) #gets second to last item
print(numbers[-3]) #gets first item
 
#output

#30
#20
#10

How to Search Through an Array in Python

You can find out an element's index number by using the index() method.

You pass the value of the element being searched as the argument to the method, and the element's index number is returned.

import array as arr 

numbers = arr.array('i',[10,20,30])

#search for the index of the value 10
print(numbers.index(10))

#output

#0

If there is more than one element with the same value, the index of the first instance of the value will be returned:

import array as arr 


numbers = arr.array('i',[10,20,30,10,20,30])

#search for the index of the value 10
#will return the index number of the first instance of the value 10
print(numbers.index(10))

#output

#0

How to Loop through an Array in Python

You've seen how to access each individual element in an array and print it out on its own.

You've also seen how to print the array, using the print() method. That method gives the following result:

import array as arr 

numbers = arr.array('i',[10,20,30])

print(numbers)

#output

#array('i', [10, 20, 30])

What if you want to print each value one by one?

This is where a loop comes in handy. You can loop through the array and print out each value, one-by-one, with each loop iteration.

For this you can use a simple for loop:

import array as arr 

numbers = arr.array('i',[10,20,30])

for number in numbers:
    print(number)
    
#output
#10
#20
#30

You could also use the range() function, and pass the len() method as its parameter. This would give the same result as above:

import array as arr  

values = arr.array('i',[10,20,30])

#prints each individual value in the array
for value in range(len(values)):
    print(values[value])

#output

#10
#20
#30

How to Slice an Array in Python

To access a specific range of values inside the array, use the slicing operator, which is a colon :.

When using the slicing operator and you only include one value, the counting starts from 0 by default. It gets the first item, and goes up to but not including the index number you specify.

import array as arr 

#original array
numbers = arr.array('i',[10,20,30])

#get the values 10 and 20 only
print(numbers[:2])  #first to second position

#output

#array('i', [10, 20])

When you pass two numbers as arguments, you specify a range of numbers. In this case, the counting starts at the position of the first number in the range, and up to but not including the second one:

import array as arr 

#original array
numbers = arr.array('i',[10,20,30])


#get the values 20 and 30 only
print(numbers[1:3]) #second to third position

#output

#rray('i', [20, 30])

Methods For Performing Operations on Arrays in Python

Arrays are mutable, which means they are changeable. You can change the value of the different items, add new ones, or remove any you don't want in your program anymore.

Let's see some of the most commonly used methods which are used for performing operations on arrays.

How to Change the Value of an Item in an Array

You can change the value of a specific element by speficying its position and assigning it a new value:

import array as arr 

#original array
numbers = arr.array('i',[10,20,30])

#change the first element
#change it from having a value of 10 to having a value of 40
numbers[0] = 40

print(numbers)

#output

#array('i', [40, 20, 30])

How to Add a New Value to an Array

To add one single value at the end of an array, use the append() method:

import array as arr 

#original array
numbers = arr.array('i',[10,20,30])

#add the integer 40 to the end of numbers
numbers.append(40)

print(numbers)

#output

#array('i', [10, 20, 30, 40])

Be aware that the new item you add needs to be the same data type as the rest of the items in the array.

Look what happens when I try to add a float to an array of integers:

import array as arr 

#original array
numbers = arr.array('i',[10,20,30])

#add the integer 40 to the end of numbers
numbers.append(40.0)

print(numbers)

#output

#Traceback (most recent call last):
#  File "/Users/dionysialemonaki/python_articles/demo.py", line 19, in <module>
#   numbers.append(40.0)
#TypeError: 'float' object cannot be interpreted as an integer

But what if you want to add more than one value to the end an array?

Use the extend() method, which takes an iterable (such as a list of items) as an argument. Again, make sure that the new items are all the same data type.

import array as arr 

#original array
numbers = arr.array('i',[10,20,30])

#add the integers 40,50,60 to the end of numbers
#The numbers need to be enclosed in square brackets

numbers.extend([40,50,60])

print(numbers)

#output

#array('i', [10, 20, 30, 40, 50, 60])

And what if you don't want to add an item to the end of an array? Use the insert() method, to add an item at a specific position.

The insert() function takes two arguments: the index number of the position the new element will be inserted, and the value of the new element.

import array as arr 

#original array
numbers = arr.array('i',[10,20,30])

#add the integer 40 in the first position
#remember indexing starts at 0

numbers.insert(0,40)

print(numbers)

#output

#array('i', [40, 10, 20, 30])

How to Remove a Value from an Array

To remove an element from an array, use the remove() method and include the value as an argument to the method.

import array as arr 

#original array
numbers = arr.array('i',[10,20,30])

numbers.remove(10)

print(numbers)

#output

#array('i', [20, 30])

With remove(), only the first instance of the value you pass as an argument will be removed.

See what happens when there are more than one identical values:

import array as arr 

#original array
numbers = arr.array('i',[10,20,30,10,20])

numbers.remove(10)

print(numbers)

#output

#array('i', [20, 30, 10, 20])

Only the first occurence of 10 is removed.

You can also use the pop() method, and specify the position of the element to be removed:

import array as arr 

#original array
numbers = arr.array('i',[10,20,30,10,20])

#remove the first instance of 10
numbers.pop(0)

print(numbers)

#output

#array('i', [20, 30, 10, 20])

Conclusion

And there you have it - you now know the basics of how to create arrays in Python using the array module. Hopefully you found this guide helpful.

Thanks for reading and happy coding!

#python #programming 

Connor Mills

Connor Mills

1670560264

Understanding Arrays in Python

Learn how to use Python arrays. Create arrays in Python using the array module. You'll see how to define them and the different methods commonly used for performing operations on them.
 

The artcile covers arrays that you create by importing the array module. We won't cover NumPy arrays here.

Table of Contents

  1. Introduction to Arrays
    1. The differences between Lists and Arrays
    2. When to use arrays
  2. How to use arrays
    1. Define arrays
    2. Find the length of arrays
    3. Array indexing
    4. Search through arrays
    5. Loop through arrays
    6. Slice an array
  3. Array methods for performing operations
    1. Change an existing value
    2. Add a new value
    3. Remove a value
  4. Conclusion

Let's get started!


What are Python Arrays?

Arrays are a fundamental data structure, and an important part of most programming languages. In Python, they are containers which are able to store more than one item at the same time.

Specifically, they are an ordered collection of elements with every value being of the same data type. That is the most important thing to remember about Python arrays - the fact that they can only hold a sequence of multiple items that are of the same type.

What's the Difference between Python Lists and Python Arrays?

Lists are one of the most common data structures in Python, and a core part of the language.

Lists and arrays behave similarly.

Just like arrays, lists are an ordered sequence of elements.

They are also mutable and not fixed in size, which means they can grow and shrink throughout the life of the program. Items can be added and removed, making them very flexible to work with.

However, lists and arrays are not the same thing.

Lists store items that are of various data types. This means that a list can contain integers, floating point numbers, strings, or any other Python data type, at the same time. That is not the case with arrays.

As mentioned in the section above, arrays store only items that are of the same single data type. There are arrays that contain only integers, or only floating point numbers, or only any other Python data type you want to use.

When to Use Python Arrays

Lists are built into the Python programming language, whereas arrays aren't. Arrays are not a built-in data structure, and therefore need to be imported via the array module in order to be used.

Arrays of the array module are a thin wrapper over C arrays, and are useful when you want to work with homogeneous data.

They are also more compact and take up less memory and space which makes them more size efficient compared to lists.

If you want to perform mathematical calculations, then you should use NumPy arrays by importing the NumPy package. Besides that, you should just use Python arrays when you really need to, as lists work in a similar way and are more flexible to work with.

How to Use Arrays in Python

In order to create Python arrays, you'll first have to import the array module which contains all the necassary functions.

There are three ways you can import the array module:

  1. By using import array at the top of the file. This includes the module array. You would then go on to create an array using array.array().
import array

#how you would create an array
array.array()
  1. Instead of having to type array.array() all the time, you could use import array as arr at the top of the file, instead of import array alone. You would then create an array by typing arr.array(). The arr acts as an alias name, with the array constructor then immediately following it.
import array as arr

#how you would create an array
arr.array()
  1. Lastly, you could also use from array import *, with * importing all the functionalities available. You would then create an array by writing the array() constructor alone.
from array import *

#how you would create an array
array()

How to Define Arrays in Python

Once you've imported the array module, you can then go on to define a Python array.

The general syntax for creating an array looks like this:

variable_name = array(typecode,[elements])

Let's break it down:

  • variable_name would be the name of the array.
  • The typecode specifies what kind of elements would be stored in the array. Whether it would be an array of integers, an array of floats or an array of any other Python data type. Remember that all elements should be of the same data type.
  • Inside square brackets you mention the elements that would be stored in the array, with each element being separated by a comma. You can also create an empty array by just writing variable_name = array(typecode) alone, without any elements.

Below is a typecode table, with the different typecodes that can be used with the different data types when defining Python arrays:

TYPECODEC TYPEPYTHON TYPESIZE
'b'signed charint1
'B'unsigned charint1
'u'wchar_tUnicode character2
'h'signed shortint2
'H'unsigned shortint2
'i'signed intint2
'I'unsigned intint2
'l'signed longint4
'L'unsigned longint4
'q'signed long longint8
'Q'unsigned long longint8
'f'floatfloat4
'd'doublefloat8

Tying everything together, here is an example of how you would define an array in Python:

import array as arr 

numbers = arr.array('i',[10,20,30])


print(numbers)

#output

#array('i', [10, 20, 30])

Let's break it down:

  • First we included the array module, in this case with import array as arr .
  • Then, we created a numbers array.
  • We used arr.array() because of import array as arr .
  • Inside the array() constructor, we first included i, for signed integer. Signed integer means that the array can include positive and negative values. Unsigned integer, with H for example, would mean that no negative values are allowed.
  • Lastly, we included the values to be stored in the array in square brackets.

Keep in mind that if you tried to include values that were not of i typecode, meaning they were not integer values, you would get an error:

import array as arr 

numbers = arr.array('i',[10.0,20,30])


print(numbers)

#output

#Traceback (most recent call last):
# File "/Users/dionysialemonaki/python_articles/demo.py", line 14, in <module>
#   numbers = arr.array('i',[10.0,20,30])
#TypeError: 'float' object cannot be interpreted as an integer

In the example above, I tried to include a floating point number in the array. I got an error because this is meant to be an integer array only.

Another way to create an array is the following:

from array import *

#an array of floating point values
numbers = array('d',[10.0,20.0,30.0])

print(numbers)

#output

#array('d', [10.0, 20.0, 30.0])

The example above imported the array module via from array import * and created an array numbers of float data type. This means that it holds only floating point numbers, which is specified with the 'd' typecode.

How to Find the Length of an Array in Python

To find out the exact number of elements contained in an array, use the built-in len() method.

It will return the integer number that is equal to the total number of elements in the array you specify.

import array as arr 

numbers = arr.array('i',[10,20,30])


print(len(numbers))

#output
# 3

In the example above, the array contained three elements – 10, 20, 30 – so the length of numbers is 3.

Array Indexing and How to Access Individual Items in an Array in Python

Each item in an array has a specific address. Individual items are accessed by referencing their index number.

Indexing in Python, and in all programming languages and computing in general, starts at 0. It is important to remember that counting starts at 0 and not at 1.

To access an element, you first write the name of the array followed by square brackets. Inside the square brackets you include the item's index number.

The general syntax would look something like this:

array_name[index_value_of_item]

Here is how you would access each individual element in an array:

import array as arr 

numbers = arr.array('i',[10,20,30])

print(numbers[0]) # gets the 1st element
print(numbers[1]) # gets the 2nd element
print(numbers[2]) # gets the 3rd element

#output

#10
#20
#30

Remember that the index value of the last element of an array is always one less than the length of the array. Where n is the length of the array, n - 1 will be the index value of the last item.

Note that you can also access each individual element using negative indexing.

With negative indexing, the last element would have an index of -1, the second to last element would have an index of -2, and so on.

Here is how you would get each item in an array using that method:

import array as arr 

numbers = arr.array('i',[10,20,30])

print(numbers[-1]) #gets last item
print(numbers[-2]) #gets second to last item
print(numbers[-3]) #gets first item
 
#output

#30
#20
#10

How to Search Through an Array in Python

You can find out an element's index number by using the index() method.

You pass the value of the element being searched as the argument to the method, and the element's index number is returned.

import array as arr 

numbers = arr.array('i',[10,20,30])

#search for the index of the value 10
print(numbers.index(10))

#output

#0

If there is more than one element with the same value, the index of the first instance of the value will be returned:

import array as arr 


numbers = arr.array('i',[10,20,30,10,20,30])

#search for the index of the value 10
#will return the index number of the first instance of the value 10
print(numbers.index(10))

#output

#0

How to Loop through an Array in Python

You've seen how to access each individual element in an array and print it out on its own.

You've also seen how to print the array, using the print() method. That method gives the following result:

import array as arr 

numbers = arr.array('i',[10,20,30])

print(numbers)

#output

#array('i', [10, 20, 30])

What if you want to print each value one by one?

This is where a loop comes in handy. You can loop through the array and print out each value, one-by-one, with each loop iteration.

For this you can use a simple for loop:

import array as arr 

numbers = arr.array('i',[10,20,30])

for number in numbers:
    print(number)
    
#output
#10
#20
#30

You could also use the range() function, and pass the len() method as its parameter. This would give the same result as above:

import array as arr  

values = arr.array('i',[10,20,30])

#prints each individual value in the array
for value in range(len(values)):
    print(values[value])

#output

#10
#20
#30

How to Slice an Array in Python

To access a specific range of values inside the array, use the slicing operator, which is a colon :.

When using the slicing operator and you only include one value, the counting starts from 0 by default. It gets the first item, and goes up to but not including the index number you specify.


import array as arr 

#original array
numbers = arr.array('i',[10,20,30])

#get the values 10 and 20 only
print(numbers[:2])  #first to second position

#output

#array('i', [10, 20])

When you pass two numbers as arguments, you specify a range of numbers. In this case, the counting starts at the position of the first number in the range, and up to but not including the second one:

import array as arr 

#original array
numbers = arr.array('i',[10,20,30])


#get the values 20 and 30 only
print(numbers[1:3]) #second to third position

#output

#rray('i', [20, 30])

Methods For Performing Operations on Arrays in Python

Arrays are mutable, which means they are changeable. You can change the value of the different items, add new ones, or remove any you don't want in your program anymore.

Let's see some of the most commonly used methods which are used for performing operations on arrays.

How to Change the Value of an Item in an Array

You can change the value of a specific element by speficying its position and assigning it a new value:

import array as arr 

#original array
numbers = arr.array('i',[10,20,30])

#change the first element
#change it from having a value of 10 to having a value of 40
numbers[0] = 40

print(numbers)

#output

#array('i', [40, 20, 30])

How to Add a New Value to an Array

To add one single value at the end of an array, use the append() method:

import array as arr 

#original array
numbers = arr.array('i',[10,20,30])

#add the integer 40 to the end of numbers
numbers.append(40)

print(numbers)

#output

#array('i', [10, 20, 30, 40])

Be aware that the new item you add needs to be the same data type as the rest of the items in the array.

Look what happens when I try to add a float to an array of integers:

import array as arr 

#original array
numbers = arr.array('i',[10,20,30])

#add the integer 40 to the end of numbers
numbers.append(40.0)

print(numbers)

#output

#Traceback (most recent call last):
#  File "/Users/dionysialemonaki/python_articles/demo.py", line 19, in <module>
#   numbers.append(40.0)
#TypeError: 'float' object cannot be interpreted as an integer

But what if you want to add more than one value to the end an array?

Use the extend() method, which takes an iterable (such as a list of items) as an argument. Again, make sure that the new items are all the same data type.

import array as arr 

#original array
numbers = arr.array('i',[10,20,30])

#add the integers 40,50,60 to the end of numbers
#The numbers need to be enclosed in square brackets

numbers.extend([40,50,60])

print(numbers)

#output

#array('i', [10, 20, 30, 40, 50, 60])

And what if you don't want to add an item to the end of an array? Use the insert() method, to add an item at a specific position.

The insert() function takes two arguments: the index number of the position the new element will be inserted, and the value of the new element.

import array as arr 

#original array
numbers = arr.array('i',[10,20,30])

#add the integer 40 in the first position
#remember indexing starts at 0

numbers.insert(0,40)

print(numbers)

#output

#array('i', [40, 10, 20, 30])

How to Remove a Value from an Array

To remove an element from an array, use the remove() method and include the value as an argument to the method.

import array as arr 

#original array
numbers = arr.array('i',[10,20,30])

numbers.remove(10)

print(numbers)

#output

#array('i', [20, 30])

With remove(), only the first instance of the value you pass as an argument will be removed.

See what happens when there are more than one identical values:


import array as arr 

#original array
numbers = arr.array('i',[10,20,30,10,20])

numbers.remove(10)

print(numbers)

#output

#array('i', [20, 30, 10, 20])

Only the first occurence of 10 is removed.

You can also use the pop() method, and specify the position of the element to be removed:

import array as arr 

#original array
numbers = arr.array('i',[10,20,30,10,20])

#remove the first instance of 10
numbers.pop(0)

print(numbers)

#output

#array('i', [20, 30, 10, 20])

Conclusion

And there you have it - you now know the basics of how to create arrays in Python using the array module. Hopefully you found this guide helpful.

You'll start from the basics and learn in an interacitve and beginner-friendly way. You'll also build five projects at the end to put into practice and help reinforce what you learned.

Thanks for reading and happy coding!

Original article source at https://www.freecodecamp.org

#python 

Web  Dev

Web Dev

1652837384

Build a Single Page App with Laravel 9, Jetstream, Vuejs, Inertiajs, MySQL, Tailwind CSS and Docker

In this tutorial, you will learn how to build a single page application. I'll take you through the process step by step, using cutting edge technologies like Laravel 9, Jetstream, Vuejs, Inertiajs, MySQL, Tailwind CSS, and Docker.

Let's get started.

What you need to follow this guide:

To follow along you will need:

  • a computer
  • to know how to install software
  • a basic understanding of HTML, CSS, JavaScript, and PHP
  • knowledge of at least one JavaScript framework and an understanding of the MVC design pattern.

This guide is organized into 10 chapters and is based off a live coding series that I record. The live coding series is completely unscripted, so there will be bugs and gotchas there that you won't find in this guide.

You can find the complete playlist at the end of this article.

Everything here should just work, but if it doesn't feel free to ask for help by joining my community on Slack. There you can share code snippets and chat with me directly.

Table of Contents

  • What Tech Are We Using?
  • How to Setup Your Machine
  • How to build the app with Laravel 9, Laravel Sail, Jetstram, Inertia and Vue3
  • How to Refactor the Admin Dashboard and Create New Admin Pages
  • How to Submit Forms with Files
  • How to Add the Form to the Component
  • How to Store Data
  • How to Update Operations
  • How to Delete a Resourse
  • Wrap up and what's next
  • Conclusion

Original article source at https://www.freecodecamp.org

What Tech Are We Using?

First, let's go over the different tools we'll be using in this project.

Docker

Docker is a set of platform as a service products that use OS-level virtualization to deliver software in packages called containers.

To simplify this concept, Docker lets you package applications and dependencies in a container.

A containerized application allows you to have a flexible development environment so that you can run different applications without worrying about dependencies, their requirements, and conflicts between different versions. You can easily run applications that, for instance, require two different versions of PHP and MySQL.

Each team member can quickly reproduce the same environment of your application by simply running the same container's configuration.

If you want to learn more about Docker, its Documentation is a great place to start.

Here's a Handbook on Docker essentials, as well, so you can practice your skills.

Mysql

MySQL is an open-source relational database management system. You can use it to organize data into one or more tables with data that may be related to each other.

We need to store data somewhere and here is where MySQL comes into play.

Here are the Docs if you want to read up more. Here's a full free course on MySQL if you want to dive deeper.

Laravel

Laravel is a free, open-source PHP web framework that helps you develop web applications following the model–view–controller architectural pattern.

Laravel is an amazing PHP framework that you can use to create bespoke web applications.

Here's the Laravel Documentation for more info, and here's a full project-based course to help you learn Laravel.

Laravel Sail

Laravel Sail is a lightweight command-line interface for interacting with Laravel's default Docker development environment.

Sail provides a great starting point for building a Laravel application using PHP, MySQL, and Redis without requiring prior Docker experience.

Usually, creating a development environment to build such applications means you have to install software, languages, and frameworks on your local machine – and that is time-consuming. Thanks to Docker and Laravel Sail we will be up and running in no time!

Laravel Sail is supported on macOS, Linux, and Windows via WSL2.

Here's the Documentation if you want to read up on it.

Laravel Jetstream

When building web applications, you likely want to let users register and log in to use your app. That is why we will use Jetstream.

Laravel Jetstream is a beautifully designed application starter kit for Laravel and provides the perfect starting point for your next Laravel application.

It uses Laravel Fortify to implement all the back end authentication logic.
Here are the Docs.

Vuejs

Vue.js is an open-source model–view–ViewModel front end JavaScript framework for building user interfaces and single-page applications.

Vue is a fantastic framework that you can use as a stand-alone to build single-page applications, but you can also use it with Laravel to build something amazing.

Here's the Vue Documentation if you want to read up. And here's a great Vue course to get you started.

Inertia JS

Inertia is the glue between Laravel and Vuejs that we will use to build modern single-page applications using classic server-side routing.

You can learn more about it in the Documentation here.

Tailwind

Tailwind CSS is a utility-first CSS framework packed with classes like flex, pt-4, text-center, and rotate-90 that you can use to build any design, directly in your markup

We'll use it in this project to build our design. Here's a quick guide to get you up and running if you aren't familiar with Tailwind.

How to Set Up Your Machine

To follow along with my live coding (and this tutorial), you will need to install Docker desktop on your machine. If you are using Windows, you will also need to enable WSL in your system settings.

Visit the Docker getting started page to install Docker Desktop.

If you are on Windows, enable WSL2 by following the steps here.

If you have any trouble, feel free to reach out or join my community on Slack to get help.

Laravel Installation with Sail

If you have successfully installed Docker Desktop on your machine, we can open the terminal and install Laravel 9.

Open a terminal window and browse to a folder where you want to keep your project. Then run the command below to download the latest Laravel files. The command will put all files inside a folder called my-example-app, which you can tweak as you like.

# Download laravel
curl -s "https://laravel.build/my-example-app" | bash
# Enter the laravel folder
cd my-example-app

Deploy Laravel on Docker using the sail up command

With Docker Desktop up and running, the next step is to start Laravel sail to build all the containers required to run our application locally.

Run the following command from the folder where all Laravel files have been downloaded:

vendor/bin/sail up

It will take a minute. Then visit http://localhost and you should see your Laravel application.

If you run sail up and you get the following error, it is likely that you need to update Docker Desktop:

ERROR: Service 'laravel.test' failed to build:

How to Build the App with Laravel 9, Laravel Sail, Jetstram, Inertia and Vue3

In this section, we will define a basic roadmap, install Laravel 9 with Laravel Sail, Run sail, and build the containers.

I will also take you on a tour of Laravel Sail and the sail commands.

Then we will install Jetstream and scaffold Vue and Inertia files and have a look at the files and available features.

Next, we will populate our database and add the front end provided by Jetstream to register an account and log into a fresh Laravel application.

Finally, we will have a look at the Jetstream dashboard, and the Inertia/Vue Components and then start playing around.

Along the way, we'll disable the registration, enable the Jetstream user profile picture feature, and then add our first Inertia page where we'll render some data taken from the database.

Here's the live coding video if you want to follow along that way:

 

And if you prefer following along in this written tutorial, here are all the steps.

Just a reminder – you should have Laravel installed with Sail and have Docker set up on your machine. You can follow the steps above to do so if you haven't already.

Laravel Sail Overview – Sail Commands

With Laravel Sail installed, our usual Laravel commands have sligtly changed.

For instance, instead of running the Laravel artisan command using PHP like php artisan, we now have to use Sail, like so: sail artisan.

The sail artisan command will return a list of all available Laravel commands.

Usually, when we work with Laravel, we also have to run the npm and composer commands.

Again, we need to prefix our commands with sail to make them run inside the container.

Below you'll find a list of some commands you will likely have to run:

# Interact with the database - run the migrations
sail artisan migrate # It was: php artisan migrate
# Use composer commands
sail composer require <packageName> # it was: composer require <packageName>
# Use npm commands
sail npm run dev # it was: npm run dev

You can read more in the Sail documentation.

Install Jetstream and Scaffold Vue and Inertia

Let's now install the Laravel Jetstream authentication package and use the Inertia scaffolding with Vue3.

cd my-example-app
sail composer require laravel/jetstream 

Remember to prefix the composer command with sail.

The command above has added a new command to Laravel. Now we need to run it to install all the Jetstream components:

sail artisan jetstream:install inertia

Next we need to compile all static assets with npm:

sail npm install
sail npm run dev

Before we can actually see our application, we will need to run the database migrations so that the session table, required by Jetstream, is present.

sail artisan migrate

Done! Jetstream is now installed in our application. If you visit http://localhost in your browser you should see the Laravel application with two links at the top to register and log in.

welcome-page

Populate the Database and Create a User Account

Before creating a new user, let's have a quick look at the database configuration that Laravel Sail has created for us in the .env file.

DB_CONNECTION=mysql
DB_HOST=mysql
DB_PORT=3306
DB_DATABASE=my-example-app
DB_USERNAME=sail
DB_PASSWORD=password

As you can see, Laravel Sail configures everything we need to access the database container that is running on Docker. The DB_DATABASE is the name of the database and it is the same as the project folder. This is why in the previous step we were able to run the migrate command without issues.

Since we already migrated all database tables, we can now use the Laravel built-in user factory to create a new user then use its details to log in our user dashboard.

Let's open artisan tinker to interact with our application.

sail artisan tinker

The command above will open a command line interface that we can use to interact with our application. Let's create a new user.

User::factory()->create()

The command above will create a new user and save its data in our database. Then it will render the user data onto the screen. Make sure to copy the user email so we can use it later to log in. Then exit by typing exit;.

The default password for every user created with a factory is password.

Let's visit the login page and access our application dashboard.

loginpage

Jetstream Dashboard

After login you are redirected to the Jetstream dashboard, which looks amazing by default. We can customize it as we like, but it is just a starting point.

dashboard

Jetstream/Vue Components and Inertia Overview

The first thing you may notice after installing Jetstram is that there are a number of Vue components registered in our application. Not only that, also Inertia brings in Vue components.

To use Inertia, we need to get familiar with it when defining routes.

When we installed Jetstream, it created inside the resources/js directory a number of subfolders where all our Vue components live. There are not just simple components but also Pages components rendered by inertia as our Views.

The Jetstream inertia scaffolding created:

  • resources/js/Jetstream Here we have 27 components used by Jetstream, but we can use them in our application too if we want.
  • resources/js/Layouts In this folder there is the layout component used by inertia to render the dashboard page
  • resources/js/Pages This is where we will place all our Pages (views) components. You will find the Dashboard page as well as the Laravel Welcome page components here.

The power of Inertia mostly comes from how it connects Vue and Laravel, letting us pass data (Database Models and more) as props to our Vue Pages components.

When you open the routes/web.php file you will notice that we no longer return a view but instead we use Inertia to render a Page component.

Let's examine the / homepage route that renders the Welcome component.

Route::get('/', function () {
    return Inertia::render('Welcome', [
        'canLogin' => Route::has('login'),
        'canRegister' => Route::has('register'),
        'laravelVersion' => Application::VERSION,
        'phpVersion' => PHP_VERSION,
    ]);
});

It looks like our usual Route definition, exept that in the closure we are returning an \Inertia\Response by calling the render method of the Inertia class Inertia::render().

This method accepts two parameters. The first is a component name. Here we passed the Welcome Page component, while the second parameter is an associative array that will turn into a list of props to pass to the component. Here is where the magic happens.

Looking inside the Welcome component, you will notice that in its script section, we simply define four props matching with the keys of our associative array. Then inertia will do the rest.

<script>
    import { defineComponent } from 'vue'
    import { Head, Link } from '@inertiajs/inertia-vue3';

    export default defineComponent({
        components: {
            Head,
            Link,
        },
        // 👇 Define the props 
        props: {
            canLogin: Boolean, 
            canRegister: Boolean,
            laravelVersion: String,
            phpVersion: String,
        }
    })
</script>

We can then just call the props inside the template. If you look at the template section you will notice that laravelVersion and phpVersion are referenced in the code as you normally would do with props in Vuejs.

<div class="ml-4 text-center text-sm text-gray-500 sm:text-right sm:ml-0">
  Laravel v{{ laravelVersion }} (PHP v{{ phpVersion }})
</div>

The dashboard component is a little different. In fact it uses the Layout defined under Layouts/AppLayout.vue and uses the Welcome component to render the Dashboard page content, which is the same as the laravel Welcome page.


<template>
    <app-layout title="Dashboard">
        <template #header>
            <h2 class="font-semibold text-xl text-gray-800 leading-tight">
                Dashboard
            </h2>
        </template>

        <div class="py-12">
            <div class="max-w-7xl mx-auto sm:px-6 lg:px-8">
                <div class="bg-white overflow-hidden shadow-xl sm:rounded-lg">
                    <welcome /> 
                </div>
            </div>
        </div>
    </app-layout>
</template>

Inside the layout component you will notice the two inertia components Head and Link.

We can use the Head component to add head elements to our page, like meta tags, page title, and so on. The Link component is a wrapper aroud a standard anchor tag that incercepts click events and prevents full page reload as you can read in the Inertia documentation.

Link Component
Head Component

Disable the Registration Feature

If you are following along, the next step I'll take is to disable one on the features Jetstream provides – register an account.

To do that, we can navigate to config/fortify.php and comment out line 135 Features::registration() from the features array.

'features' => [
        //Features::registration(),
        Features::resetPasswords(),
        // Features::emailVerification(),
        Features::updateProfileInformation(),
        Features::updatePasswords(),
        Features::twoFactorAuthentication([
            'confirmPassword' => true,
        ]),
    ],

If we visit the welcome page we will notice that the register link is gone. Also, the route is no longer listed when we run sail artisan route:list.

Enable Jetstream User Profile Picture

Now let's try to enable the Jetstream feature called ProfilePhotos. As you can guess, this will allow the user to add a profile picture.

To do that we need to visit config/jetstream.php and uncomment line 59 Features::profilePhoto.

    'features' => [
        // Features::termsAndPrivacyPolicy(),
        Features::profilePhotos(), // 👈
        // Features::api(),
        // Features::teams(['invitations' => true]),
        Features::accountDeletion(),
    ],

If you log in you will see that in the user profile, a new section is available to upload a profile picture.

But before doing anything else we need to run sail artisan storage:link so that Laravel creates a symlink to the storage/app/public folder where we will save all user profile images.

Now try to visit the user profile and update the profile picture. If you get a 404 on the image this is because by default Laravel sail assumes we are using Laravel valet and sets the app URL like so APP_URL=http://my-example-app.test in the .env file. Let's change it and use localhost instead.

APP_URL=http://localhost

Now we should be good to go and be able to see and change our profile image!🥳

How to Add our First Inertia Page and Render Records from the DB

Since we are rendering Vue components instead of blade views, it is wise to start sail npm run watch to watch and recompile our Vue components as we create or edit them. Next let's add a new Photos page.

I will start by creating a new Route inside web.php:

Route::get('photos', function () {
    //dd(Photo::all());
    return Inertia::render('Guest/Photos');
});

In the code above I defined a new GET route and then rendered a component that I will place inside the resources/js/Pages/Guest and call Photos. Let's create it.

Create a Guest folder:

cd resources/js/Pages
mkdir Guest
cd Guest
touch Photos.vue

Then let's define a basic component:

<template>
  <h1>Photos Page</h1>
</template>

If we visit http://localhost/photos/ we will see our new page, cool! Let's copy over the page structure from the Welcome page so that we get the login and dashboard links as well.

The component will change to this:

<template>
    <Head title="Phots" />

    <div class="relative flex items-top justify-center min-h-screen bg-gray-100 dark:bg-gray-900 sm:items-center sm:pt-0">
        <div v-if="canLogin" class="hidden fixed top-0 right-0 px-6 py-4 sm:block">
            <Link v-if="$page.props.user" :href="route('admin.dashboard')" class="text-sm text-gray-700 underline">
                Dashboard
            </Link>

            <template v-else>
                <Link :href="route('login')" class="text-sm text-gray-700 underline">
                    Log in
                </Link>

                <Link v-if="canRegister" :href="route('register')" class="ml-4 text-sm text-gray-700 underline">
                    Register
                </Link>
            </template>
        </div>

        <div class="max-w-6xl mx-auto sm:px-6 lg:px-8">
            <h1>Photos</h1>
            
        </div>
    </div>
</template>

<script>
    import { defineComponent } from 'vue'
    import { Head, Link } from '@inertiajs/inertia-vue3';

    export default defineComponent({
        components: {
            Head,
            Link,
        },

        props: {
            canLogin: Boolean,
            canRegister: Boolean,
          
        }
    })
</script>

The next step is to render a bunch of data onto this new page. For that we will build a Model and add some records to the database.

saild artisan make:model Photo -mfcr

This command creates a Model called Photo, plus a database migration table class, a factory, and a resource controller.

Now let's define the database table inside the migration we just creted. Visit the database/migrations folder and you should see a file with a name similar to this: 2022_02_13_215119_create_photos_table (yours will be sligly different).

Inside the migration file we can define a basic table like the following:

 public function up()
    {
        Schema::create('photos', function (Blueprint $table) {
            $table->id();
            $table->string('path');
            $table->text('description');
            $table->timestamps();
        });
    }

For our table we defined just two new columns, path and description, plus the id, created_at and updated_at that will be created by the $table->id() and by the $table->timestamps() methods.

After the migration we will define a seeder and then run the migrations and seed the database.

At the top of the database/seeders/PhotoSeeder.php file we will import our Model and Faker:

use App\Models\Photo;
use Faker\Generator as Faker;

Next we will implement the run method using a for loop to create 10 records in the database.



    public function run(Faker $faker)
    {
        for ($i = 0; $i < 10; $i++) {
            $photo = new Photo();
            $photo->path = $faker->imageUrl();
            $photo->description = $faker->paragraphs(2, true);
            $photo->save();
        }
    }

We are ready to run the migrations and seed the database.


sail artisan migrate
sail artisan db:seed --class PhotoSeeder

We are now ready to show the data on the Guest/Photos page component.
First update the route and pass a collection of Photos as props to the rendered component:

Route::get('photos', function () {
    //dd(Photo::all());
    return Inertia::render('Guest/Photos', [
        'photos' => Photo::all(), ## 👈 Pass a collection of photos, the key will become our prop in the component
        'canLogin' => Route::has('login'),
        'canRegister' => Route::has('register'),
    ]);
});

Second, pass the prop to the props in the script section of the Guest/Photos component:


props: {
    canLogin: Boolean,
    canRegister: Boolean,
    photos: Array // 👈 Here
}

Finally loop over the array and render all photos in the template section, just under the h1:

<section class="photos">
    <div v-for="photo in photos" :key="photo.id" class="card" >
        <img :src="photo.path" alt="">
    </div>
</section>

Done! if you visit the /photos page you should see ten photos. 🥳

How to Refactor the Admin Dashboard and Create New Admin Pages

In this chapter we will Re-route the Jetstream dashboard and make a route group for all admin pages.

Then we will see how to add a new link to the dashboard and add a new admin page.

Finally we will take a collection of data from the db and render them in a basic table. The default table isn't cool enough, so for those reading this article, I decided to add a Tailwind table component.

Re-route the Jetstream Dashboard

If we look at the config/fortify.php file we can see that around line 64 there is a key called home. It is calling the Home constant of the Route service provider.

This means that we can tweek the constant and redirect the authenticated user to a different route.

Lets go through it step-by-step:

  • update the HOME Constant
  • make a route group and redirect logged in users to admin/ instead of '/dashboard'

Our application will have only a single user, so once they're logged in it is clearly the site admin – so makes sense to redirect to an admin URI.

Change the HOME constant in app/Providers/RouteServiceProvider.php around line 20 to match the following:

public const HOME = '/admin';

How to Add an Admin Pages Route Group

Next let's update our route inside web.php. We will change the route registered by Jetstream from this:

Route::middleware(['auth:sanctum', 'verified'])->get('/', function () {
        return Inertia::render('Dashboard');
    })->name('dashboard');

To this:

Route::middleware(['auth:sanctum', 'verified'])->prefix('admin')->name('admin.')->group(function () {

    Route::get('/', function () {
        return Inertia::render('Dashboard');
    })->name('dashboard');

    // other admin routes here
});

The route above is a route group that uses the auth:sanctum middleware for all routes within the group, a prefix of admin, and adds a admin suffix to each route name.

The end result is that we will be able to refer to the dashboard route by name, which now will be admin.dashboard. When we log in, we will be redirected to the admin route. Our dashboard route will respond since it's URI is just / but the goup prefix will prefix every route in the group and make their URI start with admin.

If you now run sail artisan route:list you will notice that the dashboard route has changed as we expected.

Before moving to the next step we need to update both the /layouts/AppLayout.vue and /Pages/Welcome.vue components.

Do you remeber that the dashboard route name is now admin.dashboard and not just dashboard?

Let's inspect the two components and update every reference of route('dahsboard') to this:

route('admin.dahsboard')

and also every reference of route().current('dashboard') to this:

route().current('admin.dashboard')

After all the changes, make sure to recompile the Vue components and watch changes by running sail npm run watch. Then visit the home page to check if everything is working.

How to Add a New Link to the Dashboard

Now, to add a new admin page where we can list all photos stored in the database, we need to add a new route to the group we created earlier. Let's hit the web.php file and make our changes.

In the Route group we will add a new route:

Route::middleware(['auth:sanctum', 'verified'])->prefix('admin')->name('admin.')->group(function () {

    Route::get('/', function () {
        return Inertia::render('Dashboard');
    })->name('dashboard');

    // 👇 other admin routes here 👇

    Route::get('/photos', function () {
        return inertia('Admin/Photos');
    })->name('photos'); // This will respond to requests for admin/photos and have a name of admin.photos

});

In the new route above we used the inertia() helper function that does the same exact thing – returns an Inertia/Response and renders our Page component. We placed the component under an Admin folder inside Pages and we will call it Photos.vue.

Before we create the component, let's add a new link to the dashboard that points to our new route.

Inside AppLayout.vue, find the Navigation Links comment and copy/paste the jet-nav-link component that is actually displaing a link to the dashboard and make it point to our new route.

You will end up having something like this:

<!-- Navigation Links -->
<div class="hidden space-x-8 sm:-my-px sm:ml-10 sm:flex">
    <jet-nav-link :href="route('admin.dashboard')" :active="route().current('admin.dashboard')">
        Dashboard
    </jet-nav-link>
    <!-- 👇 here it is our new link -->
      <jet-nav-link :href="route('admin.photos')" :active="route().current('admin.photos')">
        Photos
    </jet-nav-link>
</div>

Our link above uses route('admin.photos') to point to the correct route in the admin group.

If you visit localhost/dashboard and open the inspector, you should see an error:

Error: Cannot find module `./Photos.vue`

It is fine – we haven't created the Photos page component yet. So let's do it now!

How to Add a New Admin Page Component

Make a file named Photos.vue inside the Pages/Admin folder. Below are the bash commands to create the folder and the file via terminal, but you can do the same using your IDE's graphical interface.

cd resources/js/Pages
mkdir Admin
touch Admin/Photos.vue

To make this new page look like the Dashboard page, we will copy over its content. You should end up having something like this:


<template>
  <app-layout title="Dashboard"> <!-- 👈 if you want you can update the page title -->
    <template #header>
      <h2 class="font-semibold text-xl text-gray-800 leading-tight">Photos</h2>
    </template>

    <div class="py-12">
      <div class="max-w-7xl mx-auto sm:px-6 lg:px-8">
        <div class="bg-white overflow-hidden shadow-xl sm:rounded-lg">
          <!-- 👇  All photos for the Admin page down here -->
          <h1 class="text-2xl">Photos</h1>
           
        </div>
      </div>
    </div>
  </app-layout>
</template>

<script>
import { defineComponent } from "vue";
import AppLayout from "@/Layouts/AppLayout.vue";

export default defineComponent({
  components: {
    AppLayout,
  },
});
</script>

I removed a few pieces from the Dashboard template so make sure to double check the code above. The welcome component was removed from the template as it is not required in this page, and also its reference in the script section. The rest is identical.

Feel free to update the page title referenced as prop on the <app-layout title="Dashboard">.

Now when you visit localhost/admin you can click on the Photos menu item and see our Photos page component content. It's not much for now, just an h1.

How to Render Records in the Admin Page as a Table

Now it's time to render the data onto a table. To make things work let's first add our markup and fake that we already have access to as an array of objects and loop over them inside our table. Than we will figure out how to make things work for real.

 <table class="table-auto w-full text-left">
  <thead>
    <tr>
      <th>ID</th>
      <th>Photo</th>
      <th>Desciption</th>
      <th>Actions</th>
    </tr>
  </thead>
  <tbody>
    <tr v-for="photo in photos">
      <td>{{ photo.id }}</td>
      <td><img width="60" :src="photo.path" alt="" /></td>
      <td>{{photo.description}}</td>
      <td>View - Edit - Delete</td>

    </tr>
  </tbody>
</table>

Ok, since we assumed that our component has access to a list of Photos, let's pass a new prop to the component from the Route.

Update the route in web.php and pass to the inertia() function a second argument that will be an associative array. It will have its keys passed as props to the Vue Page component.

In it we will call Photo::all() to have a collection to assign to a photos key, but you can use other eloquent methods if you want to paginate the results, for example.

Route::get('/photos', function () {
    return inertia('Admin/Photos', [
        'photos' => Photo::all()
    ]);
})->name('photos');

To connect the prop to our Page component we need to define the prop also inside the component.

<script>
import { defineComponent } from "vue";
import AppLayout from "@/Layouts/AppLayout.vue";

export default defineComponent({
  components: {
    AppLayout,
  },
  /* 👇 Pass the photos array as a props 👇 */
  props: {
    photos: Array,
  },
});
</script>

Extra: How to use a Tailwind table component

Tailwind is a CSS framework similar to Bootstrap. There are a number of free to use components that we can grab from the documentation, tweak, and use.

This table component is free and looks nice:https://tailwindui.com/components/application-ui/lists/tables.

We can tweek the Photos page template and use the Tailwind table component to get a nice looking table like so:


<template>
    <app-layout title="Dashboard">
        <template #header>
            <h2 class="font-semibold text-xl text-gray-800 leading-tight">Photos</h2>
        </template>

         <div class="py-12">
            <div class="max-w-7xl mx-auto sm:px-6 lg:px-8">
              <!-- All posts goes here -->
              <h1 class="text-2xl">Photos</h1>
              <a class="px-4 bg-sky-900 text-white rounded-md" href>Create</a>
              <div class="flex flex-col">
                  <div class="-my-2 overflow-x-auto sm:-mx-6 lg:-mx-8">
                      <div class="py-2 align-middle inline-block min-w-full sm:px-6 lg:px-8">
                          <div class="shadow overflow-hidden border-b border-gray-200 sm:rounded-lg">
                              <table class="min-w-full divide-y divide-gray-200">
                                  <thead class="bg-gray-50">
                                      <tr>
                                          <th
                                              scope="col"
                                              class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"
                                          >ID</th>
                                          <th
                                              scope="col"
                                              class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"
                                          >Photos</th>
                                          <th
                                              scope="col"
                                              class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"
                                          >Description</th>
                                          <th scope="col" class="relative px-6 py-3">
                                              <span class="sr-only">Edit</span>
                                          </th>
                                      </tr>
                                  </thead>
                                  <tbody class="bg-white divide-y divide-gray-200">
                                      <tr v-for="photo in photos" :key="photo.id">
                                          <td class="px-6 py-4 whitespace-nowrap">
                                              <div
                                                  class="text-sm text-gray-900"
                                              >{{ photo.id }}</div>
                                          </td>

                                          <td class="px-6 py-4 whitespace-nowrap">
                                              <div class="flex items-center">
                                                  <div class="flex-shrink-0 h-10 w-10">
                                                      <img
                                                          class="h-10 w-10 rounded-full"
                                                          :src="photo.path"
                                                          alt
                                                      />
                                                  </div>
                                              </div>
                                          </td>

                                          <td class="px-6 py-4 whitespace-nowrap">
                                              <div class="text-sm text-gray-900">
                                                {{ photo.description.slice(0, 100) + '...' }}
                                              </div>
                                          </td>
                                        <!-- ACTIONS -->
                                          <td class="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
                                              <a href="#" class="text-indigo-600 hover:text-indigo-900">
                                              View - Edit - Delete
                                              </a>
                                          </td>
                                      </tr>
                                  </tbody>
                              </table>
                          </div>
                      </div>
                  </div>
                </div>
            </div>
        </div>
    </app-layout>
</template>

How to Submit Forms with Files

For the next section we will look into how to submit a form so that we can add a new photo to the database.

  • Add a create button
  • Add a create route
  • Define the PhotosCreate component
  • Add a form
  • Validate data
  • Show validation errors
  • Save the file to the filesystem
  • Save the model

How to Create a New Photo

Add a link that points to a create route:

<a class="px-4 bg-sky-900 text-white rounded-md" :href="route('admin.photos.create')">Create</a>

Create the route within the admin group:

Route::get('/photos/create', function () {
    return inertia('Admin/PhotosCreate');
})->name('photos.create');

Let's add also the route that will handle the form submission for later:

Route::post('/photos', function () {
    dd('I will handle the form submission')   
})->name('photos.store');

Create the Admin/PhotosCreate.vue component:


    <template>
    <app-layout title="Dashboard">
        <template #header>
            <h2 class="font-semibold text-xl text-gray-800 leading-tight">Photos</h2>
        </template>

         <div class="py-12">
            <div class="max-w-7xl mx-auto sm:px-6 lg:px-8">
                <h1 class="text-2xl">Add a new Photo</h1>
                <!-- 👇 Photo creation form goes here -->

            </div>
        </div>
    </app-layout>
</template>


<script>
import { defineComponent } from "vue";
import AppLayout from "@/Layouts/AppLayout.vue";

export default defineComponent({
  components: {
    AppLayout,
  },

});
</script>

How to Add the Form to the Component

The next step is to add the form to the page and figure out how to submit it.

If you hit the Inertia documentation you will find out that there is a useForm class that we can use to simplify the process.

First, import the module inside the script tag of the Admin/PhotosCreate.vue component:

import { useForm } from '@inertiajs/inertia-vue3';

Next we can use it in the setup function (Vue 3 composition API):

setup () {
    const form = useForm({
      path: null,
      description: null,
    })

    return { form }
  }

In the code above we defined the function called setup() then a constant called form to have the useForm() class assigned to it.

Inside its parentheses we defined two properties, path and description which are the column names of our photos model.

Finally we returned the form variable for the setup function. This is to make the variable available inside our template.

Next we can add the form markup:

<form @submit.prevent="form.post(route('admin.photos.store'))">

<div>
    <label for="description" class="block text-sm font-medium text-gray-700"> Description </label>
    <div class="mt-1">
        <textarea id="description" name="description" rows="3" class="shadow-sm focus:ring-indigo-500 focus:border-indigo-500 mt-1 block w-full sm:text-sm border border-gray-300 rounded-md" placeholder="lorem ipsum" v-model="form.description"/>
    </div>
    <p class="mt-2 text-sm text-gray-500">Brief description for your photo</p>
        <div class="text-red-500" v-if="form.errors.description">{{form.errors.description}}</div>
</div>
<div>
    <label class="block text-sm font-medium text-gray-700"> Photo </label>
    <div class="mt-1 flex justify-center px-6 pt-5 pb-6 border-2 border-gray-300 border-dashed rounded-md">
    <div class="space-y-1 text-center">
        <svg class="mx-auto h-12 w-12 text-gray-400" stroke="currentColor" fill="none" viewBox="0 0 48 48" aria-hidden="true">
        <path d="M28 8H12a4 4 0 00-4 4v20m32-12v8m0 0v8a4 4 0 01-4 4H12a4 4 0 01-4-4v-4m32-4l-3.172-3.172a4 4 0 00-5.656 0L28 28M8 32l9.172-9.172a4 4 0 015.656 0L28 28m0 0l4 4m4-24h8m-4-4v8m-12 4h.02" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" />
        </svg>
        <div class="flex text-sm text-gray-600">
        <label for="path" class="relative cursor-pointer bg-white rounded-md font-medium text-indigo-600 hover:text-indigo-500 focus-within:outline-none focus-within:ring-2 focus-within:ring-offset-2 focus-within:ring-indigo-500">
            <span>Upload a file</span>
            <input id="path" name="path" type="file" class="sr-only" @input="form.path = $event.target.files[0]" />
        </label>
        <p class="pl-1">or drag and drop</p>
        </div>
        <p class="text-xs text-gray-500">PNG, JPG, GIF up to 10MB</p>
    </div>
    </div>
</div>
<div class="text-red-500" v-if="form.errors.path">{{form.errors.path}}</div>

<button type="submit" :disabled="form.processing" class="inline-flex justify-center py-2 px-4 border border-transparent shadow-sm text-sm font-medium rounded-md text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500">Save</button>
</form>

The code above uses the Vue v-on directive short end syntax @submit.prevent="form.post(route('admin.photos.store'))" on the form tag, and the dom event submit with the prevent modifier.

Then it uses the form variable that we created earlier and a post method. This is available because we are using the useForm class.

Next we point the form to the route named admin.photos.store that we created earlier.

Inside the form we have two groups of inputs. First, we have the textarea that uses the v-model to bind it to the property form.description that we declared before.

The second group uses the form.path in a Tailwind component (showing the markup for a drop file area).

Right now we are allowing users to upload only a single photo using the v-on directive on the input DOM event @input="form.path = $event.target.files[0]".

The last two things to notice are the error handling done via <div class="text-red-500" v-if="form.errors.path">{{form.errors.path}}</div> for the path and also for the description.

Finally we use form.processing to disable the submit button while the form is processing.

The next step is to define the logic to save the data inside the database.

How to Store Data

To store the data, we can edit the route we defined earlier like so:

Route::post('/photos', function (Request $request) {
    //dd('I will handle the form submission')  
    
    //dd(Request::all());
    $validated_data = $request->validate([
        'path' => ['required', 'image', 'max:2500'],
        'description' => ['required']
    ]);
    //dd($validated_data);
    $path = Storage::disk('public')->put('photos', $request->file('path'));
    $validated_data['path'] = $path;
    //dd($validated_data);
    Photo::create($validated_data);
    return to_route('admin.photos');
})->name('photos.store');

The code above uses dependency injection to allow us to use the parameter $request inside the callback function.

We first validate the request and save the resulting array inside the variable $validated_data. Then we use the Storage facades to save the file in the filesystem and obtain the file path that we store inside the $path variable.

Finally we add a path key to the associative array and pass to it the $path variable. Next we create the resource in the database using the Photo::create method and redirect the user to the admin.photos page using the new to_route() helper function.

Make sure to import the Request class and the Storage facades at the top of the web.php file like so:

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

Now we can add a new photo in the database and show a list of photos for both the admin and standard visitors.

Next we need to complete the CRUD operations and allow the user to edit/update a photo and delete it.

How to Update Operations

Let's start by adding the routes responsible for showing the forms used to edit the resource and update its values onto the database.

Just under the other routes in the Admin group, let's add the following code:


Route::get('/photos/{photo}/edit', function(Photo $photo){
     return inertia('Admin/PhotosEdit', [
            'photo' => $photo
        ]);
})->name('photos.edit');

The route above uses dependency injection to inject inside the function the current post, selected by the URI /photos/{photo}/edit.

Next it returns the Inertia response via the inertia() function that accepts the Component name 'Admin/PhotosEdit' as its first parameter and an associative array as its second.

Doing ['photo' => $photo] will allow us to pass the $photo model as a prop to the component later.

Next let's add the new Page component under resources/js/Pages/Admin/PhotosEdit.vue

This will be its template:

<template>
    <app-layout title="Edit Photo">
        <template #header>
            <h2 class="font-semibold text-xl text-gray-800 leading-tight">Edit Photo</h2>
        </template>
        <div class="py-12">
            <div class="max-w-7xl mx-auto sm:px-6 lg:px-8">
                <form @submit.prevent="form.post(route('admin.photos.update', photo.id))">
                    <div>
                        <label
                            for="description"
                            class="block text-sm font-medium text-gray-700"
                        >Description</label>
                        <div class="mt-1">
                            <textarea
                                id="description"
                                name="description"
                                rows="3"
                                class="shadow-sm focus:ring-indigo-500 focus:border-indigo-500 mt-1 block w-full sm:text-sm border border-gray-300 rounded-md"
                                placeholder="lorem ipsum"
                                v-model="form.description"
                            />
                        </div>
                        <p class="mt-2 text-sm text-gray-500">Brief description for your photo</p>
                        <div
                            class="text-red-500"
                            v-if="form.errors.description"
                        >{{ form.errors.description }}</div>
                    </div>

                    <div class="grid grid-cols-2">
                        <div class="preview p-4">
                            <img :src="'/storage/' + photo.path" alt />
                        </div>
                        <div>
                            <label class="block text-sm font-medium text-gray-700">Photo</label>
                            <div
                                class="mt-1 flex justify-center px-6 pt-5 pb-6 border-2 border-gray-300 border-dashed rounded-md"
                            >
                                <div class="space-y-1 text-center">
                                    <svg
                                        class="mx-auto h-12 w-12 text-gray-400"
                                        stroke="currentColor"
                                        fill="none"
                                        viewBox="0 0 48 48"
                                        aria-hidden="true"
                                    >
                                        <path
                                            d="M28 8H12a4 4 0 00-4 4v20m32-12v8m0 0v8a4 4 0 01-4 4H12a4 4 0 01-4-4v-4m32-4l-3.172-3.172a4 4 0 00-5.656 0L28 28M8 32l9.172-9.172a4 4 0 015.656 0L28 28m0 0l4 4m4-24h8m-4-4v8m-12 4h.02"
                                            stroke-width="2"
                                            stroke-linecap="round"
                                            stroke-linejoin="round"
                                        />
                                    </svg>
                                    <div class="flex text-sm text-gray-600">
                                        <label
                                            for="path"
                                            class="relative cursor-pointer bg-white rounded-md font-medium text-indigo-600 hover:text-indigo-500 focus-within:outline-none focus-within:ring-2 focus-within:ring-offset-2 focus-within:ring-indigo-500"
                                        >
                                            <span>Upload a file</span>
                                            <input
                                                id="path"
                                                name="path"
                                                type="file"
                                                class="sr-only"
                                                @input="form.path = $event.target.files[0]"
                                            />
                                        </label>
                                        <p class="pl-1">or drag and drop</p>
                                    </div>
                                    <p class="text-xs text-gray-500">PNG, JPG, GIF up to 10MB</p>
                                </div>
                            </div>
                            <div class="text-red-500" v-if="form.errors.path">{{ form.errors.path }}</div>
                        </div>
                    </div>

                    <button
                        type="submit"
                        :disabled="form.processing"
                        class="inline-flex justify-center py-2 px-4 border border-transparent shadow-sm text-sm font-medium rounded-md text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"
                    >Update</button>
                </form>
            </div>
        </div>
    </app-layout>
</template>

The template is actually identical to the Create component, except for a few things. The form points to a route that expects a paramenter that we pass as the second argument to the funtion route. It looks like this: <form @submit.prevent="form.post(route('admin.photos.update', photo.id))">.

There is a section where we can see the original photo next to the upload form group:

 <div class="preview p-4">
    <img :src="'/storage/' + photo.path" alt />
</div>

The rest is identical, and here we have the script section:

import { defineComponent } from "vue";
import AppLayout from "@/Layouts/AppLayout.vue";
import { useForm } from '@inertiajs/inertia-vue3';

export default defineComponent({
    components: {
        AppLayout,
    },
    props: {
        photo: Object
    },
    setup(props) {
        const form = useForm({
            _method: "PUT",
            path: null,
            description: props.photo.description,
        })

        return { form }
    },

});

Notice that we are passing a props object with the photo key, which allows us to reference the model in the template.

Next, this _method: "PUT", line of code is required to be able to submit a PUT request instead of the POST request called on the form tag.

Now let's implement the logic to handle the form submission inside the Route below.

In web.php just under the previous route, let's add one that responds to the PUT request submitted by our form.

Route::put('/photos/{photo}', function (Request $request, Photo $photo)
    {
        //dd(Request::all());

        $validated_data = $request->validate([
            'description' => ['required']
        ]);

        if ($request->hasFile('path')) {
            $validated_data['path'] = $request->validate([
                'path' => ['required', 'image', 'max:1500'],

            ]);

            // Grab the old image and delete it
            // dd($validated_data, $photo->path);
            $oldImage = $photo->path;
            Storage::delete($oldImage);

            $path = Storage::disk('public')->put('photos', $request->file('path'));
            $validated_data['path'] = $path;
        }

        //dd($validated_data);

        $photo->update($validated_data);
        return to_route('admin.photos');
    })->name('photos.update');


The route logic is straigthforward. First we validate the description, next we check if a file was uploaded and if so we validate it.

Then we delete the previously uploaded image Storage::delete($oldImage); before storing the new image onto the datadabse and update the resource using $photo->update($validated_data);.

As before with the store route, we redirect to the admin.photos route using return to_route('admin.photos');.

How to Delete a Resource

The last step we need to take is to write the logic to delete the photo. Let's start by adding the route.

Right below the previous route we can write:

Route::delete('/photos/{photo}', function (Photo $photo)
{
    Storage::delete($photo->path);
    $photo->delete();
    return to_route('admin.photos');
})->name('photos.delete');

This route is also using a wildcard in its URI to identify the resource. Next, its second paramenter is the callback that uses the dependency injection as before. Inside the callback we first delete the image from the filesystem using Storage::delete($photo->path);.

Then we remove the resource from the database $photo->delete(); and redirect the user back return to_route('admin.photos'); like we did in the previous reoute.

Now we need to add a delete button to the table we created in one of the previous steps to show all photos.

Inside the template section of the component Admin/Photos.vue within the v-for, we can add this Jetstream button:


<jet-danger-button @click="delete_photo(photo)">
    Delete
</jet-danger-button>

Find the table cell that has the ACTIONS comment and replace the DELETE text with the button above.

So the final code will be:

<td class="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
    <a href="#" class="text-indigo-600 hover:text-indigo-900">
    View - Edit - 

    <jet-danger-button @click="delete_photo(photo)">
        Delete
    </jet-danger-button>
    </a>
</td>

As you can see there is a @click event listener on the button. It calls a method delete_photo(photo) that we need to define along with a bunch of other methods to have a nice modal opening to ask for confirmation from the user.

First import the Inertia helper function useForm:

// 0. Import the useForm class at the top of the script section along with all required components
import { useForm } from '@inertiajs/inertia-vue3';
import JetDangerButton from '@/Jetstream/DangerButton.vue'
import { ref } from "vue";

Remember to register the component JetDangerButton inside the components object before moving forward.

Next add the setup() function in the script section and implement the logic required to submit the form and show a modal. The comments in the code will guide you thorought all the steps.

// 1. add the setup function
setup() {
    // 2. declare a form variable and assign to it the Inertia useForm() helper function 
    const form = useForm({
        // 3. override the form method to make a DELETE request
        _method: "DELETE",
    });
    // 4. define a reactive object with show_modal and photo property
    // this will be used to figure out when to show the modal and the selected post values
    const data = ref({
        show_modal: false,
        photo: {
            id: null,
            path: null,
            description: null,
        }
    })

    // 5. define the delete_photo function and update the values of the show_modal and photo properties
    // of the reactive object defined above. This method is called by the delete button and will record the details 
    // of the selected post
    const delete_photo = (photo) => {
        //console.log(photo);
        //console.log(photo.id, photo.path, photo.description);
        data.value = {
            photo: {
                id: photo.id,
                path: photo.path,
                description: photo.description
            },
            show_modal: true
        };
    }
    // 6. define the method that will be called when our delete form is submitted
    // the form will be created next
    const deleting_photo = (id) => {
        form.post(route('admin.photos.delete', id))
        closeModal();
    }
    // 7. delare a method to close the modal by setting the show_modal to false
    const closeModal = () => {
        data.value.show_modal = false;
    }
    // 8. remember to return from the setup function the all variables and methods that you want to expose 
    // to the template.
    return { form, data, closeModal, delete_photo, deleting_photo }

}

Finally outside the v-for loop add the modal using the following code. You can place this where you want but not inside the loop.


 <JetDialogModal :show="data.show_modal">
    <template #title>
        Photo {{ data.photo.description.slice(0, 20) + '...' }}
    </template>
    <template #content>
        Are you sure you want to delete this photo?

    </template>
    <template #footer>
        <button @click="closeModal" class="px-4 py-2">Close</button>
        <form @submit.prevent="deleting_photo(data.photo.id)">
            <jet-danger-button type="submit">Yes, I am sure!</jet-danger-button>
        </form>
    </template>
</JetDialogModal>

This is our final JavaScript code:

import { defineComponent } from "vue";
import AppLayout from "@/Layouts/AppLayout.vue";
import TableComponent from "@/Components/TableComponent.vue";
import { Link } from '@inertiajs/inertia-vue3';
import { useForm } from '@inertiajs/inertia-vue3';
import JetDialogModal from '@/Jetstream/DialogModal.vue';
import JetDangerButton from '@/Jetstream/DangerButton.vue'
import { ref } from "vue";
export default defineComponent({
    components: {
        AppLayout,
        Link,
        TableComponent,
        JetDialogModal,
        JetDangerButton
    },
    props: {
        photos: Array,
    },

    setup() {

        const form = useForm({
            _method: "DELETE",
        });
        const data = ref({
            show_modal: false,
            photo: {
                id: null,
                path: null,
                description: null,
            }

        })


        const delete_photo = (photo) => {
            //console.log(photo);
            console.log(photo.id, photo.path, photo.description);
            data.value = {
                photo: {
                    id: photo.id,
                    path: photo.path,
                    description: photo.description
                },
                show_modal: true
            };
        }
        const deleting_photo = (id) => {
            form.post(route('admin.photos.delete', id))
            closeModal();
        }

        const closeModal = () => {
            data.value.show_modal = false;


        }

        return { form, data, closeModal, delete_photo, deleting_photo }

    }
});
</script>

And here we have the HTML:

<template>
    <app-layout title="Dashboard">
        <template #header>
            <h2 class="font-semibold text-xl text-gray-800 leading-tight">Photos</h2>
        </template>

         <div class="py-12">
            <div class="max-w-7xl mx-auto sm:px-6 lg:px-8">
              <!-- All posts goes here -->
              <h1 class="text-2xl">Photos</h1>
              <a class="px-4 bg-sky-900 text-white rounded-md" href>Create</a>
              <div class="flex flex-col">
                  <div class="-my-2 overflow-x-auto sm:-mx-6 lg:-mx-8">
                      <div class="py-2 align-middle inline-block min-w-full sm:px-6 lg:px-8">
                          <div class="shadow overflow-hidden border-b border-gray-200 sm:rounded-lg">
                              <table class="min-w-full divide-y divide-gray-200">
                                  <thead class="bg-gray-50">
                                      <tr>
                                          <th
                                              scope="col"
                                              class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"
                                          >ID</th>
                                          <th
                                              scope="col"
                                              class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"
                                          >Photos</th>
                                          <th
                                              scope="col"
                                              class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"
                                          >Description</th>
                                          <th scope="col" class="relative px-6 py-3">
                                              <span class="sr-only">Edit</span>
                                          </th>
                                      </tr>
                                  </thead>
                                  <tbody class="bg-white divide-y divide-gray-200">
                                      <tr v-for="photo in photos" :key="photo.id">
                                          <td class="px-6 py-4 whitespace-nowrap">
                                              <div
                                                  class="text-sm text-gray-900"
                                              >{{ photo.id }}</div>
                                          </td>

                                          <td class="px-6 py-4 whitespace-nowrap">
                                              <div class="flex items-center">
                                                  <div class="flex-shrink-0 h-10 w-10">
                                                      <img
                                                          class="h-10 w-10 rounded-full"
                                                          :src="photo.path"
                                                          alt
                                                      />
                                                  </div>
                                              </div>
                                          </td>

                                          <td class="px-6 py-4 whitespace-nowrap">
                                              <div class="text-sm text-gray-900">
                                                {{ photo.description.slice(0, 100) + '...' }}
                                              </div>
                                          </td>
                                        <!-- ACTIONS -->
                                         <td class="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
                                            <a href="#" class="text-indigo-600 hover:text-indigo-900">
                                            View - Edit - 

                                            <jet-danger-button @click="delete_photo(photo)">
                                                Delete
                                            </jet-danger-button>
                                            </a>
                                        </td>
                                      </tr>
                                  </tbody>
                              </table>
                          </div>
                      </div>
                  </div>
                </div>
            </div>
        </div>
         <JetDialogModal :show="data.show_modal">
            <template #title>
                Photo {{ data.photo.description.slice(0, 20) + '...' }}
            </template>
            <template #content>
                Are you sure you want to delete this photo?

            </template>
            <template #footer>
                <button @click="closeModal" class="px-4 py-2">Close</button>
                <form @submit.prevent="deleting_photo(data.photo.id)">
                    <jet-danger-button type="submit">Yes, I am sure!</jet-danger-button>
                </form>
            </template>
        </JetDialogModal>
    </app-layout>
</template>

That's it. If you did everything correctly you should be able to see all photos, create new photos as well as edit and delete them.

I will leave you some home work. Can you figure out how to implement the view and edit links before the delete button in the section below?

<!-- ACTIONS -->
<td class="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
    <a href="#" class="text-indigo-600 hover:text-indigo-900">
    View - Edit - 

    <jet-danger-button @click="delete_photo(photo)">
        Delete
    </jet-danger-button>
    </a>
</td>

Wrapup and What's next

During this guide we took our first steps and learned how to build a single page application using Laravel as our backend framework and Vue3 for the front end. We glued them together with Inertia js and built a simple photo application that lets a user manage photos.

We are just at the beginning of a fantastic journey. Learning new technologies isn't easy, but thanks to their exaustive documentations we can keep up and build awesome applications.

Your next step to master Laravel, Vue3, Inertia and all the tech we have been using so far is to hit their documentation and keep learning. Use the app we have build if you want, and improve it or start over from scratch.

Conclusion

This is just an overview of how I'd build a single page application using these technologies.

If you are familiar with server-side routing and Vuejs then you will enjoy bulding a single page application with Laravel, Inertia, and Vuejs. The learning curve isn't that steep plus you have great documentation to help you out.

You can find the source code for this guide here.

#laravel #laravel9 #jetstream #vuejs #inertiajs #mysql #tailwindcss #docker
 

Understanding CSS's !important declaration

!important in CSS is a special notation that we can apply to a CSS declaration to override other conflicting rules for the matching selector.

When we work on web projects, it is natural that we have some style declarations that other styles overrule.

This is not an issue for an experienced developer who understands the core mechanism of CSS. However, it can be difficult for beginners to understand why the style declarations they expect are not applied by the browser.

So, instead of them focusing on resolving the issue naturally, they tend to go for the quick fix by adding the !important declaration to enforce the style they expect. While this approach might work for that moment, it can also initiate another complex problem.

In this guide, we will review the following, including how to use !important and when we should use it:

  • The CSS core mechanism
  • Understanding the !important declaration before we use it
  • :is() and other related pseudo-class functions
  • When exactly can we use !importantdeclaration?
    • Utility classes
    • The style rules we cannot override

Enough said, let’s dive in.

The CSS core mechanism

Understanding the core principles of CSS will naturally enable us to know when it’s obvious to use the !important declaration. In this section, we will walk through some of these mechanisms.

Consider the HTML and CSS code below, what color do you think the heading text will be?

First, the HTML:

<h2 class="mytitle">This is heading text</h2>

Then, the CSS:

h2 {
  color: blue;
}
h2 {
  color: green;
}

The text will render green! This is basic CSS fundamental. With the CSS cascade algorithm, the ordering of CSS rules matters. In this case, the declaration that comes last in the source code wins.

Normally, this is logical. In the first place, we should not repeat the same selector as we did above. CSS does not want repetition, so it uses the last declaration rule.

However, there are cases whereby we create generic styles for the root elements, like the h2, and then add classes to style specific elements. Let’s consider the following example as well, starting with the HTML:

<h2>This is heading text</h2>
<h2 class="mytitle">This is heading text</h2>

Then, let’s see the CSS:

.mytitle {
  color: blue;
}
h2 {
  color: green;
}

In the above code, the first h2 element has no class applied, so it is obvious that it gets the green color of the h2 selector.

However, the second h2 element uses the rule for the class selector, .mytitle, even when the element selector rule comes last in the CSS code. The reason for that is that the class selector has a higher specificity when compared to the element selector.

In other words, the weight applied to the declaration in a class selector is more than element selector’s weight.

Similarly, the declaration in an ID selector is more than that of the class selector. In this case, the red color in the code below takes precedence:

<h2 id="maintitle" class="mytitle">This is heading text</h2> 

Followed by the CSS:

.mytitle {
  color: blue;
}
#maintitle {
  color: red;
}
h2 {
  color: green;
}

Furthermore, an inline style attribute takes precedence over the ID selector, starting with the HTML:

<h2 id="maintitle" style="color: black;" class="mytitle">This is heading text</h2> 

 

Then followed by the CSS:

.mytitle {/*...*/}

#maintitle {/*...*/}

h2 {/*...*/}

This is the ideal priority flow in CSS and must be maintained to avoid anomalies. The !important declaration most of the time comes when we are oblivious of these basic rules.

The inline style attribute and each of the selectors have values that browsers assign to them. That way, it knows which one has higher or lower priority. Think of this value as a number of four single digits with the style attribute assigned the strongest weight value of 1000.

This follows the ID with a value of 0100, then class with 0010, and finally the element selector with 0001.

Sometimes we can combine selectors targeting specific elements, as seen in the example below:

<h2 id="maintitle" class="mytitle">This is heading text</h2> 

 

Followed by the CSS:

h2.mytitle {
  color: blue;
}
#maintitle {
  color: red;
}
h2 {
  color: green;
}

The specificity of the h2.mytitle selector in the CSS above is the addition of h2 and .mytitle. That is, 0001 + 0010 = 0011. This total value, however, is less than that of the #maintitle ID that is 0100.

So, the browser uses the declaration in the ID selector to override other conflicting rules. In a case of equal weight, the last rule declaration wins.

Now that we know which rules are most relevant and why the browser applies them, it will become naturally obvious whether or not to use this !important declaration.

Understanding the !important declaration before we use it

Before we consider using the !important notation, we must ensure that we follow the specificity rule and use the CSS cascade.

In the code below, we have the h2 and h3 elements styled to be a red color:

<h2 class="mytitle">This is heading II text</h2>
<h3 class="mytitle">This is heading III text</h3>

Then, .mytitle in CSS:

.mytitle {
  color: red;
}

But, let’s say at some point, we want to give the h3 element a blue color. Adding a style rule like the one below would not change the color because the class has more weight and it’s more specific than the element selector, as we’ve learned:

.mytitle {...}
h3 {
  color: blue;
}

However, using the !important on the lesser weight makes the browser enforce that declaration over other conflicting rules:

.mytitle {...}
h3 {
  color: blue !important;
}

This is because the !important notation increases the weight of the declaration in the cascade order of precedence. What this means is that we’ve disrupted the normal priority flow. Hence, bad practice, and can lead to difficulties in code maintenance and debugging.

If at some other point, we want to override the above important rule, we can apply another !important notation on a declaration with higher specificity (or the same if it is lower down in the source). It can then lead to something like this:

h3 {
  color: blue !important;
}

/* several lines of rules */

.mytitle {
  color: green !important;
}

This is bad and should be avoided. Instead, we should check if:

  1. Rearranging the rule or rewriting the selectors can solve the cascading issue
  2. Increasing the specificity of the target element can solve the issue

Well, let’s find out. Back to our style rules, we can enforce a blue color on the h3 element by increasing the specificity score.

As seen below, we can combine selectors until their specificity score supersedes the conflicting rule. The h3.mytitle selector gives a specificity score of 0011, which is more than the .mytitle of 0010 score:

.mytitle {...}
h3.mytitle {
  color: blue;
}

As we can see, instead of using the !important declaration to enforce a rule, we focus on increasing the specificity score.

:is() and other related pseudo-class functions

Sometimes, we may trace issues to a pseudo-class function. So, knowing how it works can save us a lot of stress. Let’s see another example.

Imagine we are working on a project and see the following code:

<h1 id="header">
  heading <span>span it</span>
  <a href="#">link it</a>
</h1>
<p class="paragraph">
  paragraph <span>span it</span>
  <a href="">link it</a>
</p>

Using the following CSS rules gives us the output after:

:is(#header, p) span,
:is(#header, p) a {
  color: red;
}

Output Heading Span It Link It

Now, let’s say we want to give the span and the link text in the paragraph another color of blue. We can do this by adding the following rule:

.paragraph span,
.paragraph a {
  color: blue;
}

The earlier rule will override the blue color despite being further down the line:

Blue Color

As a quick fix, we can enforce our blue color by using the !important notation like so:

:is(#header, p) span,
:is(#header, p) a {...}

.paragraph span,
.paragraph a {
  color: blue !important;
}

But, as you may guess, that is bad practice, so we must not be quick to use the !important notation. Instead, we can start by analyzing how every selector works. The :is() is used in the code is a pseudo-class function for writing mega selectors in a more compressed form.

So, here is the following rule in the above code:

:is(#header, p) span,
:is(#header, p) a {
  color: red;
}

Which is equivalent to the following:

#header span,
p span,
#header a,
p a {
  color: red;
}

So, why is .paragraph span and .paragraph a not overriding the color despite having a specificity score of 0011, which is higher than 0002 of the p span and p a.

Well, every selector in the :is() uses the highest specificity in the list of arguments. In that case, both the #header and the p in the :is(#header, p) uses the specificity score of the #header, which is 0100. Thus, the browser sticks to its value because it has a higher specificity.

Thus, anytime we see this type of conflict, we are better off not using the pseudo-class function and sticking to its equivalent like the following:

#header span,
p span,
#header a,
p a {
  color: red;
}

Now, we should be able to see the expected result without using the !important notation that disrupts cascade order.

Result With Important Notation

You can see for yourself on CodeSandbox.

When exactly can we use !important declaration?

Below are a few occasions where using the !important notation is recommended.

Utility classes

Assuming we want to style all buttons on a page to look the same, we can write a CSS rule that can be reused across a page. Let’s take a look at the following markup and style below:

<p>Subscribe button : <a class="btn" href="#">Subscribe</a></p>

<section class="content">
  <p>
    This <a href="#" class="btn">button</a> style is affected by a higher
    specificity value .
  </p>
  A link here: <a href="#">Dont click</a>
</section>

Followed by the CSS:

.btn {
  display: inline-block;
  background: #99f2f5;
  padding: 8px 10px;
  border: 1px solid #99f2f5;
  border-radius: 4px;
  color: black;
  font-weight: normal;
  text-decoration: none;
}

.content a {
  color: blue;
  font-weight: bold;
  text-decoration: underline;
}

In the above code, we can see that the button link within the section element is targeted by both selectors in the CSS. And, we learned that for conflicting rules, the browser will use the most specific rule. As we expect, .content a has a score of 0011 while .btn has a score of 0010.

The page will look like this:

Example Of Subscribe Page

In this case, we can enforce the .btn rule by adding the !important notation to the conflicting declarations like this:

.btn {
  /* ... */
  color: black !important;
  font-weight: normal !important;
  text-decoration: none !important;
}

The page now looks as we expect:

New Subscribe Page

See for yourself on CodeSandbox.

The style rules we cannot override

This mostly happens when we don’t have total control over the working code. Sometimes, when we work with a content management system like WordPress, we may find that an inline CSS style in our WordPress theme is overruling our custom style.

In this case, the !important declaration is handy to override the theme inline style.

Conclusion

The !important declaration is never meant to be used as we desire. We must only use it if absolutely necessary, such as a situation where we have less control over the code or very extreme cases in our own code.

Whether or not we use it depends on how we understand the core CSS mechanism, and in this tutorial, we covered that as well.

I hope you enjoyed reading this post. If you have questions or contributions, share your thought in the comment section and remember to share this tutorial around the web.

Source: https://blog.logrocket.com/understanding-css-important-declaration/

#css